book.tex 709 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338
  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. \end{array}
  813. }
  814. \newcommand{\LintASTRacket}{
  815. \begin{array}{rcl}
  816. \Type &::=& \key{Integer} \\
  817. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  818. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp}
  819. \end{array}
  820. }
  821. \newcommand{\LintGrammarPython}{
  822. \begin{array}{rcl}
  823. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  824. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  825. \end{array}
  826. }
  827. \newcommand{\LintASTPython}{
  828. \begin{array}{rcl}
  829. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  830. \itm{unaryop} &::= & \code{USub()} \\
  831. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  832. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  833. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  834. \end{array}
  835. }
  836. \begin{figure}[tp]
  837. \fbox{
  838. \begin{minipage}{0.96\textwidth}
  839. {\if\edition\racketEd
  840. \[
  841. \begin{array}{l}
  842. \LintGrammarRacket \\
  843. \begin{array}{rcl}
  844. \LangInt{} &::=& \Exp
  845. \end{array}
  846. \end{array}
  847. \]
  848. \fi}
  849. {\if\edition\pythonEd
  850. \[
  851. \begin{array}{l}
  852. \LintGrammarPython \\
  853. \begin{array}{rcl}
  854. \LangInt{} &::=& \Stmt^{*}
  855. \end{array}
  856. \end{array}
  857. \]
  858. \fi}
  859. \end{minipage}
  860. }
  861. \caption{The concrete syntax of \LangInt{}.}
  862. \label{fig:r0-concrete-syntax}
  863. \end{figure}
  864. \begin{figure}[tp]
  865. \fbox{
  866. \begin{minipage}{0.96\textwidth}
  867. {\if\edition\racketEd
  868. \[
  869. \begin{array}{l}
  870. \LintASTRacket{} \\
  871. \begin{array}{rcl}
  872. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  873. \end{array}
  874. \end{array}
  875. \]
  876. \fi}
  877. {\if\edition\pythonEd
  878. \[
  879. \begin{array}{l}
  880. \LintASTPython\\
  881. \begin{array}{rcl}
  882. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  883. \end{array}
  884. \end{array}
  885. \]
  886. \fi}
  887. \end{minipage}
  888. }
  889. \caption{The abstract syntax of \LangInt{}.}
  890. \label{fig:r0-syntax}
  891. \end{figure}
  892. \section{Pattern Matching}
  893. \label{sec:pattern-matching}
  894. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  895. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  896. \texttt{match} feature to access the parts of a value.
  897. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  898. \begin{center}
  899. \begin{minipage}{0.5\textwidth}
  900. {\if\edition\racketEd
  901. \begin{lstlisting}
  902. (match ast1_1
  903. [(Prim op (list child1 child2))
  904. (print op)])
  905. \end{lstlisting}
  906. \fi}
  907. {\if\edition\pythonEd
  908. \begin{lstlisting}
  909. match ast1_1:
  910. case BinOp(child1, op, child2):
  911. print(op)
  912. \end{lstlisting}
  913. \fi}
  914. \end{minipage}
  915. \end{center}
  916. {\if\edition\racketEd
  917. %
  918. In the above example, the \texttt{match} form checks whether the AST
  919. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  920. three pattern variables \texttt{op}, \texttt{child1}, and
  921. \texttt{child2}. In general, a match clause consists of a
  922. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  923. recursively defined to be either a pattern variable, a structure name
  924. followed by a pattern for each of the structure's arguments, or an
  925. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  926. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  927. and Chapter 9 of The Racket
  928. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  929. for complete descriptions of \code{match}.)
  930. %
  931. The body of a match clause may contain arbitrary Racket code. The
  932. pattern variables can be used in the scope of the body, such as
  933. \code{op} in \code{(print op)}.
  934. %
  935. \fi}
  936. %
  937. %
  938. {\if\edition\pythonEd
  939. %
  940. In the above example, the \texttt{match} form checks whether the AST
  941. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  942. three pattern variables \texttt{child1}, \texttt{op}, and
  943. \texttt{child2}, and then prints out the operator. In general, each
  944. \code{case} consists of a \emph{pattern} and a
  945. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  946. to be either a pattern variable, a class name followed by a pattern
  947. for each of its constructor's arguments, or other literals such as
  948. strings, lists, etc.
  949. %
  950. The body of each \code{case} may contain arbitrary Python code. The
  951. pattern variables can be used in the body, such as \code{op} in
  952. \code{print(op)}.
  953. %
  954. \fi}
  955. A \code{match} form may contain several clauses, as in the following
  956. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  957. the AST. The \code{match} proceeds through the clauses in order,
  958. checking whether the pattern can match the input AST. The body of the
  959. first clause that matches is executed. The output of \code{leaf} for
  960. several ASTs is shown on the right.
  961. \begin{center}
  962. \begin{minipage}{0.6\textwidth}
  963. {\if\edition\racketEd
  964. \begin{lstlisting}
  965. (define (leaf arith)
  966. (match arith
  967. [(Int n) #t]
  968. [(Prim 'read '()) #t]
  969. [(Prim '- (list e1)) #f]
  970. [(Prim '+ (list e1 e2)) #f]))
  971. (leaf (Prim 'read '()))
  972. (leaf (Prim '- (list (Int 8))))
  973. (leaf (Int 8))
  974. \end{lstlisting}
  975. \fi}
  976. {\if\edition\pythonEd
  977. \begin{lstlisting}
  978. def leaf(arith):
  979. match arith:
  980. case Constant(n):
  981. return True
  982. case Call(Name('input_int'), []):
  983. return True
  984. case UnaryOp(USub(), e1):
  985. return False
  986. case BinOp(e1, Add(), e2):
  987. return False
  988. print(leaf(Call(Name('input_int'), [])))
  989. print(leaf(UnaryOp(USub(), eight)))
  990. print(leaf(Constant(8)))
  991. \end{lstlisting}
  992. \fi}
  993. \end{minipage}
  994. \vrule
  995. \begin{minipage}{0.25\textwidth}
  996. {\if\edition\racketEd
  997. \begin{lstlisting}
  998. #t
  999. #f
  1000. #t
  1001. \end{lstlisting}
  1002. \fi}
  1003. {\if\edition\pythonEd
  1004. \begin{lstlisting}
  1005. True
  1006. False
  1007. True
  1008. \end{lstlisting}
  1009. \fi}
  1010. \end{minipage}
  1011. \end{center}
  1012. When constructing a \code{match} expression, we refer to the grammar
  1013. definition to identify which non-terminal we are expecting to match
  1014. against, then we make sure that 1) we have one
  1015. \racket{clause}\python{case} for each alternative of that non-terminal
  1016. and 2) that the pattern in each \racket{clause}\python{case}
  1017. corresponds to the corresponding right-hand side of a grammar
  1018. rule. For the \code{match} in the \code{leaf} function, we refer to
  1019. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1020. non-terminal has 4 alternatives, so the \code{match} has 4
  1021. \racket{clauses}\python{cases}. The pattern in each
  1022. \racket{clause}\python{case} corresponds to the right-hand side of a
  1023. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1024. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1025. translating from grammars to patterns, replace non-terminals such as
  1026. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1027. \code{e2}).
  1028. \section{Recursive Functions}
  1029. \label{sec:recursion}
  1030. \index{subject}{recursive function}
  1031. Programs are inherently recursive. For example, an expression is often
  1032. made of smaller expressions. Thus, the natural way to process an
  1033. entire program is with a recursive function. As a first example of
  1034. such a recursive function, we define the function \code{is\_exp} in
  1035. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1036. determines whether or not it is an expression in \LangInt{}.
  1037. %
  1038. We say that a function is defined by \emph{structural recursion} when
  1039. it is defined using a sequence of match \racket{clauses}\python{cases}
  1040. that correspond to a grammar, and the body of each
  1041. \racket{clause}\python{case} makes a recursive call on each child
  1042. node.\footnote{This principle of structuring code according to the
  1043. data definition is advocated in the book \emph{How to Design
  1044. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1045. second function, named \code{stmt}, that recognizes whether a value
  1046. is a \LangInt{} statement.} \python{Finally, }
  1047. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1048. which determines whether an AST is a program in \LangInt{}. In
  1049. general we can write one recursive function to handle each
  1050. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1051. two examples at the bottom of the figure, the first is in
  1052. \LangInt{} and the second is not.
  1053. \begin{figure}[tp]
  1054. {\if\edition\racketEd
  1055. \begin{lstlisting}
  1056. (define (is_exp ast)
  1057. (match ast
  1058. [(Int n) #t]
  1059. [(Prim 'read '()) #t]
  1060. [(Prim '- (list e)) (is_exp e)]
  1061. [(Prim '+ (list e1 e2))
  1062. (and (is_exp e1) (is_exp e2))]
  1063. [else #f]))
  1064. (define (is_Lint ast)
  1065. (match ast
  1066. [(Program '() e) (is_exp e)]
  1067. [else #f]))
  1068. (is_Lint (Program '() ast1_1)
  1069. (is_Lint (Program '()
  1070. (Prim '- (list (Prim 'read '())
  1071. (Prim '+ (list (Int 8)))))))
  1072. \end{lstlisting}
  1073. \fi}
  1074. {\if\edition\pythonEd
  1075. \begin{lstlisting}
  1076. def is_exp(e):
  1077. match e:
  1078. case Constant(n):
  1079. return True
  1080. case Call(Name('input_int'), []):
  1081. return True
  1082. case UnaryOp(USub(), e1):
  1083. return is_exp(e1)
  1084. case BinOp(e1, Add(), e2):
  1085. return is_exp(e1) and is_exp(e2)
  1086. case BinOp(e1, Sub(), e2):
  1087. return is_exp(e1) and is_exp(e2)
  1088. case _:
  1089. return False
  1090. def stmt(s):
  1091. match s:
  1092. case Expr(Call(Name('print'), [e])):
  1093. return is_exp(e)
  1094. case Expr(e):
  1095. return is_exp(e)
  1096. case _:
  1097. return False
  1098. def is_Lint(p):
  1099. match p:
  1100. case Module(body):
  1101. return all([stmt(s) for s in body])
  1102. case _:
  1103. return False
  1104. print(is_Lint(Module([Expr(ast1_1)])))
  1105. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1106. UnaryOp(Add(), Constant(8))))])))
  1107. \end{lstlisting}
  1108. \fi}
  1109. \caption{Example of recursive functions for \LangInt{}. These functions
  1110. recognize whether an AST is in \LangInt{}.}
  1111. \label{fig:exp-predicate}
  1112. \end{figure}
  1113. %% You may be tempted to merge the two functions into one, like this:
  1114. %% \begin{center}
  1115. %% \begin{minipage}{0.5\textwidth}
  1116. %% \begin{lstlisting}
  1117. %% (define (Lint ast)
  1118. %% (match ast
  1119. %% [(Int n) #t]
  1120. %% [(Prim 'read '()) #t]
  1121. %% [(Prim '- (list e)) (Lint e)]
  1122. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1123. %% [(Program '() e) (Lint e)]
  1124. %% [else #f]))
  1125. %% \end{lstlisting}
  1126. %% \end{minipage}
  1127. %% \end{center}
  1128. %% %
  1129. %% Sometimes such a trick will save a few lines of code, especially when
  1130. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1131. %% \emph{not} recommended because it can get you into trouble.
  1132. %% %
  1133. %% For example, the above function is subtly wrong:
  1134. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1135. %% returns true when it should return false.
  1136. \section{Interpreters}
  1137. \label{sec:interp_Lint}
  1138. \index{subject}{interpreter}
  1139. The behavior of a program is defined by the specification of the
  1140. programming language.
  1141. %
  1142. \racket{For example, the Scheme language is defined in the report by
  1143. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1144. reference manual~\citep{plt-tr}.}
  1145. %
  1146. \python{For example, the Python language is defined in the Python
  1147. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1148. %
  1149. In this book we use interpreters to specify each language that we
  1150. consider. An interpreter that is designated as the definition of a
  1151. language is called a \emph{definitional
  1152. interpreter}~\citep{reynolds72:_def_interp}.
  1153. \index{subject}{definitional interpreter} We warm up by creating a
  1154. definitional interpreter for the \LangInt{} language. This interpreter
  1155. serves as a second example of structural recursion. The
  1156. \code{interp\_Lint} function is defined in
  1157. Figure~\ref{fig:interp_Lint}.
  1158. %
  1159. \racket{The body of the function is a match on the input program
  1160. followed by a call to the \lstinline{interp_exp} helper function,
  1161. which in turn has one match clause per grammar rule for \LangInt{}
  1162. expressions.}
  1163. %
  1164. \python{The body of the function matches on the \code{Module} AST node
  1165. and then invokes \code{interp\_stmt} on each statement in the
  1166. module. The \code{interp\_stmt} function includes a case for each
  1167. grammar rule of the \Stmt{} non-terminal and it calls
  1168. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1169. function includes a case for each grammar rule of the \Exp{}
  1170. non-terminal.}
  1171. \begin{figure}[tp]
  1172. {\if\edition\racketEd
  1173. \begin{lstlisting}
  1174. (define (interp_exp e)
  1175. (match e
  1176. [(Int n) n]
  1177. [(Prim 'read '())
  1178. (define r (read))
  1179. (cond [(fixnum? r) r]
  1180. [else (error 'interp_exp "read expected an integer" r)])]
  1181. [(Prim '- (list e))
  1182. (define v (interp_exp e))
  1183. (fx- 0 v)]
  1184. [(Prim '+ (list e1 e2))
  1185. (define v1 (interp_exp e1))
  1186. (define v2 (interp_exp e2))
  1187. (fx+ v1 v2)]))
  1188. (define (interp_Lint p)
  1189. (match p
  1190. [(Program '() e) (interp_exp e)]))
  1191. \end{lstlisting}
  1192. \fi}
  1193. {\if\edition\pythonEd
  1194. \begin{lstlisting}
  1195. def interp_exp(e):
  1196. match e:
  1197. case BinOp(left, Add(), right):
  1198. l = interp_exp(left); r = interp_exp(right)
  1199. return l + r
  1200. case BinOp(left, Sub(), right):
  1201. l = interp_exp(left); r = interp_exp(right)
  1202. return l - r
  1203. case UnaryOp(USub(), v):
  1204. return - interp_exp(v)
  1205. case Constant(value):
  1206. return value
  1207. case Call(Name('input_int'), []):
  1208. return int(input())
  1209. def interp_stmt(s):
  1210. match s:
  1211. case Expr(Call(Name('print'), [arg])):
  1212. print(interp_exp(arg))
  1213. case Expr(value):
  1214. interp_exp(value)
  1215. def interp_Lint(p):
  1216. match p:
  1217. case Module(body):
  1218. for s in body:
  1219. interp_stmt(s)
  1220. \end{lstlisting}
  1221. \fi}
  1222. \caption{Interpreter for the \LangInt{} language.}
  1223. \label{fig:interp_Lint}
  1224. \end{figure}
  1225. Let us consider the result of interpreting a few \LangInt{} programs. The
  1226. following program adds two integers.
  1227. {\if\edition\racketEd
  1228. \begin{lstlisting}
  1229. (+ 10 32)
  1230. \end{lstlisting}
  1231. \fi}
  1232. {\if\edition\pythonEd
  1233. \begin{lstlisting}
  1234. print(10 + 32)
  1235. \end{lstlisting}
  1236. \fi}
  1237. %
  1238. \noindent The result is \key{42}, the answer to life, the universe,
  1239. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1240. the Galaxy} by Douglas Adams.}
  1241. %
  1242. We wrote the above program in concrete syntax whereas the parsed
  1243. abstract syntax is:
  1244. {\if\edition\racketEd
  1245. \begin{lstlisting}
  1246. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1247. \end{lstlisting}
  1248. \fi}
  1249. {\if\edition\pythonEd
  1250. \begin{lstlisting}
  1251. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1252. \end{lstlisting}
  1253. \fi}
  1254. The next example demonstrates that expressions may be nested within
  1255. each other, in this case nesting several additions and negations.
  1256. {\if\edition\racketEd
  1257. \begin{lstlisting}
  1258. (+ 10 (- (+ 12 20)))
  1259. \end{lstlisting}
  1260. \fi}
  1261. {\if\edition\pythonEd
  1262. \begin{lstlisting}
  1263. print(10 + -(12 + 20))
  1264. \end{lstlisting}
  1265. \fi}
  1266. %
  1267. \noindent What is the result of the above program?
  1268. {\if\edition\racketEd
  1269. As mentioned previously, the \LangInt{} language does not support
  1270. arbitrarily-large integers, but only $63$-bit integers, so we
  1271. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1272. in Racket.
  1273. Suppose
  1274. \[
  1275. n = 999999999999999999
  1276. \]
  1277. which indeed fits in $63$-bits. What happens when we run the
  1278. following program in our interpreter?
  1279. \begin{lstlisting}
  1280. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1281. \end{lstlisting}
  1282. It produces an error:
  1283. \begin{lstlisting}
  1284. fx+: result is not a fixnum
  1285. \end{lstlisting}
  1286. We establish the convention that if running the definitional
  1287. interpreter on a program produces an error then the meaning of that
  1288. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1289. error is a \code{trapped-error}. A compiler for the language is under
  1290. no obligations regarding programs with unspecified behavior; it does
  1291. not have to produce an executable, and if it does, that executable can
  1292. do anything. On the other hand, if the error is a
  1293. \code{trapped-error}, then the compiler must produce an executable and
  1294. it is required to report that an error occurred. To signal an error,
  1295. exit with a return code of \code{255}. The interpreters in chapters
  1296. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1297. \code{trapped-error}.
  1298. \fi}
  1299. % TODO: how to deal with too-large integers in the Python interpreter?
  1300. %% This convention applies to the languages defined in this
  1301. %% book, as a way to simplify the student's task of implementing them,
  1302. %% but this convention is not applicable to all programming languages.
  1303. %%
  1304. Moving on to the last feature of the \LangInt{} language, the
  1305. \READOP{} operation prompts the user of the program for an integer.
  1306. Recall that program \eqref{eq:arith-prog} requests an integer input
  1307. and then subtracts \code{8}. So if we run
  1308. {\if\edition\racketEd
  1309. \begin{lstlisting}
  1310. (interp_Lint (Program '() ast1_1))
  1311. \end{lstlisting}
  1312. \fi}
  1313. {\if\edition\pythonEd
  1314. \begin{lstlisting}
  1315. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1316. \end{lstlisting}
  1317. \fi}
  1318. \noindent and if the input is \code{50}, the result is \code{42}.
  1319. We include the \READOP{} operation in \LangInt{} so a clever student
  1320. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1321. during compilation to obtain the output and then generates the trivial
  1322. code to produce the output.\footnote{Yes, a clever student did this in the
  1323. first instance of this course!}
  1324. The job of a compiler is to translate a program in one language into a
  1325. program in another language so that the output program behaves the
  1326. same way as the input program. This idea is depicted in the
  1327. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1328. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1329. Given a compiler that translates from language $\mathcal{L}_1$ to
  1330. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1331. compiler must translate it into some program $P_2$ such that
  1332. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1333. same input $i$ yields the same output $o$.
  1334. \begin{equation} \label{eq:compile-correct}
  1335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1336. \node (p1) at (0, 0) {$P_1$};
  1337. \node (p2) at (3, 0) {$P_2$};
  1338. \node (o) at (3, -2.5) {$o$};
  1339. \path[->] (p1) edge [above] node {compile} (p2);
  1340. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1341. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1342. \end{tikzpicture}
  1343. \end{equation}
  1344. In the next section we see our first example of a compiler.
  1345. \section{Example Compiler: a Partial Evaluator}
  1346. \label{sec:partial-evaluation}
  1347. In this section we consider a compiler that translates \LangInt{}
  1348. programs into \LangInt{} programs that may be more efficient. The
  1349. compiler eagerly computes the parts of the program that do not depend
  1350. on any inputs, a process known as \emph{partial
  1351. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1352. For example, given the following program
  1353. {\if\edition\racketEd
  1354. \begin{lstlisting}
  1355. (+ (read) (- (+ 5 3)))
  1356. \end{lstlisting}
  1357. \fi}
  1358. {\if\edition\pythonEd
  1359. \begin{lstlisting}
  1360. print(input_int() + -(5 + 3) )
  1361. \end{lstlisting}
  1362. \fi}
  1363. \noindent our compiler translates it into the program
  1364. {\if\edition\racketEd
  1365. \begin{lstlisting}
  1366. (+ (read) -8)
  1367. \end{lstlisting}
  1368. \fi}
  1369. {\if\edition\pythonEd
  1370. \begin{lstlisting}
  1371. print(input_int() + -8)
  1372. \end{lstlisting}
  1373. \fi}
  1374. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1375. evaluator for the \LangInt{} language. The output of the partial evaluator
  1376. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1377. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1378. whereas the code for partially evaluating the negation and addition
  1379. operations is factored into two auxiliary functions:
  1380. \code{pe\_neg} and \code{pe\_add}. The input to these
  1381. functions is the output of partially evaluating the children.
  1382. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1383. arguments are integers and if they are, perform the appropriate
  1384. arithmetic. Otherwise, they create an AST node for the arithmetic
  1385. operation.
  1386. \begin{figure}[tp]
  1387. {\if\edition\racketEd
  1388. \begin{lstlisting}
  1389. (define (pe_neg r)
  1390. (match r
  1391. [(Int n) (Int (fx- 0 n))]
  1392. [else (Prim '- (list r))]))
  1393. (define (pe_add r1 r2)
  1394. (match* (r1 r2)
  1395. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1396. [(_ _) (Prim '+ (list r1 r2))]))
  1397. (define (pe_exp e)
  1398. (match e
  1399. [(Int n) (Int n)]
  1400. [(Prim 'read '()) (Prim 'read '())]
  1401. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1402. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1403. (define (pe_Lint p)
  1404. (match p
  1405. [(Program '() e) (Program '() (pe_exp e))]))
  1406. \end{lstlisting}
  1407. \fi}
  1408. {\if\edition\pythonEd
  1409. \begin{lstlisting}
  1410. def pe_neg(r):
  1411. match r:
  1412. case Constant(n):
  1413. return Constant(-n)
  1414. case _:
  1415. return UnaryOp(USub(), r)
  1416. def pe_add(r1, r2):
  1417. match (r1, r2):
  1418. case (Constant(n1), Constant(n2)):
  1419. return Constant(n1 + n2)
  1420. case _:
  1421. return BinOp(r1, Add(), r2)
  1422. def pe_sub(r1, r2):
  1423. match (r1, r2):
  1424. case (Constant(n1), Constant(n2)):
  1425. return Constant(n1 - n2)
  1426. case _:
  1427. return BinOp(r1, Sub(), r2)
  1428. def pe_exp(e):
  1429. match e:
  1430. case BinOp(left, Add(), right):
  1431. return pe_add(pe_exp(left), pe_exp(right))
  1432. case BinOp(left, Sub(), right):
  1433. return pe_sub(pe_exp(left), pe_exp(right))
  1434. case UnaryOp(USub(), v):
  1435. return pe_neg(pe_exp(v))
  1436. case Constant(value):
  1437. return e
  1438. case Call(Name('input_int'), []):
  1439. return e
  1440. def pe_stmt(s):
  1441. match s:
  1442. case Expr(Call(Name('print'), [arg])):
  1443. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1444. case Expr(value):
  1445. return Expr(pe_exp(value))
  1446. def pe_P_int(p):
  1447. match p:
  1448. case Module(body):
  1449. new_body = [pe_stmt(s) for s in body]
  1450. return Module(new_body)
  1451. \end{lstlisting}
  1452. \fi}
  1453. \caption{A partial evaluator for \LangInt{}.}
  1454. \label{fig:pe-arith}
  1455. \end{figure}
  1456. To gain some confidence that the partial evaluator is correct, we can
  1457. test whether it produces programs that produce the same result as the
  1458. input programs. That is, we can test whether it satisfies Diagram
  1459. \ref{eq:compile-correct}.
  1460. %
  1461. {\if\edition\racketEd
  1462. The following code runs the partial evaluator on several examples and
  1463. tests the output program. The \texttt{parse-program} and
  1464. \texttt{assert} functions are defined in
  1465. Appendix~\ref{appendix:utilities}.\\
  1466. \begin{minipage}{1.0\textwidth}
  1467. \begin{lstlisting}
  1468. (define (test_pe p)
  1469. (assert "testing pe_Lint"
  1470. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1471. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1472. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1473. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1474. \end{lstlisting}
  1475. \end{minipage}
  1476. \fi}
  1477. % TODO: python version of testing the PE
  1478. \begin{exercise}\normalfont
  1479. Create three programs in the \LangInt{} language and test whether
  1480. partially evaluating them with \code{pe\_Lint} and then
  1481. interpreting them with \code{interp\_Lint} gives the same result
  1482. as directly interpreting them with \code{interp\_Lint}.
  1483. \end{exercise}
  1484. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1485. \chapter{Integers and Variables}
  1486. \label{ch:Lvar}
  1487. This chapter is about compiling a subset of
  1488. \racket{Racket}\python{Python} to x86-64 assembly
  1489. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1490. integer arithmetic and local variables. We often refer to x86-64
  1491. simply as x86. The chapter begins with a description of the
  1492. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1493. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1494. large so we discuss only the instructions needed for compiling
  1495. \LangVar{}. We introduce more x86 instructions in later chapters.
  1496. After introducing \LangVar{} and x86, we reflect on their differences
  1497. and come up with a plan to break down the translation from \LangVar{}
  1498. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1499. rest of the sections in this chapter give detailed hints regarding
  1500. each step. We hope to give enough hints that the well-prepared
  1501. reader, together with a few friends, can implement a compiler from
  1502. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1503. the scale of this first compiler, the instructor solution for the
  1504. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1505. code.
  1506. \section{The \LangVar{} Language}
  1507. \label{sec:s0}
  1508. \index{subject}{variable}
  1509. The \LangVar{} language extends the \LangInt{} language with
  1510. variables. The concrete syntax of the \LangVar{} language is defined
  1511. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1512. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1513. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1514. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1515. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1516. syntax of \LangVar{} includes the \racket{\key{Program}
  1517. struct}\python{\key{Module} instance} to mark the top of the
  1518. program.
  1519. %% The $\itm{info}$
  1520. %% field of the \key{Program} structure contains an \emph{association
  1521. %% list} (a list of key-value pairs) that is used to communicate
  1522. %% auxiliary data from one compiler pass the next.
  1523. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1524. exhibit several compilation techniques.
  1525. \newcommand{\LvarGrammarRacket}{
  1526. \begin{array}{rcl}
  1527. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1528. \end{array}
  1529. }
  1530. \newcommand{\LvarASTRacket}{
  1531. \begin{array}{rcl}
  1532. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1533. \end{array}
  1534. }
  1535. \newcommand{\LvarGrammarPython}{
  1536. \begin{array}{rcl}
  1537. \Exp &::=& \Var{} \\
  1538. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1539. \end{array}
  1540. }
  1541. \newcommand{\LvarASTPython}{
  1542. \begin{array}{rcl}
  1543. \Exp{} &::=& \VAR{\Var{}} \\
  1544. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1545. \end{array}
  1546. }
  1547. \begin{figure}[tp]
  1548. \centering
  1549. \fbox{
  1550. \begin{minipage}{0.96\textwidth}
  1551. {\if\edition\racketEd
  1552. \[
  1553. \begin{array}{l}
  1554. \gray{\LintGrammarRacket{}} \\ \hline
  1555. \LvarGrammarRacket{} \\
  1556. \begin{array}{rcl}
  1557. \LangVarM{} &::=& \Exp
  1558. \end{array}
  1559. \end{array}
  1560. \]
  1561. \fi}
  1562. {\if\edition\pythonEd
  1563. \[
  1564. \begin{array}{l}
  1565. \gray{\LintGrammarPython} \\ \hline
  1566. \LvarGrammarPython \\
  1567. \begin{array}{rcl}
  1568. \LangVarM{} &::=& \Stmt^{*}
  1569. \end{array}
  1570. \end{array}
  1571. \]
  1572. \fi}
  1573. \end{minipage}
  1574. }
  1575. \caption{The concrete syntax of \LangVar{}.}
  1576. \label{fig:Lvar-concrete-syntax}
  1577. \end{figure}
  1578. \begin{figure}[tp]
  1579. \centering
  1580. \fbox{
  1581. \begin{minipage}{0.96\textwidth}
  1582. {\if\edition\racketEd
  1583. \[
  1584. \begin{array}{l}
  1585. \gray{\LintASTRacket{}} \\ \hline
  1586. \LvarASTRacket \\
  1587. \begin{array}{rcl}
  1588. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1589. \end{array}
  1590. \end{array}
  1591. \]
  1592. \fi}
  1593. {\if\edition\pythonEd
  1594. \[
  1595. \begin{array}{l}
  1596. \gray{\LintASTPython}\\ \hline
  1597. \LvarASTPython \\
  1598. \begin{array}{rcl}
  1599. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1600. \end{array}
  1601. \end{array}
  1602. \]
  1603. \fi}
  1604. \end{minipage}
  1605. }
  1606. \caption{The abstract syntax of \LangVar{}.}
  1607. \label{fig:Lvar-syntax}
  1608. \end{figure}
  1609. {\if\edition\racketEd
  1610. Let us dive further into the syntax and semantics of the \LangVar{}
  1611. language. The \key{let} feature defines a variable for use within its
  1612. body and initializes the variable with the value of an expression.
  1613. The abstract syntax for \key{let} is defined in
  1614. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1615. \begin{lstlisting}
  1616. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1617. \end{lstlisting}
  1618. For example, the following program initializes \code{x} to $32$ and then
  1619. evaluates the body \code{(+ 10 x)}, producing $42$.
  1620. \begin{lstlisting}
  1621. (let ([x (+ 12 20)]) (+ 10 x))
  1622. \end{lstlisting}
  1623. \fi}
  1624. %
  1625. {\if\edition\pythonEd
  1626. %
  1627. The \LangVar{} language includes assignment statements, which define a
  1628. variable for use in later statements and initializes the variable with
  1629. the value of an expression. The abstract syntax for assignment is
  1630. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1631. assignment is
  1632. \begin{lstlisting}
  1633. |$\itm{var}$| = |$\itm{exp}$|
  1634. \end{lstlisting}
  1635. For example, the following program initializes the variable \code{x}
  1636. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1637. \begin{lstlisting}
  1638. x = 12 + 20
  1639. print(10 + x)
  1640. \end{lstlisting}
  1641. \fi}
  1642. {\if\edition\racketEd
  1643. %
  1644. When there are multiple \key{let}'s for the same variable, the closest
  1645. enclosing \key{let} is used. That is, variable definitions overshadow
  1646. prior definitions. Consider the following program with two \key{let}'s
  1647. that define variables named \code{x}. Can you figure out the result?
  1648. \begin{lstlisting}
  1649. (let ([x 32]) (+ (let ([x 10]) x) x))
  1650. \end{lstlisting}
  1651. For the purposes of depicting which variable uses correspond to which
  1652. definitions, the following shows the \code{x}'s annotated with
  1653. subscripts to distinguish them. Double check that your answer for the
  1654. above is the same as your answer for this annotated version of the
  1655. program.
  1656. \begin{lstlisting}
  1657. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1658. \end{lstlisting}
  1659. The initializing expression is always evaluated before the body of the
  1660. \key{let}, so in the following, the \key{read} for \code{x} is
  1661. performed before the \key{read} for \code{y}. Given the input
  1662. $52$ then $10$, the following produces $42$ (not $-42$).
  1663. \begin{lstlisting}
  1664. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1665. \end{lstlisting}
  1666. \fi}
  1667. \subsection{Extensible Interpreters via Method Overriding}
  1668. \label{sec:extensible-interp}
  1669. To prepare for discussing the interpreter of \LangVar{}, we explain
  1670. why we implement it in an object-oriented style. Throughout this book
  1671. we define many interpreters, one for each of language that we
  1672. study. Because each language builds on the prior one, there is a lot
  1673. of commonality between these interpreters. We want to write down the
  1674. common parts just once instead of many times. A naive approach would
  1675. be for the interpreter of \LangVar{} to handle the
  1676. \racket{cases for variables and \code{let}}
  1677. \python{case for variables}
  1678. but dispatch to \LangInt{}
  1679. for the rest of the cases. The following code sketches this idea. (We
  1680. explain the \code{env} parameter soon, in
  1681. Section~\ref{sec:interp-Lvar}.)
  1682. \begin{center}
  1683. {\if\edition\racketEd
  1684. \begin{minipage}{0.45\textwidth}
  1685. \begin{lstlisting}
  1686. (define ((interp_Lint env) e)
  1687. (match e
  1688. [(Prim '- (list e1))
  1689. (fx- 0 ((interp_Lint env) e1))]
  1690. ...))
  1691. \end{lstlisting}
  1692. \end{minipage}
  1693. \begin{minipage}{0.45\textwidth}
  1694. \begin{lstlisting}
  1695. (define ((interp_Lvar env) e)
  1696. (match e
  1697. [(Var x)
  1698. (dict-ref env x)]
  1699. [(Let x e body)
  1700. (define v ((interp_exp env) e))
  1701. (define env^ (dict-set env x v))
  1702. ((interp_exp env^) body)]
  1703. [else ((interp_Lint env) e)]))
  1704. \end{lstlisting}
  1705. \end{minipage}
  1706. \fi}
  1707. {\if\edition\pythonEd
  1708. \begin{minipage}{0.45\textwidth}
  1709. \begin{lstlisting}
  1710. def interp_Lint(e, env):
  1711. match e:
  1712. case UnaryOp(USub(), e1):
  1713. return - interp_Lint(e1, env)
  1714. ...
  1715. \end{lstlisting}
  1716. \end{minipage}
  1717. \begin{minipage}{0.45\textwidth}
  1718. \begin{lstlisting}
  1719. def interp_Lvar(e, env):
  1720. match e:
  1721. case Name(id):
  1722. return env[id]
  1723. case _:
  1724. return interp_Lint(e, env)
  1725. \end{lstlisting}
  1726. \end{minipage}
  1727. \fi}
  1728. \end{center}
  1729. The problem with this approach is that it does not handle situations
  1730. in which an \LangVar{} feature, such as a variable, is nested inside
  1731. an \LangInt{} feature, like the \code{-} operator, as in the following
  1732. program.
  1733. %
  1734. {\if\edition\racketEd
  1735. \begin{lstlisting}
  1736. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1737. \end{lstlisting}
  1738. \fi}
  1739. {\if\edition\pythonEd
  1740. \begin{lstlisting}
  1741. y = 10
  1742. print(-y)
  1743. \end{lstlisting}
  1744. \fi}
  1745. %
  1746. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1747. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1748. then it recursively calls \code{interp\_Lint} again on its argument.
  1749. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1750. an error!
  1751. To make our interpreters extensible we need something called
  1752. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1753. recursive knot is delayed to when the functions are
  1754. composed. Object-oriented languages provide open recursion via
  1755. method overriding\index{subject}{method overriding}. The
  1756. following code uses method overriding to interpret \LangInt{} and
  1757. \LangVar{} using
  1758. %
  1759. \racket{the
  1760. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1761. \index{subject}{class} feature of Racket}
  1762. %
  1763. \python{a Python \code{class} definition}.
  1764. %
  1765. We define one class for each language and define a method for
  1766. interpreting expressions inside each class. The class for \LangVar{}
  1767. inherits from the class for \LangInt{} and the method
  1768. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1769. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1770. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1771. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1772. \code{interp\_exp} in \LangInt{}.
  1773. \begin{center}
  1774. \hspace{-20pt}
  1775. {\if\edition\racketEd
  1776. \begin{minipage}{0.45\textwidth}
  1777. \begin{lstlisting}
  1778. (define interp_Lint_class
  1779. (class object%
  1780. (define/public ((interp_exp env) e)
  1781. (match e
  1782. [(Prim '- (list e))
  1783. (fx- 0 ((interp_exp env) e))]
  1784. ...))
  1785. ...))
  1786. \end{lstlisting}
  1787. \end{minipage}
  1788. \begin{minipage}{0.45\textwidth}
  1789. \begin{lstlisting}
  1790. (define interp_Lvar_class
  1791. (class interp_Lint_class
  1792. (define/override ((interp_exp env) e)
  1793. (match e
  1794. [(Var x)
  1795. (dict-ref env x)]
  1796. [(Let x e body)
  1797. (define v ((interp_exp env) e))
  1798. (define env^ (dict-set env x v))
  1799. ((interp_exp env^) body)]
  1800. [else
  1801. (super (interp_exp env) e)]))
  1802. ...
  1803. ))
  1804. \end{lstlisting}
  1805. \end{minipage}
  1806. \fi}
  1807. {\if\edition\pythonEd
  1808. \begin{minipage}{0.45\textwidth}
  1809. \begin{lstlisting}
  1810. class InterpLint:
  1811. def interp_exp(e):
  1812. match e:
  1813. case UnaryOp(USub(), e1):
  1814. return -self.interp_exp(e1)
  1815. ...
  1816. ...
  1817. \end{lstlisting}
  1818. \end{minipage}
  1819. \begin{minipage}{0.45\textwidth}
  1820. \begin{lstlisting}
  1821. def InterpLvar(InterpLint):
  1822. def interp_exp(e):
  1823. match e:
  1824. case Name(id):
  1825. return env[id]
  1826. case _:
  1827. return super().interp_exp(e)
  1828. ...
  1829. \end{lstlisting}
  1830. \end{minipage}
  1831. \fi}
  1832. \end{center}
  1833. Getting back to the troublesome example, repeated here:
  1834. {\if\edition\racketEd
  1835. \begin{lstlisting}
  1836. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1837. \end{lstlisting}
  1838. \fi}
  1839. {\if\edition\pythonEd
  1840. \begin{lstlisting}
  1841. y = 10
  1842. print(-y)
  1843. \end{lstlisting}
  1844. \fi}
  1845. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1846. \racket{on this expression,}
  1847. \python{on the \code{-y} expression,}
  1848. %
  1849. call it \code{e0}, by creating an object of the \LangVar{} class
  1850. and calling the \code{interp\_exp} method.
  1851. {\if\edition\racketEd
  1852. \begin{lstlisting}
  1853. (send (new interp_Lvar_class) interp_exp e0)
  1854. \end{lstlisting}
  1855. \fi}
  1856. {\if\edition\pythonEd
  1857. \begin{lstlisting}
  1858. InterpLvar().interp_exp(e0)
  1859. \end{lstlisting}
  1860. \fi}
  1861. \noindent To process the \code{-} operator, the default case of
  1862. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1863. method in \LangInt{}. But then for the recursive method call, it
  1864. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1865. \code{Var} node is handled correctly. Thus, method overriding gives us
  1866. the open recursion that we need to implement our interpreters in an
  1867. extensible way.
  1868. \subsection{Definitional Interpreter for \LangVar{}}
  1869. \label{sec:interp-Lvar}
  1870. {\if\edition\racketEd
  1871. \begin{figure}[tp]
  1872. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1873. \small
  1874. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1875. An \emph{association list} (alist) is a list of key-value pairs.
  1876. For example, we can map people to their ages with an alist.
  1877. \index{subject}{alist}\index{subject}{association list}
  1878. \begin{lstlisting}[basicstyle=\ttfamily]
  1879. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1880. \end{lstlisting}
  1881. The \emph{dictionary} interface is for mapping keys to values.
  1882. Every alist implements this interface. \index{subject}{dictionary} The package
  1883. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1884. provides many functions for working with dictionaries. Here
  1885. are a few of them:
  1886. \begin{description}
  1887. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1888. returns the value associated with the given $\itm{key}$.
  1889. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1890. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1891. but otherwise is the same as $\itm{dict}$.
  1892. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1893. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1894. of keys and values in $\itm{dict}$. For example, the following
  1895. creates a new alist in which the ages are incremented.
  1896. \end{description}
  1897. \vspace{-10pt}
  1898. \begin{lstlisting}[basicstyle=\ttfamily]
  1899. (for/list ([(k v) (in-dict ages)])
  1900. (cons k (add1 v)))
  1901. \end{lstlisting}
  1902. \end{tcolorbox}
  1903. %\end{wrapfigure}
  1904. \caption{Association lists implement the dictionary interface.}
  1905. \label{fig:alist}
  1906. \end{figure}
  1907. \fi}
  1908. Having justified the use of classes and methods to implement
  1909. interpreters, we revisit the definitional interpreter for \LangInt{}
  1910. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1911. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1912. interpreter for \LangVar{} adds two new \key{match} cases for
  1913. variables and \racket{\key{let}}\python{assignment}. For
  1914. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1915. value bound to a variable to all the uses of the variable. To
  1916. accomplish this, we maintain a mapping from variables to values
  1917. called an \emph{environment}\index{subject}{environment}.
  1918. %
  1919. We use%
  1920. %
  1921. \racket{an association list (alist)}
  1922. %
  1923. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary}}
  1924. %
  1925. to represent the environment.
  1926. %
  1927. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1928. and the \code{racket/dict} package.}
  1929. %
  1930. The \code{interp\_exp} function takes the current environment,
  1931. \code{env}, as an extra parameter. When the interpreter encounters a
  1932. variable, it looks up the corresponding value in the dictionary.
  1933. %
  1934. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1935. initializing expression, extends the environment with the result
  1936. value bound to the variable, using \code{dict-set}, then evaluates
  1937. the body of the \key{Let}.}
  1938. %
  1939. \python{When the interpreter encounters an assignment, it evaluates
  1940. the initializing expression and then associates the resulting value
  1941. with the variable in the environment.}
  1942. \begin{figure}[tp]
  1943. {\if\edition\racketEd
  1944. \begin{lstlisting}
  1945. (define interp_Lint_class
  1946. (class object%
  1947. (super-new)
  1948. (define/public ((interp_exp env) e)
  1949. (match e
  1950. [(Int n) n]
  1951. [(Prim 'read '())
  1952. (define r (read))
  1953. (cond [(fixnum? r) r]
  1954. [else (error 'interp_exp "expected an integer" r)])]
  1955. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1956. [(Prim '+ (list e1 e2))
  1957. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]))
  1958. (define/public (interp_program p)
  1959. (match p
  1960. [(Program '() e) ((interp_exp '()) e)]))
  1961. ))
  1962. \end{lstlisting}
  1963. \fi}
  1964. {\if\edition\pythonEd
  1965. \begin{lstlisting}
  1966. class InterpLint:
  1967. def interp_exp(self, e, env):
  1968. match e:
  1969. case BinOp(left, Add(), right):
  1970. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1971. case UnaryOp(USub(), v):
  1972. return - self.interp_exp(v, env)
  1973. case Constant(value):
  1974. return value
  1975. case Call(Name('input_int'), []):
  1976. return int(input())
  1977. def interp_stmts(self, ss, env):
  1978. if len(ss) == 0:
  1979. return
  1980. match ss[0]:
  1981. case Expr(Call(Name('print'), [arg])):
  1982. print(self.interp_exp(arg, env), end='')
  1983. return self.interp_stmts(ss[1:], env)
  1984. case Expr(value):
  1985. self.interp_exp(value, env)
  1986. return self.interp_stmts(ss[1:], env)
  1987. def interp(self, p):
  1988. match p:
  1989. case Module(body):
  1990. self.interp_stmts(body, {})
  1991. def interp_Lint(p):
  1992. return InterpLint().interp(p)
  1993. \end{lstlisting}
  1994. \fi}
  1995. \caption{Interpreter for \LangInt{} as a class.}
  1996. \label{fig:interp-Lint-class}
  1997. \end{figure}
  1998. \begin{figure}[tp]
  1999. {\if\edition\racketEd
  2000. \begin{lstlisting}
  2001. (define interp_Lvar_class
  2002. (class interp_Lint_class
  2003. (super-new)
  2004. (define/override ((interp_exp env) e)
  2005. (match e
  2006. [(Var x) (dict-ref env x)]
  2007. [(Let x e body)
  2008. (define new-env (dict-set env x ((interp_exp env) e)))
  2009. ((interp_exp new-env) body)]
  2010. [else ((super interp-exp env) e)]))
  2011. ))
  2012. (define (interp_Lvar p)
  2013. (send (new interp_Lvar_class) interp_program p))
  2014. \end{lstlisting}
  2015. \fi}
  2016. {\if\edition\pythonEd
  2017. \begin{lstlisting}
  2018. class InterpLvar(InterpLint):
  2019. def interp_exp(self, e, env):
  2020. match e:
  2021. case Name(id):
  2022. return env[id]
  2023. case _:
  2024. return super().interp_exp(e, env)
  2025. def interp_stmts(self, ss, env):
  2026. if len(ss) == 0:
  2027. return
  2028. match ss[0]:
  2029. case Assign([lhs], value):
  2030. env[lhs.id] = self.interp_exp(value, env)
  2031. return self.interp_stmts(ss[1:], env)
  2032. case _:
  2033. return super().interp_stmts(ss, env)
  2034. def interp_Lvar(p):
  2035. return InterpLvar().interp(p)
  2036. \end{lstlisting}
  2037. \fi}
  2038. \caption{Interpreter for the \LangVar{} language.}
  2039. \label{fig:interp-Lvar}
  2040. \end{figure}
  2041. The goal for this chapter is to implement a compiler that translates
  2042. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2043. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2044. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2045. That is, they output the same integer $n$. We depict this correctness
  2046. criteria in the following diagram.
  2047. \[
  2048. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2049. \node (p1) at (0, 0) {$P_1$};
  2050. \node (p2) at (4, 0) {$P_2$};
  2051. \node (o) at (4, -2) {$n$};
  2052. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2053. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2054. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2055. \end{tikzpicture}
  2056. \]
  2057. In the next section we introduce the \LangXInt{} subset of x86 that
  2058. suffices for compiling \LangVar{}.
  2059. \section{The \LangXInt{} Assembly Language}
  2060. \label{sec:x86}
  2061. \index{subject}{x86}
  2062. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2063. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2064. assembler.
  2065. %
  2066. A program begins with a \code{main} label followed by a sequence of
  2067. instructions. The \key{globl} directive says that the \key{main}
  2068. procedure is externally visible, which is necessary so that the
  2069. operating system can call it.
  2070. %
  2071. An x86 program is stored in the computer's memory. For our purposes,
  2072. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2073. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2074. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2075. the address of the next instruction to be executed. For most
  2076. instructions, the program counter is incremented after the instruction
  2077. is executed, so it points to the next instruction in memory. Most x86
  2078. instructions take two operands, where each operand is either an
  2079. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2080. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2081. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2082. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2083. && \key{r8} \MID \key{r9} \MID \key{r10}
  2084. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2085. \MID \key{r14} \MID \key{r15}}
  2086. \begin{figure}[tp]
  2087. \fbox{
  2088. \begin{minipage}{0.96\textwidth}
  2089. {\if\edition\racketEd
  2090. \[
  2091. \begin{array}{lcl}
  2092. \Reg &::=& \allregisters{} \\
  2093. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2094. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2095. \key{subq} \; \Arg\key{,} \Arg \MID
  2096. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2097. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2098. \key{callq} \; \mathit{label} \MID
  2099. \key{retq} \MID
  2100. \key{jmp}\,\itm{label} \MID \\
  2101. && \itm{label}\key{:}\; \Instr \\
  2102. \LangXIntM{} &::= & \key{.globl main}\\
  2103. & & \key{main:} \; \Instr\ldots
  2104. \end{array}
  2105. \]
  2106. \fi}
  2107. {\if\edition\pythonEd
  2108. \[
  2109. \begin{array}{lcl}
  2110. \Reg &::=& \allregisters{} \\
  2111. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2112. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2113. \key{subq} \; \Arg\key{,} \Arg \MID
  2114. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2115. && \key{callq} \; \mathit{label} \MID
  2116. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2117. \LangXIntM{} &::= & \key{.globl main}\\
  2118. & & \key{main:} \; \Instr^{*}
  2119. \end{array}
  2120. \]
  2121. \fi}
  2122. \end{minipage}
  2123. }
  2124. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2125. \label{fig:x86-int-concrete}
  2126. \end{figure}
  2127. A register is a special kind of variable that holds a 64-bit
  2128. value. There are 16 general-purpose registers in the computer and
  2129. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2130. is written with a \key{\%} followed by the register name, such as
  2131. \key{\%rax}.
  2132. An immediate value is written using the notation \key{\$}$n$ where $n$
  2133. is an integer.
  2134. %
  2135. %
  2136. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2137. which obtains the address stored in register $r$ and then adds $n$
  2138. bytes to the address. The resulting address is used to load or store
  2139. to memory depending on whether it occurs as a source or destination
  2140. argument of an instruction.
  2141. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2142. source $s$ and destination $d$, applies the arithmetic operation, then
  2143. writes the result back to the destination $d$. \index{subject}{instruction}
  2144. %
  2145. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2146. stores the result in $d$.
  2147. %
  2148. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2149. specified by the label and $\key{retq}$ returns from a procedure to
  2150. its caller.
  2151. %
  2152. We discuss procedure calls in more detail later in this chapter and in
  2153. Chapter~\ref{ch:Lfun}.
  2154. %
  2155. The last letter \key{q} indicates that these instructions operate on
  2156. quadwords, i.e., 64-bit values.
  2157. %
  2158. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2159. counter to the address of the instruction after the specified
  2160. label.}
  2161. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2162. all of the x86 instructions used in this book.
  2163. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2164. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2165. \lstinline{movq $10, %rax}
  2166. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2167. adds $32$ to the $10$ in \key{rax} and
  2168. puts the result, $42$, back into \key{rax}.
  2169. %
  2170. The last instruction, \key{retq}, finishes the \key{main} function by
  2171. returning the integer in \key{rax} to the operating system. The
  2172. operating system interprets this integer as the program's exit
  2173. code. By convention, an exit code of 0 indicates that a program
  2174. completed successfully, and all other exit codes indicate various
  2175. errors.
  2176. %
  2177. \racket{Nevertheless, in this book we return the result of the program
  2178. as the exit code.}
  2179. \begin{figure}[tbp]
  2180. \begin{lstlisting}
  2181. .globl main
  2182. main:
  2183. movq $10, %rax
  2184. addq $32, %rax
  2185. retq
  2186. \end{lstlisting}
  2187. \caption{An x86 program that computes
  2188. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2189. \label{fig:p0-x86}
  2190. \end{figure}
  2191. We exhibit the use of memory for storing intermediate results in the
  2192. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2193. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2194. uses a region of memory called the \emph{procedure call stack} (or
  2195. \emph{stack} for
  2196. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2197. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2198. for each procedure call. The memory layout for an individual frame is
  2199. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2200. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2201. address of the item at the top of the stack. In general, we use the
  2202. term \emph{pointer}\index{subject}{pointer} for something that
  2203. contains an address. The stack grows downward in memory, so we
  2204. increase the size of the stack by subtracting from the stack pointer.
  2205. In the context of a procedure call, the \emph{return
  2206. address}\index{subject}{return address} is the instruction after the
  2207. call instruction on the caller side. The function call instruction,
  2208. \code{callq}, pushes the return address onto the stack prior to
  2209. jumping to the procedure. The register \key{rbp} is the \emph{base
  2210. pointer}\index{subject}{base pointer} and is used to access variables
  2211. that are stored in the frame of the current procedure call. The base
  2212. pointer of the caller is store after the return address. In
  2213. Figure~\ref{fig:frame} we number the variables from $1$ to
  2214. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2215. at $-16\key{(\%rbp)}$, etc.
  2216. \begin{figure}[tbp]
  2217. {\if\edition\racketEd
  2218. \begin{lstlisting}
  2219. start:
  2220. movq $10, -8(%rbp)
  2221. negq -8(%rbp)
  2222. movq -8(%rbp), %rax
  2223. addq $52, %rax
  2224. jmp conclusion
  2225. .globl main
  2226. main:
  2227. pushq %rbp
  2228. movq %rsp, %rbp
  2229. subq $16, %rsp
  2230. jmp start
  2231. conclusion:
  2232. addq $16, %rsp
  2233. popq %rbp
  2234. retq
  2235. \end{lstlisting}
  2236. \fi}
  2237. {\if\edition\pythonEd
  2238. \begin{lstlisting}
  2239. .globl main
  2240. main:
  2241. pushq %rbp
  2242. movq %rsp, %rbp
  2243. subq $16, %rsp
  2244. movq $10, -8(%rbp)
  2245. negq -8(%rbp)
  2246. movq -8(%rbp), %rax
  2247. addq $52, %rax
  2248. addq $16, %rsp
  2249. popq %rbp
  2250. retq
  2251. \end{lstlisting}
  2252. \fi}
  2253. \caption{An x86 program that computes
  2254. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2255. \label{fig:p1-x86}
  2256. \end{figure}
  2257. \begin{figure}[tbp]
  2258. \centering
  2259. \begin{tabular}{|r|l|} \hline
  2260. Position & Contents \\ \hline
  2261. 8(\key{\%rbp}) & return address \\
  2262. 0(\key{\%rbp}) & old \key{rbp} \\
  2263. -8(\key{\%rbp}) & variable $1$ \\
  2264. -16(\key{\%rbp}) & variable $2$ \\
  2265. \ldots & \ldots \\
  2266. 0(\key{\%rsp}) & variable $n$\\ \hline
  2267. \end{tabular}
  2268. \caption{Memory layout of a frame.}
  2269. \label{fig:frame}
  2270. \end{figure}
  2271. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2272. control is transferred from the operating system to the \code{main}
  2273. function. The operating system issues a \code{callq main} instruction
  2274. which pushes its return address on the stack and then jumps to
  2275. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2276. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2277. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2278. alignment (because the \code{callq} pushed the return address). The
  2279. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2280. for a procedure. The instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2281. pointer and then saves the base pointer of the caller at address
  2282. \code{rsp} on the stack. The next instruction \code{movq \%rsp, \%rbp} sets the
  2283. base pointer to the current stack pointer, which is pointing at the location
  2284. of the old base pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2285. pointer down to make enough room for storing variables. This program
  2286. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2287. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2288. functions.
  2289. \racket{The last instruction of the prelude is \code{jmp start},
  2290. which transfers control to the instructions that were generated from
  2291. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2292. \racket{The first instruction under the \code{start} label is}
  2293. %
  2294. \python{The first instruction after the prelude is}
  2295. %
  2296. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2297. %
  2298. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2299. %
  2300. The next instruction moves the $-10$ from variable $1$ into the
  2301. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2302. the value in \code{rax}, updating its contents to $42$.
  2303. \racket{The three instructions under the label \code{conclusion} are the
  2304. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2305. %
  2306. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2307. \code{main} function consists of the last three instructions.}
  2308. %
  2309. The first two restore the \code{rsp} and \code{rbp} registers to the
  2310. state they were in at the beginning of the procedure. In particular,
  2311. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2312. old base pointer. Then \key{popq \%rbp} returns the old base pointer
  2313. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2314. \key{retq}, jumps back to the procedure that called this one and adds
  2315. $8$ to the stack pointer.
  2316. Our compiler needs a convenient representation for manipulating x86
  2317. programs, so we define an abstract syntax for x86 in
  2318. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2319. \LangXInt{}.
  2320. %
  2321. {\if\edition\pythonEd%
  2322. The main difference compared to the concrete syntax of \LangXInt{}
  2323. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2324. names, and register names are explicitly represented by strings.
  2325. \fi} %
  2326. {\if\edition\racketEd
  2327. The main difference compared to the concrete syntax of \LangXInt{}
  2328. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2329. front of every instruction. Instead instructions are grouped into
  2330. \emph{blocks}\index{subject}{block} with a
  2331. label associated with every block, which is why the \key{X86Program}
  2332. struct includes an alist mapping labels to blocks. The reason for this
  2333. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2334. introduce conditional branching. The \code{Block} structure includes
  2335. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2336. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2337. $\itm{info}$ field should contain an empty list.
  2338. \fi}
  2339. %
  2340. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2341. node includes an integer for representing the arity of the function,
  2342. i.e., the number of arguments, which is helpful to know during
  2343. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2344. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2345. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2346. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2347. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2348. \MID \skey{r14} \MID \skey{r15}}
  2349. \begin{figure}[tp]
  2350. \fbox{
  2351. \begin{minipage}{0.98\textwidth}
  2352. \small
  2353. {\if\edition\racketEd
  2354. \[
  2355. \begin{array}{lcl}
  2356. \Reg &::=& \allregisters{} \\
  2357. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2358. \MID \DEREF{\Reg}{\Int} \\
  2359. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2360. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2361. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2362. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2363. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2364. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2365. \MID \RETQ{}
  2366. \MID \JMP{\itm{label}} \\
  2367. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2368. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2369. \end{array}
  2370. \]
  2371. \fi}
  2372. {\if\edition\pythonEd
  2373. \[
  2374. \begin{array}{lcl}
  2375. \Reg &::=& \allastregisters{} \\
  2376. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2377. \MID \DEREF{\Reg}{\Int} \\
  2378. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2379. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2380. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2381. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2382. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2383. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2384. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2385. \end{array}
  2386. \]
  2387. \fi}
  2388. \end{minipage}
  2389. }
  2390. \caption{The abstract syntax of \LangXInt{} assembly.}
  2391. \label{fig:x86-int-ast}
  2392. \end{figure}
  2393. \section{Planning the trip to x86}
  2394. \label{sec:plan-s0-x86}
  2395. To compile one language to another it helps to focus on the
  2396. differences between the two languages because the compiler will need
  2397. to bridge those differences. What are the differences between \LangVar{}
  2398. and x86 assembly? Here are some of the most important ones:
  2399. \begin{enumerate}
  2400. \item x86 arithmetic instructions typically have two arguments and
  2401. update the second argument in place. In contrast, \LangVar{}
  2402. arithmetic operations take two arguments and produce a new value.
  2403. An x86 instruction may have at most one memory-accessing argument.
  2404. Furthermore, some x86 instructions place special restrictions on
  2405. their arguments.
  2406. \item An argument of an \LangVar{} operator can be a deeply-nested
  2407. expression, whereas x86 instructions restrict their arguments to be
  2408. integer constants, registers, and memory locations.
  2409. {\if\edition\racketEd
  2410. \item The order of execution in x86 is explicit in the syntax: a
  2411. sequence of instructions and jumps to labeled positions, whereas in
  2412. \LangVar{} the order of evaluation is a left-to-right depth-first
  2413. traversal of the abstract syntax tree.
  2414. \fi}
  2415. \item A program in \LangVar{} can have any number of variables
  2416. whereas x86 has 16 registers and the procedure call stack.
  2417. {\if\edition\racketEd
  2418. \item Variables in \LangVar{} can shadow other variables with the
  2419. same name. In x86, registers have unique names and memory locations
  2420. have unique addresses.
  2421. \fi}
  2422. \end{enumerate}
  2423. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2424. down the problem into several steps, dealing with the above
  2425. differences one at a time. Each of these steps is called a \emph{pass}
  2426. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2427. %
  2428. This terminology comes from the way each step passes over, that is,
  2429. traverses the AST of the program.
  2430. %
  2431. Furthermore, we follow the nanopass approach, which means we strive
  2432. for each pass to accomplish one clear objective (not two or three at
  2433. the same time).
  2434. %
  2435. We begin by sketching how we might implement each pass, and give them
  2436. names. We then figure out an ordering of the passes and the
  2437. input/output language for each pass. The very first pass has
  2438. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2439. its output language. In between we can choose whichever language is
  2440. most convenient for expressing the output of each pass, whether that
  2441. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2442. our own design. Finally, to implement each pass we write one
  2443. recursive function per non-terminal in the grammar of the input
  2444. language of the pass. \index{subject}{intermediate language}
  2445. Our compiler for \LangVar{} consists of the following passes.
  2446. %
  2447. \begin{description}
  2448. {\if\edition\racketEd
  2449. \item[\key{uniquify}] deals with the shadowing of variables by
  2450. renaming every variable to a unique name.
  2451. \fi}
  2452. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2453. of a primitive operation or function call is a variable or integer,
  2454. that is, an \emph{atomic} expression. We refer to non-atomic
  2455. expressions as \emph{complex}. This pass introduces temporary
  2456. variables to hold the results of complex
  2457. subexpressions.\index{subject}{atomic
  2458. expression}\index{subject}{complex expression}%
  2459. {\if\edition\racketEd
  2460. \item[\key{explicate\_control}] makes the execution order of the
  2461. program explicit. It converts the abstract syntax tree representation
  2462. into a control-flow graph in which each node contains a sequence of
  2463. statements and the edges between nodes say which nodes contain jumps
  2464. to other nodes.
  2465. \fi}
  2466. \item[\key{select\_instructions}] handles the difference between
  2467. \LangVar{} operations and x86 instructions. This pass converts each
  2468. \LangVar{} operation to a short sequence of instructions that
  2469. accomplishes the same task.
  2470. \item[\key{assign\_homes}] replaces variables with registers or stack
  2471. locations.
  2472. \end{description}
  2473. %
  2474. {\if\edition\racketEd
  2475. %
  2476. Our treatment of \code{remove\_complex\_operands} and
  2477. \code{explicate\_control} as separate passes is an example of the
  2478. nanopass approach\footnote{For analogous decompositions of the
  2479. translation into continuation passing style, see the work of
  2480. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2481. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2482. %
  2483. \fi}
  2484. The next question is: in what order should we apply these passes? This
  2485. question can be challenging because it is difficult to know ahead of
  2486. time which orderings will be better (easier to implement, produce more
  2487. efficient code, etc.) so oftentimes trial-and-error is
  2488. involved. Nevertheless, we can try to plan ahead and make educated
  2489. choices regarding the ordering.
  2490. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2491. \key{uniquify}? The \key{uniquify} pass should come first because
  2492. \key{explicate\_control} changes all the \key{let}-bound variables to
  2493. become local variables whose scope is the entire program, which would
  2494. confuse variables with the same name.}
  2495. %
  2496. \racket{We place \key{remove\_complex\_opera*} before \key{explicate\_control}
  2497. because the later removes the \key{let} form, but it is convenient to
  2498. use \key{let} in the output of \key{remove\_complex\_opera*}.}
  2499. %
  2500. \racket{The ordering of \key{uniquify} with respect to
  2501. \key{remove\_complex\_opera*} does not matter so we arbitrarily choose
  2502. \key{uniquify} to come first.}
  2503. The \key{select\_instructions} and \key{assign\_homes} passes are
  2504. intertwined.
  2505. %
  2506. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2507. passing arguments to functions and it is preferable to assign
  2508. parameters to their corresponding registers. This suggests that it
  2509. would be better to start with the \key{select\_instructions} pass,
  2510. which generates the instructions for argument passing, before
  2511. performing register allocation.
  2512. %
  2513. On the other hand, by selecting instructions first we may run into a
  2514. dead end in \key{assign\_homes}. Recall that only one argument of an
  2515. x86 instruction may be a memory access but \key{assign\_homes} might
  2516. be forced to assign both arguments to memory locations.
  2517. %
  2518. A sophisticated approach is to iteratively repeat the two passes until
  2519. a solution is found. However, to reduce implementation complexity we
  2520. recommend placing \key{select\_instructions} first, followed by the
  2521. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2522. that uses a reserved register to fix outstanding problems.
  2523. \begin{figure}[tbp]
  2524. {\if\edition\racketEd
  2525. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2526. \node (Lvar) at (0,2) {\large \LangVar{}};
  2527. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2528. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2529. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2530. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2531. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2532. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2533. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2534. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2535. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2536. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2537. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2538. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2539. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2540. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2541. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2542. \end{tikzpicture}
  2543. \fi}
  2544. {\if\edition\pythonEd
  2545. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2546. \node (Lvar) at (0,2) {\large \LangVar{}};
  2547. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2548. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2549. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2550. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2551. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2552. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2553. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2554. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2555. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2556. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2557. \end{tikzpicture}
  2558. \fi}
  2559. \caption{Diagram of the passes for compiling \LangVar{}. }
  2560. \label{fig:Lvar-passes}
  2561. \end{figure}
  2562. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2563. passes and identifies the input and output language of each pass.
  2564. %
  2565. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2566. language, which extends \LangXInt{} with an unbounded number of
  2567. program-scope variables and removes the restrictions regarding
  2568. instruction arguments.
  2569. %
  2570. The last pass, \key{prelude\_and\_conclusion}, places the program
  2571. instructions inside a \code{main} function with instructions for the
  2572. prelude and conclusion.
  2573. %
  2574. \racket{In the following section we discuss the \LangCVar{}
  2575. intermediate language.}
  2576. %
  2577. The remainder of this chapter provides guidance on the implementation
  2578. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2579. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2580. %% are programs that are still in the \LangVar{} language, though the
  2581. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2582. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2583. %% %
  2584. %% The output of \code{explicate\_control} is in an intermediate language
  2585. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2586. %% syntax, which we introduce in the next section. The
  2587. %% \key{select-instruction} pass translates from \LangCVar{} to
  2588. %% \LangXVar{}. The \key{assign-homes} and
  2589. %% \key{patch-instructions}
  2590. %% passes input and output variants of x86 assembly.
  2591. \newcommand{\CvarGrammarRacket}{
  2592. \begin{array}{lcl}
  2593. \Atm &::=& \Int \MID \Var \\
  2594. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2595. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2596. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2597. \end{array}
  2598. }
  2599. \newcommand{\CvarASTRacket}{
  2600. \begin{array}{lcl}
  2601. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2602. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2603. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2604. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2605. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2606. \end{array}
  2607. }
  2608. {\if\edition\racketEd
  2609. \subsection{The \LangCVar{} Intermediate Language}
  2610. The output of \code{explicate\_control} is similar to the $C$
  2611. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2612. categories for expressions and statements, so we name it \LangCVar{}.
  2613. This style of intermediate language is also known as
  2614. \emph{three-address code}, to emphasize that the typical form of a
  2615. statement is \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2616. addresses~\citep{Aho:2006wb}.
  2617. The concrete syntax for \LangCVar{} is defined in
  2618. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2619. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2620. %
  2621. The \LangCVar{} language supports the same operators as \LangVar{} but
  2622. the arguments of operators are restricted to atomic
  2623. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2624. assignment statements which can be executed in sequence using the
  2625. \key{Seq} form. A sequence of statements always ends with
  2626. \key{Return}, a guarantee that is baked into the grammar rules for
  2627. \itm{tail}. The naming of this non-terminal comes from the term
  2628. \emph{tail position}\index{subject}{tail position}, which refers to an
  2629. expression that is the last one to execute within a function.
  2630. A \LangCVar{} program consists of an alist mapping labels to
  2631. tails. This is more general than necessary for the present chapter, as
  2632. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2633. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2634. there will be just one label, \key{start}, and the whole program is
  2635. its tail.
  2636. %
  2637. The $\itm{info}$ field of the \key{CProgram} form, after the
  2638. \code{explicate\_control} pass, contains a mapping from the symbol
  2639. \key{locals} to a list of variables, that is, a list of all the
  2640. variables used in the program. At the start of the program, these
  2641. variables are uninitialized; they become initialized on their first
  2642. assignment.
  2643. \begin{figure}[tbp]
  2644. \fbox{
  2645. \begin{minipage}{0.96\textwidth}
  2646. \[
  2647. \begin{array}{l}
  2648. \CvarGrammarRacket \\
  2649. \begin{array}{lcl}
  2650. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2651. \end{array}
  2652. \end{array}
  2653. \]
  2654. \end{minipage}
  2655. }
  2656. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2657. \label{fig:c0-concrete-syntax}
  2658. \end{figure}
  2659. \begin{figure}[tbp]
  2660. \fbox{
  2661. \begin{minipage}{0.96\textwidth}
  2662. \[
  2663. \begin{array}{l}
  2664. \CvarASTRacket \\
  2665. \begin{array}{lcl}
  2666. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2667. \end{array}
  2668. \end{array}
  2669. \]
  2670. \end{minipage}
  2671. }
  2672. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2673. \label{fig:c0-syntax}
  2674. \end{figure}
  2675. The definitional interpreter for \LangCVar{} is in the support code,
  2676. in the file \code{interp-Cvar.rkt}.
  2677. \fi}
  2678. {\if\edition\racketEd
  2679. \section{Uniquify Variables}
  2680. \label{sec:uniquify-Lvar}
  2681. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2682. programs in which every \key{let} binds a unique variable name. For
  2683. example, the \code{uniquify} pass should translate the program on the
  2684. left into the program on the right.
  2685. \begin{transformation}
  2686. \begin{lstlisting}
  2687. (let ([x 32])
  2688. (+ (let ([x 10]) x) x))
  2689. \end{lstlisting}
  2690. \compilesto
  2691. \begin{lstlisting}
  2692. (let ([x.1 32])
  2693. (+ (let ([x.2 10]) x.2) x.1))
  2694. \end{lstlisting}
  2695. \end{transformation}
  2696. The following is another example translation, this time of a program
  2697. with a \key{let} nested inside the initializing expression of another
  2698. \key{let}.
  2699. \begin{transformation}
  2700. \begin{lstlisting}
  2701. (let ([x (let ([x 4])
  2702. (+ x 1))])
  2703. (+ x 2))
  2704. \end{lstlisting}
  2705. \compilesto
  2706. \begin{lstlisting}
  2707. (let ([x.2 (let ([x.1 4])
  2708. (+ x.1 1))])
  2709. (+ x.2 2))
  2710. \end{lstlisting}
  2711. \end{transformation}
  2712. We recommend implementing \code{uniquify} by creating a structurally
  2713. recursive function named \code{uniquify-exp} that mostly just copies
  2714. an expression. However, when encountering a \key{let}, it should
  2715. generate a unique name for the variable and associate the old name
  2716. with the new name in an alist.\footnote{The Racket function
  2717. \code{gensym} is handy for generating unique variable names.} The
  2718. \code{uniquify-exp} function needs to access this alist when it gets
  2719. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2720. for the alist.
  2721. The skeleton of the \code{uniquify-exp} function is shown in
  2722. Figure~\ref{fig:uniquify-Lvar}. The function is curried so that it is
  2723. convenient to partially apply it to an alist and then apply it to
  2724. different expressions, as in the last case for primitive operations in
  2725. Figure~\ref{fig:uniquify-Lvar}. The
  2726. %
  2727. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2728. %
  2729. form of Racket is useful for transforming each element of a list to
  2730. produce a new list.\index{subject}{for/list}
  2731. \begin{figure}[tbp]
  2732. \begin{lstlisting}
  2733. (define (uniquify-exp env)
  2734. (lambda (e)
  2735. (match e
  2736. [(Var x) ___]
  2737. [(Int n) (Int n)]
  2738. [(Let x e body) ___]
  2739. [(Prim op es)
  2740. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2741. (define (uniquify p)
  2742. (match p
  2743. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2744. \end{lstlisting}
  2745. \caption{Skeleton for the \key{uniquify} pass.}
  2746. \label{fig:uniquify-Lvar}
  2747. \end{figure}
  2748. \begin{exercise}
  2749. \normalfont % I don't like the italics for exercises. -Jeremy
  2750. Complete the \code{uniquify} pass by filling in the blanks in
  2751. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2752. variables and for the \key{let} form in the file \code{compiler.rkt}
  2753. in the support code.
  2754. \end{exercise}
  2755. \begin{exercise}
  2756. \normalfont % I don't like the italics for exercises. -Jeremy
  2757. \label{ex:Lvar}
  2758. Create five \LangVar{} programs that exercise the most interesting
  2759. parts of the \key{uniquify} pass, that is, the programs should include
  2760. \key{let} forms, variables, and variables that shadow each other.
  2761. The five programs should be placed in the subdirectory named
  2762. \key{tests} and the file names should start with \code{var\_test\_}
  2763. followed by a unique integer and end with the file extension
  2764. \key{.rkt}.
  2765. %
  2766. The \key{run-tests.rkt} script in the support code checks whether the
  2767. output programs produce the same result as the input programs. The
  2768. script uses the \key{interp-tests} function
  2769. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2770. your \key{uniquify} pass on the example programs. The \code{passes}
  2771. parameter of \key{interp-tests} is a list that should have one entry
  2772. for each pass in your compiler. For now, define \code{passes} to
  2773. contain just one entry for \code{uniquify} as shown below.
  2774. \begin{lstlisting}
  2775. (define passes
  2776. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2777. \end{lstlisting}
  2778. Run the \key{run-tests.rkt} script in the support code to check
  2779. whether the output programs produce the same result as the input
  2780. programs.
  2781. \end{exercise}
  2782. \fi}
  2783. \section{Remove Complex Operands}
  2784. \label{sec:remove-complex-opera-Lvar}
  2785. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2786. into a restricted form in which the arguments of operations are atomic
  2787. expressions. Put another way, this pass removes complex
  2788. operands\index{subject}{complex operand}, such as the expression
  2789. \racket{\code{(- 10)}}\python{\code{-10}}
  2790. in the program below. This is accomplished by introducing a new
  2791. temporary variable, assigning the complex operand to the new
  2792. variable, and then using the new variable in place of the complex
  2793. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2794. right.
  2795. {\if\edition\racketEd
  2796. \begin{transformation}
  2797. % var_test_19.rkt
  2798. \begin{lstlisting}
  2799. (let ([x (+ 42 (- 10))])
  2800. (+ x 10))
  2801. \end{lstlisting}
  2802. \compilesto
  2803. \begin{lstlisting}
  2804. (let ([x (let ([tmp.1 (- 10)])
  2805. (+ 42 tmp.1))])
  2806. (+ x 10))
  2807. \end{lstlisting}
  2808. \end{transformation}
  2809. \fi}
  2810. {\if\edition\pythonEd
  2811. \begin{transformation}
  2812. \begin{lstlisting}
  2813. x = 42 + -10
  2814. print(x + 10)
  2815. \end{lstlisting}
  2816. \compilesto
  2817. \begin{lstlisting}
  2818. tmp_0 = -10
  2819. x = 42 + tmp_0
  2820. tmp_1 = x + 10
  2821. print(tmp_1)
  2822. \end{lstlisting}
  2823. \end{transformation}
  2824. \fi}
  2825. \newcommand{\LvarMonadASTPython}{
  2826. \begin{array}{rcl}
  2827. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2828. \Exp{} &::=& \Atm \MID \READ{} \\
  2829. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2830. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2831. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2832. \end{array}
  2833. }
  2834. \begin{figure}[tp]
  2835. \centering
  2836. \fbox{
  2837. \begin{minipage}{0.96\textwidth}
  2838. {\if\edition\racketEd
  2839. \[
  2840. \begin{array}{rcl}
  2841. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2842. \Exp &::=& \Atm \MID \READ{} \\
  2843. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2844. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2845. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2846. \end{array}
  2847. \]
  2848. \fi}
  2849. {\if\edition\pythonEd
  2850. \[
  2851. \begin{array}{l}
  2852. \LvarMonadASTPython \\
  2853. \begin{array}{rcl}
  2854. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2855. \end{array}
  2856. \end{array}
  2857. \]
  2858. \fi}
  2859. \end{minipage}
  2860. }
  2861. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2862. atomic expressions.}
  2863. \label{fig:Lvar-anf-syntax}
  2864. \end{figure}
  2865. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2866. of this pass, the language \LangVarANF{}. The only difference is that
  2867. operator arguments are restricted to be atomic expressions that are
  2868. defined by the \Atm{} non-terminal. In particular, integer constants
  2869. and variables are atomic.
  2870. The atomic expressions are pure (they do not cause side-effects or
  2871. depend on them) whereas complex expressions may have side effects,
  2872. such as \READ{}. A language with this separation between pure versus
  2873. side-effecting expressions is said to be in monadic normal
  2874. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2875. in \LangVarANF{}. An important invariant of the
  2876. \code{remove\_complex\_operands} pass is that the relative ordering
  2877. among complex expressions is not changed, but the relative ordering
  2878. between atomic expressions and complex expressions can change and
  2879. often does. The reason that these changes are behaviour preserving is
  2880. that the atomic expressions are pure.
  2881. Another well-known form for intermediate languages is the
  2882. \emph{administrative normal form}
  2883. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2884. \index{subject}{administrative normal form} \index{subject}{ANF}
  2885. %
  2886. The \LangVarANF{} language is not quite in ANF because we allow the
  2887. right-hand side of a \code{let} to be a complex expression.
  2888. {\if\edition\racketEd
  2889. We recommend implementing this pass with two mutually recursive
  2890. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2891. \code{rco\_atom} to subexpressions that need to become atomic and to
  2892. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2893. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2894. returns an expression. The \code{rco\_atom} function returns two
  2895. things: an atomic expression and an alist mapping temporary variables to
  2896. complex subexpressions. You can return multiple things from a function
  2897. using Racket's \key{values} form and you can receive multiple things
  2898. from a function call using the \key{define-values} form.
  2899. Also, the
  2900. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2901. form is useful for applying a function to each element of a list, in
  2902. the case where the function returns multiple values.
  2903. \index{subject}{for/lists}
  2904. \fi}
  2905. %
  2906. {\if\edition\pythonEd
  2907. %
  2908. We recommend implementing this pass with an auxiliary method named
  2909. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2910. Boolean that specifies whether the expression needs to become atomic
  2911. or not. The \code{rco\_exp} method should return a pair consisting of
  2912. the new expression and a list of pairs, associating new temporary
  2913. variables with their initializing expressions.
  2914. %
  2915. \fi}
  2916. {\if\edition\racketEd
  2917. Returning to the example program with the expression \code{(+ 42 (-
  2918. 10))}, the subexpression \code{(- 10)} should be processed using the
  2919. \code{rco\_atom} function because it is an argument of the \code{+} and
  2920. therefore needs to become atomic. The output of \code{rco\_atom}
  2921. applied to \code{(- 10)} is as follows.
  2922. \begin{transformation}
  2923. \begin{lstlisting}
  2924. (- 10)
  2925. \end{lstlisting}
  2926. \compilesto
  2927. \begin{lstlisting}
  2928. tmp.1
  2929. ((tmp.1 . (- 10)))
  2930. \end{lstlisting}
  2931. \end{transformation}
  2932. \fi}
  2933. %
  2934. {\if\edition\pythonEd
  2935. %
  2936. Returning to the example program with the expression \code{42 + -10},
  2937. the subexpression \code{-10} should be processed using the
  2938. \code{rco\_exp} function with \code{True} as the second argument
  2939. because \code{-10} is an argument of the \code{+} operator and
  2940. therefore needs to become atomic. The output of \code{rco\_exp}
  2941. applied to \code{-10} is as follows.
  2942. \begin{transformation}
  2943. \begin{lstlisting}
  2944. -10
  2945. \end{lstlisting}
  2946. \compilesto
  2947. \begin{lstlisting}
  2948. tmp_1
  2949. [(tmp_1, -10)]
  2950. \end{lstlisting}
  2951. \end{transformation}
  2952. %
  2953. \fi}
  2954. Take special care of programs such as the following that
  2955. %
  2956. \racket{bind a variable to an atomic expression}
  2957. %
  2958. \python{assign an atomic expression to a variable}.
  2959. %
  2960. You should leave such \racket{variable bindings}\python{assignments}
  2961. unchanged, as shown in the program on the right\\
  2962. %
  2963. {\if\edition\racketEd
  2964. \begin{transformation}
  2965. % var_test_20.rkt
  2966. \begin{lstlisting}
  2967. (let ([a 42])
  2968. (let ([b a])
  2969. b))
  2970. \end{lstlisting}
  2971. \compilesto
  2972. \begin{lstlisting}
  2973. (let ([a 42])
  2974. (let ([b a])
  2975. b))
  2976. \end{lstlisting}
  2977. \end{transformation}
  2978. \fi}
  2979. {\if\edition\pythonEd
  2980. \begin{transformation}
  2981. \begin{lstlisting}
  2982. a = 42
  2983. b = a
  2984. print(b)
  2985. \end{lstlisting}
  2986. \compilesto
  2987. \begin{lstlisting}
  2988. a = 42
  2989. b = a
  2990. print(b)
  2991. \end{lstlisting}
  2992. \end{transformation}
  2993. \fi}
  2994. %
  2995. \noindent A careless implementation might produce the following output with
  2996. unnecessary temporary variables.
  2997. \begin{center}
  2998. \begin{minipage}{0.4\textwidth}
  2999. {\if\edition\racketEd
  3000. \begin{lstlisting}
  3001. (let ([tmp.1 42])
  3002. (let ([a tmp.1])
  3003. (let ([tmp.2 a])
  3004. (let ([b tmp.2])
  3005. b))))
  3006. \end{lstlisting}
  3007. \fi}
  3008. {\if\edition\pythonEd
  3009. \begin{lstlisting}
  3010. tmp_1 = 42
  3011. a = tmp_1
  3012. tmp_2 = a
  3013. b = tmp_2
  3014. print(b)
  3015. \end{lstlisting}
  3016. \fi}
  3017. \end{minipage}
  3018. \end{center}
  3019. \begin{exercise}
  3020. \normalfont
  3021. {\if\edition\racketEd
  3022. Implement the \code{remove\_complex\_operands} function in
  3023. \code{compiler.rkt}.
  3024. %
  3025. Create three new \LangVar{} programs that exercise the interesting
  3026. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3027. regarding file names described in Exercise~\ref{ex:Lvar}.
  3028. %
  3029. In the \code{run-tests.rkt} script, add the following entry to the
  3030. list of \code{passes} and then run the script to test your compiler.
  3031. \begin{lstlisting}
  3032. (list "remove-complex" remove-complex-opera* interp_Lvar type-check-Lvar)
  3033. \end{lstlisting}
  3034. While debugging your compiler, it is often useful to see the
  3035. intermediate programs that are output from each pass. To print the
  3036. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3037. \code{interp-tests} in \code{run-tests.rkt}.
  3038. \fi}
  3039. %
  3040. {\if\edition\pythonEd
  3041. Implement the \code{remove\_complex\_operands} pass in
  3042. \code{compiler.py}, creating auxiliary functions for each
  3043. non-terminal in the grammar, i.e., \code{rco\_exp}
  3044. and \code{rco\_stmt}. We recommend you use the function
  3045. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3046. \fi}
  3047. \end{exercise}
  3048. {\if\edition\pythonEd
  3049. \begin{exercise}
  3050. \normalfont % I don't like the italics for exercises. -Jeremy
  3051. \label{ex:Lvar}
  3052. Create five \LangVar{} programs that exercise the most interesting
  3053. parts of the \code{remove\_complex\_operands} pass. The five programs
  3054. should be placed in the subdirectory named \key{tests} and the file
  3055. names should start with \code{var\_test\_} followed by a unique
  3056. integer and end with the file extension \key{.py}.
  3057. %% The \key{run-tests.rkt} script in the support code checks whether the
  3058. %% output programs produce the same result as the input programs. The
  3059. %% script uses the \key{interp-tests} function
  3060. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3061. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3062. %% parameter of \key{interp-tests} is a list that should have one entry
  3063. %% for each pass in your compiler. For now, define \code{passes} to
  3064. %% contain just one entry for \code{uniquify} as shown below.
  3065. %% \begin{lstlisting}
  3066. %% (define passes
  3067. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3068. %% \end{lstlisting}
  3069. Run the \key{run-tests.py} script in the support code to check
  3070. whether the output programs produce the same result as the input
  3071. programs.
  3072. \end{exercise}
  3073. \fi}
  3074. {\if\edition\racketEd
  3075. \section{Explicate Control}
  3076. \label{sec:explicate-control-Lvar}
  3077. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3078. programs that make the order of execution explicit in their
  3079. syntax. For now this amounts to flattening \key{let} constructs into a
  3080. sequence of assignment statements. For example, consider the following
  3081. \LangVar{} program.\\
  3082. % var_test_11.rkt
  3083. \begin{minipage}{0.96\textwidth}
  3084. \begin{lstlisting}
  3085. (let ([y (let ([x 20])
  3086. (+ x (let ([x 22]) x)))])
  3087. y)
  3088. \end{lstlisting}
  3089. \end{minipage}\\
  3090. %
  3091. The output of the previous pass and of \code{explicate\_control} is
  3092. shown below. Recall that the right-hand-side of a \key{let} executes
  3093. before its body, so the order of evaluation for this program is to
  3094. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  3095. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  3096. output of \code{explicate\_control} makes this ordering explicit.
  3097. \begin{transformation}
  3098. \begin{lstlisting}
  3099. (let ([y (let ([x.1 20])
  3100. (let ([x.2 22])
  3101. (+ x.1 x.2)))])
  3102. y)
  3103. \end{lstlisting}
  3104. \compilesto
  3105. \begin{lstlisting}[language=C]
  3106. start:
  3107. x.1 = 20;
  3108. x.2 = 22;
  3109. y = (+ x.1 x.2);
  3110. return y;
  3111. \end{lstlisting}
  3112. \end{transformation}
  3113. \begin{figure}[tbp]
  3114. \begin{lstlisting}
  3115. (define (explicate_tail e)
  3116. (match e
  3117. [(Var x) ___]
  3118. [(Int n) (Return (Int n))]
  3119. [(Let x rhs body) ___]
  3120. [(Prim op es) ___]
  3121. [else (error "explicate_tail unhandled case" e)]))
  3122. (define (explicate_assign e x cont)
  3123. (match e
  3124. [(Var x) ___]
  3125. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3126. [(Let y rhs body) ___]
  3127. [(Prim op es) ___]
  3128. [else (error "explicate_assign unhandled case" e)]))
  3129. (define (explicate_control p)
  3130. (match p
  3131. [(Program info body) ___]))
  3132. \end{lstlisting}
  3133. \caption{Skeleton for the \code{explicate\_control} pass.}
  3134. \label{fig:explicate-control-Lvar}
  3135. \end{figure}
  3136. The organization of this pass depends on the notion of tail position
  3137. that we have alluded to earlier.
  3138. \begin{definition}
  3139. The following rules define when an expression is in \textbf{\emph{tail
  3140. position}}\index{subject}{tail position} for the language \LangVar{}.
  3141. \begin{enumerate}
  3142. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3143. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3144. \end{enumerate}
  3145. \end{definition}
  3146. We recommend implementing \code{explicate\_control} using two mutually
  3147. recursive functions, \code{explicate\_tail} and
  3148. \code{explicate\_assign}, as suggested in the skeleton code in
  3149. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3150. function should be applied to expressions in tail position whereas the
  3151. \code{explicate\_assign} should be applied to expressions that occur on
  3152. the right-hand-side of a \key{let}.
  3153. %
  3154. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3155. input and produces a \Tail{} in \LangCVar{} (see
  3156. Figure~\ref{fig:c0-syntax}).
  3157. %
  3158. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3159. the variable that it is to be assigned to, and a \Tail{} in
  3160. \LangCVar{} for the code that comes after the assignment. The
  3161. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3162. The \code{explicate\_assign} function is in accumulator-passing style:
  3163. the \code{cont} parameter is used for accumulating the output. This
  3164. accumulator-passing style plays an important role in how we generate
  3165. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3166. \begin{exercise}\normalfont
  3167. %
  3168. Implement the \code{explicate\_control} function in
  3169. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3170. exercise the code in \code{explicate\_control}.
  3171. %
  3172. In the \code{run-tests.rkt} script, add the following entry to the
  3173. list of \code{passes} and then run the script to test your compiler.
  3174. \begin{lstlisting}
  3175. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3176. \end{lstlisting}
  3177. \end{exercise}
  3178. \fi}
  3179. \section{Select Instructions}
  3180. \label{sec:select-Lvar}
  3181. \index{subject}{instruction selection}
  3182. In the \code{select\_instructions} pass we begin the work of
  3183. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3184. language of this pass is a variant of x86 that still uses variables,
  3185. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3186. non-terminal of the \LangXInt{} abstract syntax
  3187. (Figure~\ref{fig:x86-int-ast}).
  3188. \racket{We recommend implementing the
  3189. \code{select\_instructions} with three auxiliary functions, one for
  3190. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3191. $\Tail$.}
  3192. \python{We recommend implementing an auxiliary function
  3193. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3194. \racket{
  3195. The cases for $\Atm$ are straightforward; variables stay
  3196. the same and integer constants change to immediates:
  3197. $\INT{n}$ changes to $\IMM{n}$.}
  3198. We consider the cases for the $\Stmt$ non-terminal, starting with
  3199. arithmetic operations. For example, consider the addition operation
  3200. below, on the left side. There is an \key{addq} instruction in x86,
  3201. but it performs an in-place update. So we could move $\Arg_1$
  3202. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3203. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3204. $\Atm_1$ and $\Atm_2$ respectively.
  3205. \begin{transformation}
  3206. {\if\edition\racketEd
  3207. \begin{lstlisting}
  3208. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3209. \end{lstlisting}
  3210. \fi}
  3211. {\if\edition\pythonEd
  3212. \begin{lstlisting}
  3213. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3214. \end{lstlisting}
  3215. \fi}
  3216. \compilesto
  3217. \begin{lstlisting}
  3218. movq |$\Arg_1$|, |$\itm{var}$|
  3219. addq |$\Arg_2$|, |$\itm{var}$|
  3220. \end{lstlisting}
  3221. \end{transformation}
  3222. There are also cases that require special care to avoid generating
  3223. needlessly complicated code. For example, if one of the arguments of
  3224. the addition is the same variable as the left-hand side of the
  3225. assignment, as shown below, then there is no need for the extra move
  3226. instruction. The assignment statement can be translated into a single
  3227. \key{addq} instruction as follows.
  3228. \begin{transformation}
  3229. {\if\edition\racketEd
  3230. \begin{lstlisting}
  3231. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3232. \end{lstlisting}
  3233. \fi}
  3234. {\if\edition\pythonEd
  3235. \begin{lstlisting}
  3236. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3237. \end{lstlisting}
  3238. \fi}
  3239. \compilesto
  3240. \begin{lstlisting}
  3241. addq |$\Arg_1$|, |$\itm{var}$|
  3242. \end{lstlisting}
  3243. \end{transformation}
  3244. The \READOP{} operation does not have a direct counterpart in x86
  3245. assembly, so we provide this functionality with the function
  3246. \code{read\_int} in the file \code{runtime.c}, written in
  3247. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3248. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3249. system}, or simply the \emph{runtime} for short. When compiling your
  3250. generated x86 assembly code, you need to compile \code{runtime.c} to
  3251. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3252. \code{-c}) and link it into the executable. For our purposes of code
  3253. generation, all you need to do is translate an assignment of
  3254. \READOP{} into a call to the \code{read\_int} function followed by a
  3255. move from \code{rax} to the left-hand-side variable. (Recall that the
  3256. return value of a function goes into \code{rax}.)
  3257. \begin{transformation}
  3258. {\if\edition\racketEd
  3259. \begin{lstlisting}
  3260. |$\itm{var}$| = (read);
  3261. \end{lstlisting}
  3262. \fi}
  3263. {\if\edition\pythonEd
  3264. \begin{lstlisting}
  3265. |$\itm{var}$| = input_int();
  3266. \end{lstlisting}
  3267. \fi}
  3268. \compilesto
  3269. \begin{lstlisting}
  3270. callq read_int
  3271. movq %rax, |$\itm{var}$|
  3272. \end{lstlisting}
  3273. \end{transformation}
  3274. {\if\edition\pythonEd
  3275. %
  3276. Similarly, we translate the \code{print} operation, shown below, into
  3277. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3278. In x86, the first six arguments to functions are passed in registers,
  3279. with the first argument passed in register \code{rdi}. So we move the
  3280. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3281. \code{callq} instruction.
  3282. \begin{transformation}
  3283. \begin{lstlisting}
  3284. print(|$\Atm$|)
  3285. \end{lstlisting}
  3286. \compilesto
  3287. \begin{lstlisting}
  3288. movq |$\Arg$|, %rdi
  3289. callq print_int
  3290. \end{lstlisting}
  3291. \end{transformation}
  3292. %
  3293. \fi}
  3294. {\if\edition\racketEd
  3295. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3296. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3297. assignment to the \key{rax} register followed by a jump to the
  3298. conclusion of the program (so the conclusion needs to be labeled).
  3299. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3300. recursively and then append the resulting instructions.
  3301. \fi}
  3302. {\if\edition\pythonEd
  3303. We recommend that you use the function \code{utils.label\_name()} to
  3304. transform a string into an label argument suitably suitable for, e.g.,
  3305. the target of the \code{callq} instruction. This practice makes your
  3306. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3307. all labels.
  3308. \fi}
  3309. \begin{exercise}
  3310. \normalfont
  3311. {\if\edition\racketEd
  3312. Implement the \code{select\_instructions} pass in
  3313. \code{compiler.rkt}. Create three new example programs that are
  3314. designed to exercise all of the interesting cases in this pass.
  3315. %
  3316. In the \code{run-tests.rkt} script, add the following entry to the
  3317. list of \code{passes} and then run the script to test your compiler.
  3318. \begin{lstlisting}
  3319. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3320. \end{lstlisting}
  3321. \fi}
  3322. {\if\edition\pythonEd
  3323. Implement the \key{select\_instructions} pass in
  3324. \code{compiler.py}. Create three new example programs that are
  3325. designed to exercise all of the interesting cases in this pass.
  3326. Run the \code{run-tests.py} script to to check
  3327. whether the output programs produce the same result as the input
  3328. programs.
  3329. \fi}
  3330. \end{exercise}
  3331. \section{Assign Homes}
  3332. \label{sec:assign-Lvar}
  3333. The \key{assign\_homes} pass compiles \LangXVar{} programs to
  3334. \LangXVar{} programs that no longer use program variables.
  3335. Thus, the \key{assign-homes} pass is responsible for placing all of
  3336. the program variables in registers or on the stack. For runtime
  3337. efficiency, it is better to place variables in registers, but as there
  3338. are only 16 registers, some programs must necessarily resort to
  3339. placing some variables on the stack. In this chapter we focus on the
  3340. mechanics of placing variables on the stack. We study an algorithm for
  3341. placing variables in registers in
  3342. Chapter~\ref{ch:register-allocation-Lvar}.
  3343. Consider again the following \LangVar{} program from
  3344. Section~\ref{sec:remove-complex-opera-Lvar}.
  3345. % var_test_20.rkt
  3346. {\if\edition\racketEd
  3347. \begin{lstlisting}
  3348. (let ([a 42])
  3349. (let ([b a])
  3350. b))
  3351. \end{lstlisting}
  3352. \fi}
  3353. {\if\edition\pythonEd
  3354. \begin{lstlisting}
  3355. a = 42
  3356. b = a
  3357. print(b)
  3358. \end{lstlisting}
  3359. \fi}
  3360. %
  3361. The output of \code{select\_instructions} is shown below, on the left,
  3362. and the output of \code{assign\_homes} is on the right. In this
  3363. example, we assign variable \code{a} to stack location
  3364. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3365. \begin{transformation}
  3366. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3367. movq $42, a
  3368. movq a, b
  3369. movq b, %rax
  3370. \end{lstlisting}
  3371. \compilesto
  3372. %stack-space: 16
  3373. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3374. movq $42, -8(%rbp)
  3375. movq -8(%rbp), -16(%rbp)
  3376. movq -16(%rbp), %rax
  3377. \end{lstlisting}
  3378. \end{transformation}
  3379. \racket{The \code{locals-types} entry in the $\itm{info}$ of the
  3380. \code{X86Program} node is an alist mapping all the variables in the
  3381. program to their types (for now just \code{Integer}). The
  3382. \code{assign\_homes} pass should replace all uses of those variables
  3383. with stack locations. As an aside, the \code{locals-types} entry is
  3384. computed by \code{type-check-Cvar} in the support code, which
  3385. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3386. which should be propagated to the \code{X86Program} node.}
  3387. %
  3388. \python{The \code{assign\_homes} pass should replace all uses of
  3389. variables with stack locations.}
  3390. %
  3391. In the process of assigning variables to stack locations, it is
  3392. convenient for you to compute and store the size of the frame (in
  3393. bytes) in%
  3394. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space}}
  3395. %
  3396. \python{the field \code{stack\_space} of the \key{X86Program} node},
  3397. which is needed later to generate the conclusion of the \code{main}
  3398. procedure. The x86-64 standard requires the frame size to be a
  3399. multiple of 16 bytes.\index{subject}{frame}
  3400. % TODO: store the number of variables instead? -Jeremy
  3401. \begin{exercise}\normalfont
  3402. Implement the \key{assign\_homes} pass in
  3403. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3404. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3405. grammar. We recommend that the auxiliary functions take an extra
  3406. parameter that maps variable names to homes (stack locations for now).
  3407. %
  3408. {\if\edition\racketEd
  3409. In the \code{run-tests.rkt} script, add the following entry to the
  3410. list of \code{passes} and then run the script to test your compiler.
  3411. \begin{lstlisting}
  3412. (list "assign homes" assign-homes interp_x86-0)
  3413. \end{lstlisting}
  3414. \fi}
  3415. {\if\edition\pythonEd
  3416. Run the \code{run-tests.py} script to to check
  3417. whether the output programs produce the same result as the input
  3418. programs.
  3419. \fi}
  3420. \end{exercise}
  3421. \section{Patch Instructions}
  3422. \label{sec:patch-s0}
  3423. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3424. \LangXInt{} by making sure that each instruction adheres to the
  3425. restriction that at most one argument of an instruction may be a
  3426. memory reference.
  3427. We return to the following example.\\
  3428. \begin{minipage}{0.5\textwidth}
  3429. % var_test_20.rkt
  3430. {\if\edition\racketEd
  3431. \begin{lstlisting}
  3432. (let ([a 42])
  3433. (let ([b a])
  3434. b))
  3435. \end{lstlisting}
  3436. \fi}
  3437. {\if\edition\pythonEd
  3438. \begin{lstlisting}
  3439. a = 42
  3440. b = a
  3441. print(b)
  3442. \end{lstlisting}
  3443. \fi}
  3444. \end{minipage}\\
  3445. The \key{assign\_homes} pass produces the following translation. \\
  3446. \begin{minipage}{0.5\textwidth}
  3447. {\if\edition\racketEd
  3448. \begin{lstlisting}
  3449. movq $42, -8(%rbp)
  3450. movq -8(%rbp), -16(%rbp)
  3451. movq -16(%rbp), %rax
  3452. \end{lstlisting}
  3453. \fi}
  3454. {\if\edition\pythonEd
  3455. \begin{lstlisting}
  3456. movq 42, -8(%rbp)
  3457. movq -8(%rbp), -16(%rbp)
  3458. movq -16(%rbp), %rdi
  3459. callq print_int
  3460. \end{lstlisting}
  3461. \fi}
  3462. \end{minipage}\\
  3463. The second \key{movq} instruction is problematic because both
  3464. arguments are stack locations. We suggest fixing this problem by
  3465. moving from the source location to the register \key{rax} and then
  3466. from \key{rax} to the destination location, as follows.
  3467. \begin{lstlisting}
  3468. movq -8(%rbp), %rax
  3469. movq %rax, -16(%rbp)
  3470. \end{lstlisting}
  3471. \begin{exercise}
  3472. \normalfont Implement the \key{patch\_instructions} pass in
  3473. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3474. Create three new example programs that are
  3475. designed to exercise all of the interesting cases in this pass.
  3476. %
  3477. {\if\edition\racketEd
  3478. In the \code{run-tests.rkt} script, add the following entry to the
  3479. list of \code{passes} and then run the script to test your compiler.
  3480. \begin{lstlisting}
  3481. (list "patch instructions" patch_instructions interp_x86-0)
  3482. \end{lstlisting}
  3483. \fi}
  3484. {\if\edition\pythonEd
  3485. Run the \code{run-tests.py} script to to check
  3486. whether the output programs produce the same result as the input
  3487. programs.
  3488. \fi}
  3489. \end{exercise}
  3490. \section{Generate Prelude and Conclusion}
  3491. \label{sec:print-x86}
  3492. \index{subject}{prelude}\index{subject}{conclusion}
  3493. The last step of the compiler from \LangVar{} to x86 is to generate
  3494. the \code{main} function with a prelude and conclusion wrapped around
  3495. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3496. discussed in Section~\ref{sec:x86}.
  3497. When running on Mac OS X, your compiler should prefix an underscore to
  3498. all labels, e.g., changing \key{main} to \key{\_main}.
  3499. %
  3500. \racket{The Racket call \code{(system-type 'os)} is useful for
  3501. determining which operating system the compiler is running on. It
  3502. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3503. %
  3504. \python{The Python \code{platform} library includes a \code{system()}
  3505. function that returns \code{'Linux'}, \code{'Windows'}, or
  3506. \code{'Darwin'} (for Mac).}
  3507. \begin{exercise}\normalfont
  3508. %
  3509. Implement the \key{prelude\_and\_conclusion} pass in
  3510. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3511. %
  3512. {\if\edition\racketEd
  3513. In the \code{run-tests.rkt} script, add the following entry to the
  3514. list of \code{passes} and then run the script to test your compiler.
  3515. \begin{lstlisting}
  3516. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3517. \end{lstlisting}
  3518. %
  3519. Uncomment the call to the \key{compiler-tests} function
  3520. (Appendix~\ref{appendix:utilities}), which tests your complete
  3521. compiler by executing the generated x86 code. It translates the x86
  3522. AST that you produce into a string by invoking the \code{print-x86}
  3523. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3524. the provided \key{runtime.c} file to \key{runtime.o} using
  3525. \key{gcc}. Run the script to test your compiler.
  3526. %
  3527. \fi}
  3528. {\if\edition\pythonEd
  3529. %
  3530. Run the \code{run-tests.py} script to to check whether the output
  3531. programs produce the same result as the input programs. That script
  3532. translates the x86 AST that you produce into a string by invoking the
  3533. \code{repr} method that is implemented by the x86 AST classes in
  3534. \code{x86\_ast.py}.
  3535. %
  3536. \fi}
  3537. \end{exercise}
  3538. \section{Challenge: Partial Evaluator for \LangVar{}}
  3539. \label{sec:pe-Lvar}
  3540. \index{subject}{partial evaluation}
  3541. This section describes two optional challenge exercises that involve
  3542. adapting and improving the partial evaluator for \LangInt{} that was
  3543. introduced in Section~\ref{sec:partial-evaluation}.
  3544. \begin{exercise}\label{ex:pe-Lvar}
  3545. \normalfont
  3546. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3547. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3548. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3549. %
  3550. \racket{\key{let} binding}\python{assignment}
  3551. %
  3552. to the \LangInt{} language, so you will need to add cases for them in
  3553. the \code{pe\_exp}
  3554. %
  3555. \racket{function}
  3556. %
  3557. \python{and \code{pe\_stmt} functions}.
  3558. %
  3559. Once complete, add the partial evaluation pass to the front of your
  3560. compiler and make sure that your compiler still passes all of the
  3561. tests.
  3562. \end{exercise}
  3563. \begin{exercise}
  3564. \normalfont
  3565. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3566. \code{pe\_add} auxiliary functions with functions that know more about
  3567. arithmetic. For example, your partial evaluator should translate
  3568. {\if\edition\racketEd
  3569. \[
  3570. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3571. \code{(+ 2 (read))}
  3572. \]
  3573. \fi}
  3574. {\if\edition\pythonEd
  3575. \[
  3576. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3577. \code{2 + input\_int()}
  3578. \]
  3579. \fi}
  3580. To accomplish this, the \code{pe\_exp} function should produce output
  3581. in the form of the $\itm{residual}$ non-terminal of the following
  3582. grammar. The idea is that when processing an addition expression, we
  3583. can always produce either 1) an integer constant, 2) an addition
  3584. expression with an integer constant on the left-hand side but not the
  3585. right-hand side, or 3) or an addition expression in which neither
  3586. subexpression is a constant.
  3587. {\if\edition\racketEd
  3588. \[
  3589. \begin{array}{lcl}
  3590. \itm{inert} &::=& \Var
  3591. \MID \LP\key{read}\RP
  3592. \MID \LP\key{-} ~\Var\RP
  3593. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3594. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3595. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3596. \itm{residual} &::=& \Int
  3597. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3598. \MID \itm{inert}
  3599. \end{array}
  3600. \]
  3601. \fi}
  3602. {\if\edition\pythonEd
  3603. \[
  3604. \begin{array}{lcl}
  3605. \itm{inert} &::=& \Var
  3606. \MID \key{input\_int}\LP\RP
  3607. \MID \key{-} \Var
  3608. \MID \key{-} \key{input\_int}\LP\RP
  3609. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3610. \itm{residual} &::=& \Int
  3611. \MID \Int ~ \key{+} ~ \itm{inert}
  3612. \MID \itm{inert}
  3613. \end{array}
  3614. \]
  3615. \fi}
  3616. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3617. inputs are $\itm{residual}$ expressions and they should return
  3618. $\itm{residual}$ expressions. Once the improvements are complete,
  3619. make sure that your compiler still passes all of the tests. After
  3620. all, fast code is useless if it produces incorrect results!
  3621. \end{exercise}
  3622. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3623. \chapter{Register Allocation}
  3624. \label{ch:register-allocation-Lvar}
  3625. \index{subject}{register allocation}
  3626. In Chapter~\ref{ch:Lvar} we learned how to store variables on the
  3627. stack. In this chapter we learn how to improve the performance of the
  3628. generated code by assigning some variables to registers. The CPU can
  3629. access a register in a single cycle, whereas accessing the stack can
  3630. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3631. serves as a running example. The source program is on the left and the
  3632. output of instruction selection is on the right. The program is almost
  3633. in the x86 assembly language but it still uses variables.
  3634. \begin{figure}
  3635. \begin{minipage}{0.45\textwidth}
  3636. Example \LangVar{} program:
  3637. % var_test_28.rkt
  3638. {\if\edition\racketEd
  3639. \begin{lstlisting}
  3640. (let ([v 1])
  3641. (let ([w 42])
  3642. (let ([x (+ v 7)])
  3643. (let ([y x])
  3644. (let ([z (+ x w)])
  3645. (+ z (- y)))))))
  3646. \end{lstlisting}
  3647. \fi}
  3648. {\if\edition\pythonEd
  3649. \begin{lstlisting}
  3650. v = 1
  3651. w = 42
  3652. x = v + 7
  3653. y = x
  3654. z = x + w
  3655. print(z + (- y))
  3656. \end{lstlisting}
  3657. \fi}
  3658. \end{minipage}
  3659. \begin{minipage}{0.45\textwidth}
  3660. After instruction selection:
  3661. {\if\edition\racketEd
  3662. \begin{lstlisting}
  3663. locals-types:
  3664. x : Integer, y : Integer,
  3665. z : Integer, t : Integer,
  3666. v : Integer, w : Integer
  3667. start:
  3668. movq $1, v
  3669. movq $42, w
  3670. movq v, x
  3671. addq $7, x
  3672. movq x, y
  3673. movq x, z
  3674. addq w, z
  3675. movq y, t
  3676. negq t
  3677. movq z, %rax
  3678. addq t, %rax
  3679. jmp conclusion
  3680. \end{lstlisting}
  3681. \fi}
  3682. {\if\edition\pythonEd
  3683. \begin{lstlisting}
  3684. movq $1, v
  3685. movq $42, w
  3686. movq v, x
  3687. addq $7, x
  3688. movq x, y
  3689. movq x, z
  3690. addq w, z
  3691. movq y, tmp_0
  3692. negq tmp_0
  3693. movq z, tmp_1
  3694. addq tmp_0, tmp_1
  3695. movq tmp_1, %rdi
  3696. callq print_int
  3697. \end{lstlisting}
  3698. \fi}
  3699. \end{minipage}
  3700. \caption{A running example for register allocation.}
  3701. \label{fig:reg-eg}
  3702. \end{figure}
  3703. The goal of register allocation is to fit as many variables into
  3704. registers as possible. Some programs have more variables than
  3705. registers so we cannot always map each variable to a different
  3706. register. Fortunately, it is common for different variables to be
  3707. needed during different periods of time during program execution, and
  3708. in such cases several variables can be mapped to the same register.
  3709. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3710. After the variable \code{x} is moved to \code{z} it is no longer
  3711. needed. Variable \code{z}, on the other hand, is used only after this
  3712. point, so \code{x} and \code{z} could share the same register. The
  3713. topic of Section~\ref{sec:liveness-analysis-Lvar} is how to compute
  3714. where a variable is needed. Once we have that information, we compute
  3715. which variables are needed at the same time, i.e., which ones
  3716. \emph{interfere} with each other, and represent this relation as an
  3717. undirected graph whose vertices are variables and edges indicate when
  3718. two variables interfere (Section~\ref{sec:build-interference}). We
  3719. then model register allocation as a graph coloring problem
  3720. (Section~\ref{sec:graph-coloring}).
  3721. If we run out of registers despite these efforts, we place the
  3722. remaining variables on the stack, similar to what we did in
  3723. Chapter~\ref{ch:Lvar}. It is common to use the verb \emph{spill} for
  3724. assigning a variable to a stack location. The decision to spill a
  3725. variable is handled as part of the graph coloring process.
  3726. We make the simplifying assumption that each variable is assigned to
  3727. one location (a register or stack address). A more sophisticated
  3728. approach is to assign a variable to one or more locations in different
  3729. regions of the program. For example, if a variable is used many times
  3730. in short sequence and then only used again after many other
  3731. instructions, it could be more efficient to assign the variable to a
  3732. register during the initial sequence and then move it to the stack for
  3733. the rest of its lifetime. We refer the interested reader to
  3734. \citet{Cooper:2011aa} Chapter 13 for more information about that
  3735. approach.
  3736. % discuss prioritizing variables based on how much they are used.
  3737. \section{Registers and Calling Conventions}
  3738. \label{sec:calling-conventions}
  3739. \index{subject}{calling conventions}
  3740. As we perform register allocation, we need to be aware of the
  3741. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3742. functions calls are performed in x86.
  3743. %
  3744. Even though \LangVar{} does not include programmer-defined functions,
  3745. our generated code includes a \code{main} function that is called by
  3746. the operating system and our generated code contains calls to the
  3747. \code{read\_int} function.
  3748. Function calls require coordination between two pieces of code that
  3749. may be written by different programmers or generated by different
  3750. compilers. Here we follow the System V calling conventions that are
  3751. used by the GNU C compiler on Linux and
  3752. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3753. %
  3754. The calling conventions include rules about how functions share the
  3755. use of registers. In particular, the caller is responsible for freeing
  3756. up some registers prior to the function call for use by the callee.
  3757. These are called the \emph{caller-saved registers}
  3758. \index{subject}{caller-saved registers}
  3759. and they are
  3760. \begin{lstlisting}
  3761. rax rcx rdx rsi rdi r8 r9 r10 r11
  3762. \end{lstlisting}
  3763. On the other hand, the callee is responsible for preserving the values
  3764. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3765. which are
  3766. \begin{lstlisting}
  3767. rsp rbp rbx r12 r13 r14 r15
  3768. \end{lstlisting}
  3769. We can think about this caller/callee convention from two points of
  3770. view, the caller view and the callee view:
  3771. \begin{itemize}
  3772. \item The caller should assume that all the caller-saved registers get
  3773. overwritten with arbitrary values by the callee. On the other hand,
  3774. the caller can safely assume that all the callee-saved registers
  3775. contain the same values after the call that they did before the
  3776. call.
  3777. \item The callee can freely use any of the caller-saved registers.
  3778. However, if the callee wants to use a callee-saved register, the
  3779. callee must arrange to put the original value back in the register
  3780. prior to returning to the caller. This can be accomplished by saving
  3781. the value to the stack in the prelude of the function and restoring
  3782. the value in the conclusion of the function.
  3783. \end{itemize}
  3784. In x86, registers are also used for passing arguments to a function
  3785. and for the return value. In particular, the first six arguments to a
  3786. function are passed in the following six registers, in this order.
  3787. \begin{lstlisting}
  3788. rdi rsi rdx rcx r8 r9
  3789. \end{lstlisting}
  3790. If there are more than six arguments, then the convention is to use
  3791. space on the frame of the caller for the rest of the
  3792. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3793. need more than six arguments.
  3794. %
  3795. \racket{For now, the only function we care about is \code{read\_int}
  3796. and it takes zero arguments.}
  3797. %
  3798. \python{For now, the only functions we care about are \code{read\_int}
  3799. and \code{print\_int}, which take zero and one argument, respectively.}
  3800. %
  3801. The register \code{rax} is used for the return value of a function.
  3802. The next question is how these calling conventions impact register
  3803. allocation. Consider the \LangVar{} program in
  3804. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3805. example from the caller point of view and then from the callee point
  3806. of view.
  3807. The program makes two calls to \READOP{}. Also, the variable \code{x}
  3808. is in use during the second call to \READOP{}, so we need to make sure
  3809. that the value in \code{x} does not get accidentally wiped out by the
  3810. call to \READOP{}. One obvious approach is to save all the values in
  3811. caller-saved registers to the stack prior to each function call, and
  3812. restore them after each call. That way, if the register allocator
  3813. chooses to assign \code{x} to a caller-saved register, its value will
  3814. be preserved across the call to \READOP{}. However, saving and
  3815. restoring to the stack is relatively slow. If \code{x} is not used
  3816. many times, it may be better to assign \code{x} to a stack location in
  3817. the first place. Or better yet, if we can arrange for \code{x} to be
  3818. placed in a callee-saved register, then it won't need to be saved and
  3819. restored during function calls.
  3820. The approach that we recommend for variables that are in use during a
  3821. function call is to either assign them to callee-saved registers or to
  3822. spill them to the stack. On the other hand, for variables that are not
  3823. in use during a function call, we try the following alternatives in
  3824. order 1) look for an available caller-saved register (to leave room
  3825. for other variables in the callee-saved register), 2) look for a
  3826. callee-saved register, and 3) spill the variable to the stack.
  3827. It is straightforward to implement this approach in a graph coloring
  3828. register allocator. First, we know which variables are in use during
  3829. every function call because we compute that information for every
  3830. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3831. we build the interference graph
  3832. (Section~\ref{sec:build-interference}), we can place an edge between
  3833. each of these call-live variables and the caller-saved registers in
  3834. the interference graph. This will prevent the graph coloring algorithm
  3835. from assigning them to caller-saved registers.
  3836. Returning to the example in
  3837. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3838. generated x86 code on the right-hand side. Notice that variable
  3839. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3840. is already in a safe place during the second call to
  3841. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3842. \code{rcx}, a caller-saved register, because \code{y} is not in the
  3843. live-after set of a \code{callq} instruction.
  3844. Next we analyze the example from the callee point of view, focusing on
  3845. the prelude and conclusion of the \code{main} function. As usual the
  3846. prelude begins with saving the \code{rbp} register to the stack and
  3847. setting the \code{rbp} to the current stack pointer. We now know why
  3848. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3849. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3850. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3851. (\code{x}). The other callee-saved registers are not saved in the
  3852. prelude because they are not used. The prelude subtracts 8 bytes from
  3853. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3854. conclusion, we see that \code{rbx} is restored from the stack with a
  3855. \code{popq} instruction.
  3856. \index{subject}{prelude}\index{subject}{conclusion}
  3857. \begin{figure}[tp]
  3858. \begin{minipage}{0.45\textwidth}
  3859. Example \LangVar{} program:
  3860. %var_test_14.rkt
  3861. {\if\edition\racketEd
  3862. \begin{lstlisting}
  3863. (let ([x (read)])
  3864. (let ([y (read)])
  3865. (+ (+ x y) 42)))
  3866. \end{lstlisting}
  3867. \fi}
  3868. {\if\edition\pythonEd
  3869. \begin{lstlisting}
  3870. x = input_int()
  3871. y = input_int()
  3872. print((x + y) + 42)
  3873. \end{lstlisting}
  3874. \fi}
  3875. \end{minipage}
  3876. \begin{minipage}{0.45\textwidth}
  3877. Generated x86 assembly:
  3878. {\if\edition\racketEd
  3879. \begin{lstlisting}
  3880. start:
  3881. callq read_int
  3882. movq %rax, %rbx
  3883. callq read_int
  3884. movq %rax, %rcx
  3885. addq %rcx, %rbx
  3886. movq %rbx, %rax
  3887. addq $42, %rax
  3888. jmp _conclusion
  3889. .globl main
  3890. main:
  3891. pushq %rbp
  3892. movq %rsp, %rbp
  3893. pushq %rbx
  3894. subq $8, %rsp
  3895. jmp start
  3896. conclusion:
  3897. addq $8, %rsp
  3898. popq %rbx
  3899. popq %rbp
  3900. retq
  3901. \end{lstlisting}
  3902. \fi}
  3903. {\if\edition\pythonEd
  3904. \begin{lstlisting}
  3905. .globl main
  3906. main:
  3907. pushq %rbp
  3908. movq %rsp, %rbp
  3909. pushq %rbx
  3910. subq $8, %rsp
  3911. callq read_int
  3912. movq %rax, %rbx
  3913. callq read_int
  3914. movq %rax, %rcx
  3915. movq %rbx, %rdx
  3916. addq %rcx, %rdx
  3917. movq %rdx, %rcx
  3918. addq $42, %rcx
  3919. movq %rcx, %rdi
  3920. callq print_int
  3921. addq $8, %rsp
  3922. popq %rbx
  3923. popq %rbp
  3924. retq
  3925. \end{lstlisting}
  3926. \fi}
  3927. \end{minipage}
  3928. \caption{An example with function calls.}
  3929. \label{fig:example-calling-conventions}
  3930. \end{figure}
  3931. %\clearpage
  3932. \section{Liveness Analysis}
  3933. \label{sec:liveness-analysis-Lvar}
  3934. \index{subject}{liveness analysis}
  3935. The \code{uncover\_live} \racket{pass}\python{function}
  3936. performs \emph{liveness analysis}, that
  3937. is, it discovers which variables are in-use in different regions of a
  3938. program.
  3939. %
  3940. A variable or register is \emph{live} at a program point if its
  3941. current value is used at some later point in the program. We refer to
  3942. variables, stack locations, and registers collectively as
  3943. \emph{locations}.
  3944. %
  3945. Consider the following code fragment in which there are two writes to
  3946. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3947. \begin{center}
  3948. \begin{minipage}{0.96\textwidth}
  3949. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3950. movq $5, a
  3951. movq $30, b
  3952. movq a, c
  3953. movq $10, b
  3954. addq b, c
  3955. \end{lstlisting}
  3956. \end{minipage}
  3957. \end{center}
  3958. The answer is no because \code{a} is live from line 1 to 3 and
  3959. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3960. line 2 is never used because it is overwritten (line 4) before the
  3961. next read (line 5).
  3962. The live locations can be computed by traversing the instruction
  3963. sequence back to front (i.e., backwards in execution order). Let
  3964. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3965. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3966. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3967. locations before instruction $I_k$.
  3968. \racket{We recommend representing these
  3969. sets with the Racket \code{set} data structure described in
  3970. Figure~\ref{fig:set}.}
  3971. \python{We recommend representing these sets with the Python
  3972. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  3973. data structure.}
  3974. {\if\edition\racketEd
  3975. \begin{figure}[tp]
  3976. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3977. \small
  3978. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3979. A \emph{set} is an unordered collection of elements without duplicates.
  3980. Here are some of the operations defined on sets.
  3981. \index{subject}{set}
  3982. \begin{description}
  3983. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3984. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3985. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3986. difference of the two sets.
  3987. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3988. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3989. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3990. \end{description}
  3991. \end{tcolorbox}
  3992. %\end{wrapfigure}
  3993. \caption{The \code{set} data structure.}
  3994. \label{fig:set}
  3995. \end{figure}
  3996. \fi}
  3997. The live locations after an instruction are always the same as the
  3998. live locations before the next instruction.
  3999. \index{subject}{live-after} \index{subject}{live-before}
  4000. \begin{equation} \label{eq:live-after-before-next}
  4001. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4002. \end{equation}
  4003. To start things off, there are no live locations after the last
  4004. instruction, so
  4005. \begin{equation}\label{eq:live-last-empty}
  4006. L_{\mathsf{after}}(n) = \emptyset
  4007. \end{equation}
  4008. We then apply the following rule repeatedly, traversing the
  4009. instruction sequence back to front.
  4010. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4011. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4012. \end{equation}
  4013. where $W(k)$ are the locations written to by instruction $I_k$ and
  4014. $R(k)$ are the locations read by instruction $I_k$.
  4015. {\if\edition\racketEd
  4016. There is a special case for \code{jmp} instructions. The locations
  4017. that are live before a \code{jmp} should be the locations in
  4018. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4019. maintaining an alist named \code{label->live} that maps each label to
  4020. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4021. now the only \code{jmp} in a \LangXVar{} program is the one at the
  4022. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  4023. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  4024. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4025. \fi}
  4026. Let us walk through the above example, applying these formulas
  4027. starting with the instruction on line 5. We collect the answers in
  4028. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4029. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4030. instruction (formula~\ref{eq:live-last-empty}). The
  4031. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4032. because it reads from variables \code{b} and \code{c}
  4033. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4034. \[
  4035. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4036. \]
  4037. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4038. the live-before set from line 5 to be the live-after set for this
  4039. instruction (formula~\ref{eq:live-after-before-next}).
  4040. \[
  4041. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4042. \]
  4043. This move instruction writes to \code{b} and does not read from any
  4044. variables, so we have the following live-before set
  4045. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4046. \[
  4047. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4048. \]
  4049. The live-before for instruction \code{movq a, c}
  4050. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4051. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4052. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4053. variable that is not live and does not read from a variable.
  4054. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4055. because it writes to variable \code{a}.
  4056. \begin{figure}[tbp]
  4057. \begin{minipage}{0.45\textwidth}
  4058. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4059. movq $5, a
  4060. movq $30, b
  4061. movq a, c
  4062. movq $10, b
  4063. addq b, c
  4064. \end{lstlisting}
  4065. \end{minipage}
  4066. \vrule\hspace{10pt}
  4067. \begin{minipage}{0.45\textwidth}
  4068. \begin{align*}
  4069. L_{\mathsf{before}}(1)= \emptyset,
  4070. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4071. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4072. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4073. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4074. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4075. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4076. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4077. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4078. L_{\mathsf{after}}(5)= \emptyset
  4079. \end{align*}
  4080. \end{minipage}
  4081. \caption{Example output of liveness analysis on a short example.}
  4082. \label{fig:liveness-example-0}
  4083. \end{figure}
  4084. \begin{exercise}\normalfont
  4085. Perform liveness analysis on the running example in
  4086. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4087. sets for each instruction. Compare your answers to the solution
  4088. shown in Figure~\ref{fig:live-eg}.
  4089. \end{exercise}
  4090. \begin{figure}[tp]
  4091. \hspace{20pt}
  4092. \begin{minipage}{0.45\textwidth}
  4093. {\if\edition\racketEd
  4094. \begin{lstlisting}
  4095. |$\{\ttm{rsp}\}$|
  4096. movq $1, v
  4097. |$\{\ttm{v},\ttm{rsp}\}$|
  4098. movq $42, w
  4099. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4100. movq v, x
  4101. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4102. addq $7, x
  4103. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4104. movq x, y
  4105. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4106. movq x, z
  4107. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4108. addq w, z
  4109. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4110. movq y, t
  4111. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4112. negq t
  4113. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4114. movq z, %rax
  4115. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4116. addq t, %rax
  4117. |$\{\ttm{rax},\ttm{rsp}\}$|
  4118. jmp conclusion
  4119. \end{lstlisting}
  4120. \fi}
  4121. {\if\edition\pythonEd
  4122. \begin{lstlisting}
  4123. movq $1, v
  4124. |$\{\ttm{v}\}$|
  4125. movq $42, w
  4126. |$\{\ttm{w}, \ttm{v}\}$|
  4127. movq v, x
  4128. |$\{\ttm{w}, \ttm{x}\}$|
  4129. addq $7, x
  4130. |$\{\ttm{w}, \ttm{x}\}$|
  4131. movq x, y
  4132. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4133. movq x, z
  4134. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4135. addq w, z
  4136. |$\{\ttm{y}, \ttm{z}\}$|
  4137. movq y, tmp_0
  4138. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4139. negq tmp_0
  4140. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4141. movq z, tmp_1
  4142. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4143. addq tmp_0, tmp_1
  4144. |$\{\ttm{tmp\_1}\}$|
  4145. movq tmp_1, %rdi
  4146. |$\{\ttm{rdi}\}$|
  4147. callq print_int
  4148. |$\{\}$|
  4149. \end{lstlisting}
  4150. \fi}
  4151. \end{minipage}
  4152. \caption{The running example annotated with live-after sets.}
  4153. \label{fig:live-eg}
  4154. \end{figure}
  4155. \begin{exercise}\normalfont
  4156. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4157. %
  4158. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4159. field of the \code{Block} structure.}
  4160. %
  4161. \python{Return a dictionary that maps each instruction to its
  4162. live-after set.}
  4163. %
  4164. \racket{We recommend creating an auxiliary function that takes a list
  4165. of instructions and an initial live-after set (typically empty) and
  4166. returns the list of live-after sets.}
  4167. %
  4168. We recommend creating auxiliary functions to 1) compute the set
  4169. of locations that appear in an \Arg{}, 2) compute the locations read
  4170. by an instruction (the $R$ function), and 3) the locations written by
  4171. an instruction (the $W$ function). The \code{callq} instruction should
  4172. include all of the caller-saved registers in its write-set $W$ because
  4173. the calling convention says that those registers may be written to
  4174. during the function call. Likewise, the \code{callq} instruction
  4175. should include the appropriate argument-passing registers in its
  4176. read-set $R$, depending on the arity of the function being
  4177. called. (This is why the abstract syntax for \code{callq} includes the
  4178. arity.)
  4179. \end{exercise}
  4180. %\clearpage
  4181. \section{Build the Interference Graph}
  4182. \label{sec:build-interference}
  4183. {\if\edition\racketEd
  4184. \begin{figure}[tp]
  4185. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4186. \small
  4187. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4188. A \emph{graph} is a collection of vertices and edges where each
  4189. edge connects two vertices. A graph is \emph{directed} if each
  4190. edge points from a source to a target. Otherwise the graph is
  4191. \emph{undirected}.
  4192. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4193. \begin{description}
  4194. %% We currently don't use directed graphs. We instead use
  4195. %% directed multi-graphs. -Jeremy
  4196. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4197. directed graph from a list of edges. Each edge is a list
  4198. containing the source and target vertex.
  4199. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4200. undirected graph from a list of edges. Each edge is represented by
  4201. a list containing two vertices.
  4202. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4203. inserts a vertex into the graph.
  4204. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4205. inserts an edge between the two vertices.
  4206. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4207. returns a sequence of vertices adjacent to the vertex.
  4208. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4209. returns a sequence of all vertices in the graph.
  4210. \end{description}
  4211. \end{tcolorbox}
  4212. %\end{wrapfigure}
  4213. \caption{The Racket \code{graph} package.}
  4214. \label{fig:graph}
  4215. \end{figure}
  4216. \fi}
  4217. Based on the liveness analysis, we know where each location is live.
  4218. However, during register allocation, we need to answer questions of
  4219. the specific form: are locations $u$ and $v$ live at the same time?
  4220. (And therefore cannot be assigned to the same register.) To make this
  4221. question more efficient to answer, we create an explicit data
  4222. structure, an \emph{interference graph}\index{subject}{interference
  4223. graph}. An interference graph is an undirected graph that has an
  4224. edge between two locations if they are live at the same time, that is,
  4225. if they interfere with each other.
  4226. %
  4227. \racket{We recommend using the Racket \code{graph} package
  4228. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4229. %
  4230. \python{We provide implementations of directed and undirected graph
  4231. data structures in the file \code{graph.py} of the support code.}
  4232. A straightforward way to compute the interference graph is to look at
  4233. the set of live locations between each instruction and add an edge to
  4234. the graph for every pair of variables in the same set. This approach
  4235. is less than ideal for two reasons. First, it can be expensive because
  4236. it takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  4237. locations. Second, in the special case where two locations hold the
  4238. same value (because one was assigned to the other), they can be live
  4239. at the same time without interfering with each other.
  4240. A better way to compute the interference graph is to focus on
  4241. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4242. must not overwrite something in a live location. So for each
  4243. instruction, we create an edge between the locations being written to
  4244. and the live locations. (Except that one should not create self
  4245. edges.) Note that for the \key{callq} instruction, we consider all of
  4246. the caller-saved registers as being written to, so an edge is added
  4247. between every live variable and every caller-saved register. Also, for
  4248. \key{movq} there is the above-mentioned special case to deal with. If
  4249. a live variable $v$ is the same as the source of the \key{movq}, then
  4250. there is no need to add an edge between $v$ and the destination,
  4251. because they both hold the same value.
  4252. %
  4253. So we have the following two rules.
  4254. \begin{enumerate}
  4255. \item If instruction $I_k$ is a move instruction of the form
  4256. \key{movq} $s$\key{,} $d$, then for every $v \in
  4257. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4258. $(d,v)$.
  4259. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4260. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4261. $(d,v)$.
  4262. \end{enumerate}
  4263. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4264. the above rules to each instruction. We highlight a few of the
  4265. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4266. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4267. so \code{v} interferes with \code{rsp}.}
  4268. %
  4269. \python{The first instruction is \lstinline{movq $1, v} and the
  4270. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4271. no interference because $\ttm{v}$ is the destination of the move.}
  4272. %
  4273. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4274. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4275. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4276. %
  4277. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4278. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4279. $\ttm{x}$ interferes with \ttm{w}.}
  4280. %
  4281. \racket{The next instruction is \lstinline{movq x, y} and the
  4282. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4283. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4284. \ttm{x} because \ttm{x} is the source of the move and therefore
  4285. \ttm{x} and \ttm{y} hold the same value.}
  4286. %
  4287. \python{The next instruction is \lstinline{movq x, y} and the
  4288. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4289. applies, so \ttm{y} interferes with \ttm{w} but not
  4290. \ttm{x} because \ttm{x} is the source of the move and therefore
  4291. \ttm{x} and \ttm{y} hold the same value.}
  4292. %
  4293. Figure~\ref{fig:interference-results} lists the interference results
  4294. for all of the instructions and the resulting interference graph is
  4295. shown in Figure~\ref{fig:interfere}.
  4296. \begin{figure}[tbp]
  4297. \begin{quote}
  4298. {\if\edition\racketEd
  4299. \begin{tabular}{ll}
  4300. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4301. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4302. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4303. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4304. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4305. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4306. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4307. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4308. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4309. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4310. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4311. \lstinline!jmp conclusion!& no interference.
  4312. \end{tabular}
  4313. \fi}
  4314. {\if\edition\pythonEd
  4315. \begin{tabular}{ll}
  4316. \lstinline!movq $1, v!& no interference\\
  4317. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4318. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4319. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4320. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4321. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4322. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4323. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4324. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4325. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4326. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4327. \lstinline!movq tmp_1, %rdi! & no interference \\
  4328. \lstinline!callq print_int!& no interference.
  4329. \end{tabular}
  4330. \fi}
  4331. \end{quote}
  4332. \caption{Interference results for the running example.}
  4333. \label{fig:interference-results}
  4334. \end{figure}
  4335. \begin{figure}[tbp]
  4336. \large
  4337. {\if\edition\racketEd
  4338. \[
  4339. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4340. \node (rax) at (0,0) {$\ttm{rax}$};
  4341. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4342. \node (t1) at (0,2) {$\ttm{t}$};
  4343. \node (z) at (3,2) {$\ttm{z}$};
  4344. \node (x) at (6,2) {$\ttm{x}$};
  4345. \node (y) at (3,0) {$\ttm{y}$};
  4346. \node (w) at (6,0) {$\ttm{w}$};
  4347. \node (v) at (9,0) {$\ttm{v}$};
  4348. \draw (t1) to (rax);
  4349. \draw (t1) to (z);
  4350. \draw (z) to (y);
  4351. \draw (z) to (w);
  4352. \draw (x) to (w);
  4353. \draw (y) to (w);
  4354. \draw (v) to (w);
  4355. \draw (v) to (rsp);
  4356. \draw (w) to (rsp);
  4357. \draw (x) to (rsp);
  4358. \draw (y) to (rsp);
  4359. \path[-.,bend left=15] (z) edge node {} (rsp);
  4360. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4361. \draw (rax) to (rsp);
  4362. \end{tikzpicture}
  4363. \]
  4364. \fi}
  4365. {\if\edition\pythonEd
  4366. \[
  4367. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4368. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4369. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4370. \node (z) at (3,2) {$\ttm{z}$};
  4371. \node (x) at (6,2) {$\ttm{x}$};
  4372. \node (y) at (3,0) {$\ttm{y}$};
  4373. \node (w) at (6,0) {$\ttm{w}$};
  4374. \node (v) at (9,0) {$\ttm{v}$};
  4375. \draw (t0) to (t1);
  4376. \draw (t0) to (z);
  4377. \draw (z) to (y);
  4378. \draw (z) to (w);
  4379. \draw (x) to (w);
  4380. \draw (y) to (w);
  4381. \draw (v) to (w);
  4382. \end{tikzpicture}
  4383. \]
  4384. \fi}
  4385. \caption{The interference graph of the example program.}
  4386. \label{fig:interfere}
  4387. \end{figure}
  4388. %% Our next concern is to choose a data structure for representing the
  4389. %% interference graph. There are many choices for how to represent a
  4390. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4391. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4392. %% data structure is to study the algorithm that uses the data structure,
  4393. %% determine what operations need to be performed, and then choose the
  4394. %% data structure that provide the most efficient implementations of
  4395. %% those operations. Often times the choice of data structure can have an
  4396. %% effect on the time complexity of the algorithm, as it does here. If
  4397. %% you skim the next section, you will see that the register allocation
  4398. %% algorithm needs to ask the graph for all of its vertices and, given a
  4399. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4400. %% correct choice of graph representation is that of an adjacency
  4401. %% list. There are helper functions in \code{utilities.rkt} for
  4402. %% representing graphs using the adjacency list representation:
  4403. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4404. %% (Appendix~\ref{appendix:utilities}).
  4405. %% %
  4406. %% \margincomment{\footnotesize To do: change to use the
  4407. %% Racket graph library. \\ --Jeremy}
  4408. %% %
  4409. %% In particular, those functions use a hash table to map each vertex to
  4410. %% the set of adjacent vertices, and the sets are represented using
  4411. %% Racket's \key{set}, which is also a hash table.
  4412. \begin{exercise}\normalfont
  4413. \racket{Implement the compiler pass named \code{build\_interference} according
  4414. to the algorithm suggested above. We recommend using the Racket
  4415. \code{graph} package to create and inspect the interference graph.
  4416. The output graph of this pass should be stored in the $\itm{info}$ field of
  4417. the program, under the key \code{conflicts}.}
  4418. %
  4419. \python{Implement a function named \code{build\_interference}
  4420. according to the algorithm suggested above that
  4421. returns the interference graph.}
  4422. \end{exercise}
  4423. \section{Graph Coloring via Sudoku}
  4424. \label{sec:graph-coloring}
  4425. \index{subject}{graph coloring}
  4426. \index{subject}{Sudoku}
  4427. \index{subject}{color}
  4428. We come to the main event, mapping variables to registers and stack
  4429. locations. Variables that interfere with each other must be mapped to
  4430. different locations. In terms of the interference graph, this means
  4431. that adjacent vertices must be mapped to different locations. If we
  4432. think of locations as colors, the register allocation problem becomes
  4433. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4434. The reader may be more familiar with the graph coloring problem than he
  4435. or she realizes; the popular game of Sudoku is an instance of the
  4436. graph coloring problem. The following describes how to build a graph
  4437. out of an initial Sudoku board.
  4438. \begin{itemize}
  4439. \item There is one vertex in the graph for each Sudoku square.
  4440. \item There is an edge between two vertices if the corresponding squares
  4441. are in the same row, in the same column, or if the squares are in
  4442. the same $3\times 3$ region.
  4443. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4444. \item Based on the initial assignment of numbers to squares in the
  4445. Sudoku board, assign the corresponding colors to the corresponding
  4446. vertices in the graph.
  4447. \end{itemize}
  4448. If you can color the remaining vertices in the graph with the nine
  4449. colors, then you have also solved the corresponding game of Sudoku.
  4450. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4451. the corresponding graph with colored vertices. We map the Sudoku
  4452. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4453. sampling of the vertices (the colored ones) because showing edges for
  4454. all of the vertices would make the graph unreadable.
  4455. \begin{figure}[tbp]
  4456. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4457. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4458. \caption{A Sudoku game board and the corresponding colored graph.}
  4459. \label{fig:sudoku-graph}
  4460. \end{figure}
  4461. Some techniques for playing Sudoku correspond to heuristics used in
  4462. graph coloring algorithms. For example, one of the basic techniques
  4463. for Sudoku is called Pencil Marks. The idea is to use a process of
  4464. elimination to determine what numbers are no longer available for a
  4465. square and write down those numbers in the square (writing very
  4466. small). For example, if the number $1$ is assigned to a square, then
  4467. write the pencil mark $1$ in all the squares in the same row, column,
  4468. and region to indicate that $1$ is no longer an option for those other
  4469. squares.
  4470. %
  4471. The Pencil Marks technique corresponds to the notion of
  4472. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4473. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4474. are no longer available. In graph terminology, we have the following
  4475. definition:
  4476. \begin{equation*}
  4477. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4478. \text{ and } \mathrm{color}(v) = c \}
  4479. \end{equation*}
  4480. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4481. edge with $u$.
  4482. The Pencil Marks technique leads to a simple strategy for filling in
  4483. numbers: if there is a square with only one possible number left, then
  4484. choose that number! But what if there are no squares with only one
  4485. possibility left? One brute-force approach is to try them all: choose
  4486. the first one and if that ultimately leads to a solution, great. If
  4487. not, backtrack and choose the next possibility. One good thing about
  4488. Pencil Marks is that it reduces the degree of branching in the search
  4489. tree. Nevertheless, backtracking can be terribly time consuming. One
  4490. way to reduce the amount of backtracking is to use the
  4491. most-constrained-first heuristic (aka. minimum remaining
  4492. values)~\citep{Russell2003}. That is, when choosing a square, always
  4493. choose one with the fewest possibilities left (the vertex with the
  4494. highest saturation). The idea is that choosing highly constrained
  4495. squares earlier rather than later is better because later on there may
  4496. not be any possibilities left in the highly saturated squares.
  4497. However, register allocation is easier than Sudoku because the
  4498. register allocator can fall back to assigning variables to stack
  4499. locations when the registers run out. Thus, it makes sense to replace
  4500. backtracking with greedy search: make the best choice at the time and
  4501. keep going. We still wish to minimize the number of colors needed, so
  4502. we use the most-constrained-first heuristic in the greedy search.
  4503. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4504. algorithm for register allocation based on saturation and the
  4505. most-constrained-first heuristic. It is roughly equivalent to the
  4506. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4507. %,Gebremedhin:1999fk,Omari:2006uq
  4508. Just as in Sudoku, the algorithm represents colors with integers. The
  4509. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4510. for register allocation. The integers $k$ and larger correspond to
  4511. stack locations. The registers that are not used for register
  4512. allocation, such as \code{rax}, are assigned to negative integers. In
  4513. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4514. %% One might wonder why we include registers at all in the liveness
  4515. %% analysis and interference graph. For example, we never allocate a
  4516. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4517. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4518. %% to use register for passing arguments to functions, it will be
  4519. %% necessary for those registers to appear in the interference graph
  4520. %% because those registers will also be assigned to variables, and we
  4521. %% don't want those two uses to encroach on each other. Regarding
  4522. %% registers such as \code{rax} and \code{rsp} that are not used for
  4523. %% variables, we could omit them from the interference graph but that
  4524. %% would require adding special cases to our algorithm, which would
  4525. %% complicate the logic for little gain.
  4526. \begin{figure}[btp]
  4527. \centering
  4528. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4529. Algorithm: DSATUR
  4530. Input: a graph |$G$|
  4531. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4532. |$W \gets \mathrm{vertices}(G)$|
  4533. while |$W \neq \emptyset$| do
  4534. pick a vertex |$u$| from |$W$| with the highest saturation,
  4535. breaking ties randomly
  4536. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4537. |$\mathrm{color}[u] \gets c$|
  4538. |$W \gets W - \{u\}$|
  4539. \end{lstlisting}
  4540. \caption{The saturation-based greedy graph coloring algorithm.}
  4541. \label{fig:satur-algo}
  4542. \end{figure}
  4543. {\if\edition\racketEd
  4544. With the DSATUR algorithm in hand, let us return to the running
  4545. example and consider how to color the interference graph in
  4546. Figure~\ref{fig:interfere}.
  4547. %
  4548. We start by assigning the register nodes to their own color. For
  4549. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4550. assigned $-2$. The variables are not yet colored, so they are
  4551. annotated with a dash. We then update the saturation for vertices that
  4552. are adjacent to a register, obtaining the following annotated
  4553. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4554. it interferes with both \code{rax} and \code{rsp}.
  4555. \[
  4556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4557. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4558. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4559. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4560. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4561. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4562. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4563. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4564. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4565. \draw (t1) to (rax);
  4566. \draw (t1) to (z);
  4567. \draw (z) to (y);
  4568. \draw (z) to (w);
  4569. \draw (x) to (w);
  4570. \draw (y) to (w);
  4571. \draw (v) to (w);
  4572. \draw (v) to (rsp);
  4573. \draw (w) to (rsp);
  4574. \draw (x) to (rsp);
  4575. \draw (y) to (rsp);
  4576. \path[-.,bend left=15] (z) edge node {} (rsp);
  4577. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4578. \draw (rax) to (rsp);
  4579. \end{tikzpicture}
  4580. \]
  4581. The algorithm says to select a maximally saturated vertex. So we pick
  4582. $\ttm{t}$ and color it with the first available integer, which is
  4583. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4584. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4585. \[
  4586. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4587. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4588. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4589. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4590. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4591. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4592. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4593. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4594. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4595. \draw (t1) to (rax);
  4596. \draw (t1) to (z);
  4597. \draw (z) to (y);
  4598. \draw (z) to (w);
  4599. \draw (x) to (w);
  4600. \draw (y) to (w);
  4601. \draw (v) to (w);
  4602. \draw (v) to (rsp);
  4603. \draw (w) to (rsp);
  4604. \draw (x) to (rsp);
  4605. \draw (y) to (rsp);
  4606. \path[-.,bend left=15] (z) edge node {} (rsp);
  4607. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4608. \draw (rax) to (rsp);
  4609. \end{tikzpicture}
  4610. \]
  4611. We repeat the process, selecting a maximally saturated vertex,
  4612. choosing is \code{z}, and color it with the first available number, which
  4613. is $1$. We add $1$ to the saturation for the neighboring vertices
  4614. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4615. \[
  4616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4617. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4618. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4619. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4620. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4621. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4622. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4623. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4624. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4625. \draw (t1) to (rax);
  4626. \draw (t1) to (z);
  4627. \draw (z) to (y);
  4628. \draw (z) to (w);
  4629. \draw (x) to (w);
  4630. \draw (y) to (w);
  4631. \draw (v) to (w);
  4632. \draw (v) to (rsp);
  4633. \draw (w) to (rsp);
  4634. \draw (x) to (rsp);
  4635. \draw (y) to (rsp);
  4636. \path[-.,bend left=15] (z) edge node {} (rsp);
  4637. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4638. \draw (rax) to (rsp);
  4639. \end{tikzpicture}
  4640. \]
  4641. The most saturated vertices are now \code{w} and \code{y}. We color
  4642. \code{w} with the first available color, which is $0$.
  4643. \[
  4644. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4645. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4646. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4647. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4648. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4649. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4650. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4651. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4652. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4653. \draw (t1) to (rax);
  4654. \draw (t1) to (z);
  4655. \draw (z) to (y);
  4656. \draw (z) to (w);
  4657. \draw (x) to (w);
  4658. \draw (y) to (w);
  4659. \draw (v) to (w);
  4660. \draw (v) to (rsp);
  4661. \draw (w) to (rsp);
  4662. \draw (x) to (rsp);
  4663. \draw (y) to (rsp);
  4664. \path[-.,bend left=15] (z) edge node {} (rsp);
  4665. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4666. \draw (rax) to (rsp);
  4667. \end{tikzpicture}
  4668. \]
  4669. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4670. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4671. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4672. and \code{z}, whose colors are $0$ and $1$ respectively.
  4673. \[
  4674. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4675. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4676. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4677. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4678. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4679. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4680. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4681. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4682. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4683. \draw (t1) to (rax);
  4684. \draw (t1) to (z);
  4685. \draw (z) to (y);
  4686. \draw (z) to (w);
  4687. \draw (x) to (w);
  4688. \draw (y) to (w);
  4689. \draw (v) to (w);
  4690. \draw (v) to (rsp);
  4691. \draw (w) to (rsp);
  4692. \draw (x) to (rsp);
  4693. \draw (y) to (rsp);
  4694. \path[-.,bend left=15] (z) edge node {} (rsp);
  4695. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4696. \draw (rax) to (rsp);
  4697. \end{tikzpicture}
  4698. \]
  4699. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4700. \[
  4701. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4702. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4703. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4704. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4705. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4706. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4707. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4708. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4709. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4710. \draw (t1) to (rax);
  4711. \draw (t1) to (z);
  4712. \draw (z) to (y);
  4713. \draw (z) to (w);
  4714. \draw (x) to (w);
  4715. \draw (y) to (w);
  4716. \draw (v) to (w);
  4717. \draw (v) to (rsp);
  4718. \draw (w) to (rsp);
  4719. \draw (x) to (rsp);
  4720. \draw (y) to (rsp);
  4721. \path[-.,bend left=15] (z) edge node {} (rsp);
  4722. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4723. \draw (rax) to (rsp);
  4724. \end{tikzpicture}
  4725. \]
  4726. In the last step of the algorithm, we color \code{x} with $1$.
  4727. \[
  4728. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4729. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4730. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4731. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4732. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4733. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4734. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4735. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4736. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4737. \draw (t1) to (rax);
  4738. \draw (t1) to (z);
  4739. \draw (z) to (y);
  4740. \draw (z) to (w);
  4741. \draw (x) to (w);
  4742. \draw (y) to (w);
  4743. \draw (v) to (w);
  4744. \draw (v) to (rsp);
  4745. \draw (w) to (rsp);
  4746. \draw (x) to (rsp);
  4747. \draw (y) to (rsp);
  4748. \path[-.,bend left=15] (z) edge node {} (rsp);
  4749. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4750. \draw (rax) to (rsp);
  4751. \end{tikzpicture}
  4752. \]
  4753. So we obtain the following coloring:
  4754. \[
  4755. \{
  4756. \ttm{rax} \mapsto -1,
  4757. \ttm{rsp} \mapsto -2,
  4758. \ttm{t} \mapsto 0,
  4759. \ttm{z} \mapsto 1,
  4760. \ttm{x} \mapsto 1,
  4761. \ttm{y} \mapsto 2,
  4762. \ttm{w} \mapsto 0,
  4763. \ttm{v} \mapsto 1
  4764. \}
  4765. \]
  4766. \fi}
  4767. %
  4768. {\if\edition\pythonEd
  4769. %
  4770. With the DSATUR algorithm in hand, let us return to the running
  4771. example and consider how to color the interference graph in
  4772. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4773. to indicate that it has not yet been assigned a color. The saturation
  4774. sets are also shown for each node; all of them start as the empty set.
  4775. (We do not include the register nodes in the graph below because there
  4776. were no interference edges involving registers in this program, but in
  4777. general there can be.)
  4778. %
  4779. \[
  4780. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4781. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4782. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4783. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4784. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4785. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4786. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4787. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4788. \draw (t0) to (t1);
  4789. \draw (t0) to (z);
  4790. \draw (z) to (y);
  4791. \draw (z) to (w);
  4792. \draw (x) to (w);
  4793. \draw (y) to (w);
  4794. \draw (v) to (w);
  4795. \end{tikzpicture}
  4796. \]
  4797. The algorithm says to select a maximally saturated vertex, but they
  4798. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4799. then color it with the first available integer, which is $0$. We mark
  4800. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4801. they interfere with $\ttm{tmp\_0}$.
  4802. \[
  4803. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4804. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4805. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4806. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4807. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4808. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4809. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4810. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4811. \draw (t0) to (t1);
  4812. \draw (t0) to (z);
  4813. \draw (z) to (y);
  4814. \draw (z) to (w);
  4815. \draw (x) to (w);
  4816. \draw (y) to (w);
  4817. \draw (v) to (w);
  4818. \end{tikzpicture}
  4819. \]
  4820. We repeat the process. The most saturated vertices are \code{z} and
  4821. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4822. available number, which is $1$. We add $1$ to the saturation for the
  4823. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4824. \[
  4825. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4826. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4827. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4828. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4829. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4830. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4831. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4832. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4833. \draw (t0) to (t1);
  4834. \draw (t0) to (z);
  4835. \draw (z) to (y);
  4836. \draw (z) to (w);
  4837. \draw (x) to (w);
  4838. \draw (y) to (w);
  4839. \draw (v) to (w);
  4840. \end{tikzpicture}
  4841. \]
  4842. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4843. \code{y}. We color \code{w} with the first available color, which
  4844. is $0$.
  4845. \[
  4846. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4847. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4848. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4849. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4850. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4851. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4852. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4853. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4854. \draw (t0) to (t1);
  4855. \draw (t0) to (z);
  4856. \draw (z) to (y);
  4857. \draw (z) to (w);
  4858. \draw (x) to (w);
  4859. \draw (y) to (w);
  4860. \draw (v) to (w);
  4861. \end{tikzpicture}
  4862. \]
  4863. Now \code{y} is the most saturated, so we color it with $2$.
  4864. \[
  4865. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4866. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4867. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4868. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4869. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4870. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4871. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4872. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4873. \draw (t0) to (t1);
  4874. \draw (t0) to (z);
  4875. \draw (z) to (y);
  4876. \draw (z) to (w);
  4877. \draw (x) to (w);
  4878. \draw (y) to (w);
  4879. \draw (v) to (w);
  4880. \end{tikzpicture}
  4881. \]
  4882. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4883. We choose to color \code{v} with $1$.
  4884. \[
  4885. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4886. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4887. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4888. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4889. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4890. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4891. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4892. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4893. \draw (t0) to (t1);
  4894. \draw (t0) to (z);
  4895. \draw (z) to (y);
  4896. \draw (z) to (w);
  4897. \draw (x) to (w);
  4898. \draw (y) to (w);
  4899. \draw (v) to (w);
  4900. \end{tikzpicture}
  4901. \]
  4902. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4903. \[
  4904. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4905. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4906. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4907. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4908. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4909. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4910. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4911. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4912. \draw (t0) to (t1);
  4913. \draw (t0) to (z);
  4914. \draw (z) to (y);
  4915. \draw (z) to (w);
  4916. \draw (x) to (w);
  4917. \draw (y) to (w);
  4918. \draw (v) to (w);
  4919. \end{tikzpicture}
  4920. \]
  4921. So we obtain the following coloring:
  4922. \[
  4923. \{ \ttm{tmp\_0} \mapsto 0,
  4924. \ttm{tmp\_1} \mapsto 1,
  4925. \ttm{z} \mapsto 1,
  4926. \ttm{x} \mapsto 1,
  4927. \ttm{y} \mapsto 2,
  4928. \ttm{w} \mapsto 0,
  4929. \ttm{v} \mapsto 1 \}
  4930. \]
  4931. \fi}
  4932. We recommend creating an auxiliary function named \code{color\_graph}
  4933. that takes an interference graph and a list of all the variables in
  4934. the program. This function should return a mapping of variables to
  4935. their colors (represented as natural numbers). By creating this helper
  4936. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4937. when we add support for functions.
  4938. To prioritize the processing of highly saturated nodes inside the
  4939. \code{color\_graph} function, we recommend using the priority queue
  4940. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4941. addition, you will need to maintain a mapping from variables to their
  4942. ``handles'' in the priority queue so that you can notify the priority
  4943. queue when their saturation changes.}
  4944. {\if\edition\racketEd
  4945. \begin{figure}[tp]
  4946. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4947. \small
  4948. \begin{tcolorbox}[title=Priority Queue]
  4949. A \emph{priority queue} is a collection of items in which the
  4950. removal of items is governed by priority. In a ``min'' queue,
  4951. lower priority items are removed first. An implementation is in
  4952. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4953. queue} \index{subject}{minimum priority queue}
  4954. \begin{description}
  4955. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4956. priority queue that uses the $\itm{cmp}$ predicate to determine
  4957. whether its first argument has lower or equal priority to its
  4958. second argument.
  4959. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4960. items in the queue.
  4961. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4962. the item into the queue and returns a handle for the item in the
  4963. queue.
  4964. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4965. the lowest priority.
  4966. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4967. notifies the queue that the priority has decreased for the item
  4968. associated with the given handle.
  4969. \end{description}
  4970. \end{tcolorbox}
  4971. %\end{wrapfigure}
  4972. \caption{The priority queue data structure.}
  4973. \label{fig:priority-queue}
  4974. \end{figure}
  4975. \fi}
  4976. With the coloring complete, we finalize the assignment of variables to
  4977. registers and stack locations. We map the first $k$ colors to the $k$
  4978. registers and the rest of the colors to stack locations. Suppose for
  4979. the moment that we have just one register to use for register
  4980. allocation, \key{rcx}. Then we have the following map from colors to
  4981. locations.
  4982. \[
  4983. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4984. \]
  4985. Composing this mapping with the coloring, we arrive at the following
  4986. assignment of variables to locations.
  4987. {\if\edition\racketEd
  4988. \begin{gather*}
  4989. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4990. \ttm{w} \mapsto \key{\%rcx}, \,
  4991. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4992. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4993. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4994. \ttm{t} \mapsto \key{\%rcx} \}
  4995. \end{gather*}
  4996. \fi}
  4997. {\if\edition\pythonEd
  4998. \begin{gather*}
  4999. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5000. \ttm{w} \mapsto \key{\%rcx}, \,
  5001. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5002. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5003. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5004. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5005. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5006. \end{gather*}
  5007. \fi}
  5008. Adapt the code from the \code{assign\_homes} pass
  5009. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5010. assigned location. Applying the above assignment to our running
  5011. example, on the left, yields the program on the right.
  5012. % why frame size of 32? -JGS
  5013. \begin{center}
  5014. {\if\edition\racketEd
  5015. \begin{minipage}{0.3\textwidth}
  5016. \begin{lstlisting}
  5017. movq $1, v
  5018. movq $42, w
  5019. movq v, x
  5020. addq $7, x
  5021. movq x, y
  5022. movq x, z
  5023. addq w, z
  5024. movq y, t
  5025. negq t
  5026. movq z, %rax
  5027. addq t, %rax
  5028. jmp conclusion
  5029. \end{lstlisting}
  5030. \end{minipage}
  5031. $\Rightarrow\qquad$
  5032. \begin{minipage}{0.45\textwidth}
  5033. \begin{lstlisting}
  5034. movq $1, -8(%rbp)
  5035. movq $42, %rcx
  5036. movq -8(%rbp), -8(%rbp)
  5037. addq $7, -8(%rbp)
  5038. movq -8(%rbp), -16(%rbp)
  5039. movq -8(%rbp), -8(%rbp)
  5040. addq %rcx, -8(%rbp)
  5041. movq -16(%rbp), %rcx
  5042. negq %rcx
  5043. movq -8(%rbp), %rax
  5044. addq %rcx, %rax
  5045. jmp conclusion
  5046. \end{lstlisting}
  5047. \end{minipage}
  5048. \fi}
  5049. {\if\edition\pythonEd
  5050. \begin{minipage}{0.3\textwidth}
  5051. \begin{lstlisting}
  5052. movq $1, v
  5053. movq $42, w
  5054. movq v, x
  5055. addq $7, x
  5056. movq x, y
  5057. movq x, z
  5058. addq w, z
  5059. movq y, tmp_0
  5060. negq tmp_0
  5061. movq z, tmp_1
  5062. addq tmp_0, tmp_1
  5063. movq tmp_1, %rdi
  5064. callq print_int
  5065. \end{lstlisting}
  5066. \end{minipage}
  5067. $\Rightarrow\qquad$
  5068. \begin{minipage}{0.45\textwidth}
  5069. \begin{lstlisting}
  5070. movq $1, -8(%rbp)
  5071. movq $42, %rcx
  5072. movq -8(%rbp), -8(%rbp)
  5073. addq $7, -8(%rbp)
  5074. movq -8(%rbp), -16(%rbp)
  5075. movq -8(%rbp), -8(%rbp)
  5076. addq %rcx, -8(%rbp)
  5077. movq -16(%rbp), %rcx
  5078. negq %rcx
  5079. movq -8(%rbp), -8(%rbp)
  5080. addq %rcx, -8(%rbp)
  5081. movq -8(%rbp), %rdi
  5082. callq print_int
  5083. \end{lstlisting}
  5084. \end{minipage}
  5085. \fi}
  5086. \end{center}
  5087. \begin{exercise}\normalfont
  5088. %
  5089. Implement the compiler pass \code{allocate\_registers}.
  5090. %
  5091. Create five programs that exercise all aspects of the register
  5092. allocation algorithm, including spilling variables to the stack.
  5093. %
  5094. \racket{Replace \code{assign\_homes} in the list of \code{passes} in the
  5095. \code{run-tests.rkt} script with the three new passes:
  5096. \code{uncover\_live}, \code{build\_interference}, and
  5097. \code{allocate\_registers}.
  5098. %
  5099. Temporarily remove the \code{print\_x86} pass from the list of passes
  5100. and the call to \code{compiler-tests}.
  5101. Run the script to test the register allocator.
  5102. }
  5103. %
  5104. \python{Run the \code{run-tests.py} script to to check whether the
  5105. output programs produce the same result as the input programs.}
  5106. \end{exercise}
  5107. \section{Patch Instructions}
  5108. \label{sec:patch-instructions}
  5109. The remaining step in the compilation to x86 is to ensure that the
  5110. instructions have at most one argument that is a memory access.
  5111. %
  5112. In the running example, the instruction \code{movq -8(\%rbp),
  5113. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5114. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5115. then move \code{rax} into \code{-16(\%rbp)}.
  5116. %
  5117. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5118. problematic, but they can simply be deleted. In general, we recommend
  5119. deleting all the trivial moves whose source and destination are the
  5120. same location.
  5121. %
  5122. The following is the output of \code{patch\_instructions} on the
  5123. running example.
  5124. \begin{center}
  5125. {\if\edition\racketEd
  5126. \begin{minipage}{0.4\textwidth}
  5127. \begin{lstlisting}
  5128. movq $1, -8(%rbp)
  5129. movq $42, %rcx
  5130. movq -8(%rbp), -8(%rbp)
  5131. addq $7, -8(%rbp)
  5132. movq -8(%rbp), -16(%rbp)
  5133. movq -8(%rbp), -8(%rbp)
  5134. addq %rcx, -8(%rbp)
  5135. movq -16(%rbp), %rcx
  5136. negq %rcx
  5137. movq -8(%rbp), %rax
  5138. addq %rcx, %rax
  5139. jmp conclusion
  5140. \end{lstlisting}
  5141. \end{minipage}
  5142. $\Rightarrow\qquad$
  5143. \begin{minipage}{0.45\textwidth}
  5144. \begin{lstlisting}
  5145. movq $1, -8(%rbp)
  5146. movq $42, %rcx
  5147. addq $7, -8(%rbp)
  5148. movq -8(%rbp), %rax
  5149. movq %rax, -16(%rbp)
  5150. addq %rcx, -8(%rbp)
  5151. movq -16(%rbp), %rcx
  5152. negq %rcx
  5153. movq -8(%rbp), %rax
  5154. addq %rcx, %rax
  5155. jmp conclusion
  5156. \end{lstlisting}
  5157. \end{minipage}
  5158. \fi}
  5159. {\if\edition\pythonEd
  5160. \begin{minipage}{0.4\textwidth}
  5161. \begin{lstlisting}
  5162. movq $1, -8(%rbp)
  5163. movq $42, %rcx
  5164. movq -8(%rbp), -8(%rbp)
  5165. addq $7, -8(%rbp)
  5166. movq -8(%rbp), -16(%rbp)
  5167. movq -8(%rbp), -8(%rbp)
  5168. addq %rcx, -8(%rbp)
  5169. movq -16(%rbp), %rcx
  5170. negq %rcx
  5171. movq -8(%rbp), -8(%rbp)
  5172. addq %rcx, -8(%rbp)
  5173. movq -8(%rbp), %rdi
  5174. callq print_int
  5175. \end{lstlisting}
  5176. \end{minipage}
  5177. $\Rightarrow\qquad$
  5178. \begin{minipage}{0.45\textwidth}
  5179. \begin{lstlisting}
  5180. movq $1, -8(%rbp)
  5181. movq $42, %rcx
  5182. addq $7, -8(%rbp)
  5183. movq -8(%rbp), %rax
  5184. movq %rax, -16(%rbp)
  5185. addq %rcx, -8(%rbp)
  5186. movq -16(%rbp), %rcx
  5187. negq %rcx
  5188. addq %rcx, -8(%rbp)
  5189. movq -8(%rbp), %rdi
  5190. callq print_int
  5191. \end{lstlisting}
  5192. \end{minipage}
  5193. \fi}
  5194. \end{center}
  5195. \begin{exercise}\normalfont
  5196. %
  5197. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5198. %
  5199. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5200. %in the \code{run-tests.rkt} script.
  5201. %
  5202. Run the script to test the \code{patch\_instructions} pass.
  5203. \end{exercise}
  5204. \section{Prelude and Conclusion}
  5205. \label{sec:print-x86-reg-alloc}
  5206. \index{subject}{calling conventions}
  5207. \index{subject}{prelude}\index{subject}{conclusion}
  5208. Recall that this pass generates the prelude and conclusion
  5209. instructions to satisfy the x86 calling conventions
  5210. (Section~\ref{sec:calling-conventions}). With the addition of the
  5211. register allocator, the callee-saved registers used by the register
  5212. allocator must be saved in the prelude and restored in the conclusion.
  5213. In the \code{allocate\_registers} pass,
  5214. %
  5215. \racket{add an entry to the \itm{info}
  5216. of \code{X86Program} named \code{used\_callee}}
  5217. %
  5218. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5219. %
  5220. that stores the set of callee-saved registers that were assigned to
  5221. variables. The \code{prelude\_and\_conclusion} pass can then access
  5222. this information to decide which callee-saved registers need to be
  5223. saved and restored.
  5224. %
  5225. When calculating the size of the frame to adjust the \code{rsp} in the
  5226. prelude, make sure to take into account the space used for saving the
  5227. callee-saved registers. Also, don't forget that the frame needs to be
  5228. a multiple of 16 bytes!
  5229. \racket{An overview of all of the passes involved in register
  5230. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5231. {\if\edition\racketEd
  5232. \begin{figure}[tbp]
  5233. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5234. \node (Lvar) at (0,2) {\large \LangVar{}};
  5235. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5236. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5237. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5238. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5239. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5240. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5241. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5242. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5243. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5244. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5245. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5246. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5247. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5248. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5249. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5250. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5251. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5252. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5253. \end{tikzpicture}
  5254. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5255. \label{fig:reg-alloc-passes}
  5256. \end{figure}
  5257. \fi}
  5258. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5259. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5260. use of registers and the stack, we limit the register allocator for
  5261. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5262. the prelude\index{subject}{prelude} of the \code{main} function, we
  5263. push \code{rbx} onto the stack because it is a callee-saved register
  5264. and it was assigned to variable by the register allocator. We
  5265. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5266. reserve space for the one spilled variable. After that subtraction,
  5267. the \code{rsp} is aligned to 16 bytes.
  5268. Moving on to the program proper, we see how the registers were
  5269. allocated.
  5270. %
  5271. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5272. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5273. %
  5274. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5275. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5276. were assigned to \code{rbx}.}
  5277. %
  5278. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5279. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5280. callee-save register \code{rbx} onto the stack. The spilled variables
  5281. must be placed lower on the stack than the saved callee-save
  5282. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5283. \code{-16(\%rbp)}.
  5284. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5285. done in the prelude. We move the stack pointer up by \code{8} bytes
  5286. (the room for spilled variables), then we pop the old values of
  5287. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5288. \code{retq} to return control to the operating system.
  5289. \begin{figure}[tbp]
  5290. % var_test_28.rkt
  5291. % (use-minimal-set-of-registers! #t)
  5292. % and only rbx rcx
  5293. % tmp 0 rbx
  5294. % z 1 rcx
  5295. % y 0 rbx
  5296. % w 2 16(%rbp)
  5297. % v 0 rbx
  5298. % x 0 rbx
  5299. {\if\edition\racketEd
  5300. \begin{lstlisting}
  5301. start:
  5302. movq $1, %rbx
  5303. movq $42, -16(%rbp)
  5304. addq $7, %rbx
  5305. movq %rbx, %rcx
  5306. addq -16(%rbp), %rcx
  5307. negq %rbx
  5308. movq %rcx, %rax
  5309. addq %rbx, %rax
  5310. jmp conclusion
  5311. .globl main
  5312. main:
  5313. pushq %rbp
  5314. movq %rsp, %rbp
  5315. pushq %rbx
  5316. subq $8, %rsp
  5317. jmp start
  5318. conclusion:
  5319. addq $8, %rsp
  5320. popq %rbx
  5321. popq %rbp
  5322. retq
  5323. \end{lstlisting}
  5324. \fi}
  5325. {\if\edition\pythonEd
  5326. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5327. \begin{lstlisting}
  5328. .globl main
  5329. main:
  5330. pushq %rbp
  5331. movq %rsp, %rbp
  5332. pushq %rbx
  5333. subq $8, %rsp
  5334. movq $1, %rcx
  5335. movq $42, %rbx
  5336. addq $7, %rcx
  5337. movq %rcx, -16(%rbp)
  5338. addq %rbx, -16(%rbp)
  5339. negq %rcx
  5340. movq -16(%rbp), %rbx
  5341. addq %rcx, %rbx
  5342. movq %rbx, %rdi
  5343. callq print_int
  5344. addq $8, %rsp
  5345. popq %rbx
  5346. popq %rbp
  5347. retq
  5348. \end{lstlisting}
  5349. \fi}
  5350. \caption{The x86 output from the running example
  5351. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5352. and \code{rcx}.}
  5353. \label{fig:running-example-x86}
  5354. \end{figure}
  5355. \begin{exercise}\normalfont
  5356. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5357. %
  5358. \racket{
  5359. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5360. list of passes and the call to \code{compiler-tests}.}
  5361. %
  5362. Run the script to test the complete compiler for \LangVar{} that
  5363. performs register allocation.
  5364. \end{exercise}
  5365. \section{Challenge: Move Biasing}
  5366. \label{sec:move-biasing}
  5367. \index{subject}{move biasing}
  5368. This section describes an enhancement to the register allocator,
  5369. called move biasing, for students who are looking for an extra
  5370. challenge.
  5371. {\if\edition\racketEd
  5372. To motivate the need for move biasing we return to the running example
  5373. but this time use all of the general purpose registers. So we have
  5374. the following mapping of color numbers to registers.
  5375. \[
  5376. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  5377. \]
  5378. Using the same assignment of variables to color numbers that was
  5379. produced by the register allocator described in the last section, we
  5380. get the following program.
  5381. \begin{center}
  5382. \begin{minipage}{0.3\textwidth}
  5383. \begin{lstlisting}
  5384. movq $1, v
  5385. movq $42, w
  5386. movq v, x
  5387. addq $7, x
  5388. movq x, y
  5389. movq x, z
  5390. addq w, z
  5391. movq y, t
  5392. negq t
  5393. movq z, %rax
  5394. addq t, %rax
  5395. jmp conclusion
  5396. \end{lstlisting}
  5397. \end{minipage}
  5398. $\Rightarrow\qquad$
  5399. \begin{minipage}{0.45\textwidth}
  5400. \begin{lstlisting}
  5401. movq $1, %rdx
  5402. movq $42, %rcx
  5403. movq %rdx, %rdx
  5404. addq $7, %rdx
  5405. movq %rdx, %rsi
  5406. movq %rdx, %rdx
  5407. addq %rcx, %rdx
  5408. movq %rsi, %rcx
  5409. negq %rcx
  5410. movq %rdx, %rax
  5411. addq %rcx, %rax
  5412. jmp conclusion
  5413. \end{lstlisting}
  5414. \end{minipage}
  5415. \end{center}
  5416. In the above output code there are two \key{movq} instructions that
  5417. can be removed because their source and target are the same. However,
  5418. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5419. register, we could instead remove three \key{movq} instructions. We
  5420. can accomplish this by taking into account which variables appear in
  5421. \key{movq} instructions with which other variables.
  5422. \fi}
  5423. {\if\edition\pythonEd
  5424. %
  5425. To motivate the need for move biasing we return to the running example
  5426. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5427. remove three trivial move instructions from the running
  5428. example. However, we could remove another trivial move if we were able
  5429. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5430. We say that two variables $p$ and $q$ are \emph{move
  5431. related}\index{subject}{move related} if they participate together in
  5432. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5433. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5434. when there are multiple variables with the same saturation, prefer
  5435. variables that can be assigned to a color that is the same as the
  5436. color of a move related variable. Furthermore, when the register
  5437. allocator chooses a color for a variable, it should prefer a color
  5438. that has already been used for a move-related variable (assuming that
  5439. they do not interfere). Of course, this preference should not override
  5440. the preference for registers over stack locations. So this preference
  5441. should be used as a tie breaker when choosing between registers or
  5442. when choosing between stack locations.
  5443. We recommend representing the move relationships in a graph, similar
  5444. to how we represented interference. The following is the \emph{move
  5445. graph} for our running example.
  5446. {\if\edition\racketEd
  5447. \[
  5448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5449. \node (rax) at (0,0) {$\ttm{rax}$};
  5450. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5451. \node (t) at (0,2) {$\ttm{t}$};
  5452. \node (z) at (3,2) {$\ttm{z}$};
  5453. \node (x) at (6,2) {$\ttm{x}$};
  5454. \node (y) at (3,0) {$\ttm{y}$};
  5455. \node (w) at (6,0) {$\ttm{w}$};
  5456. \node (v) at (9,0) {$\ttm{v}$};
  5457. \draw (v) to (x);
  5458. \draw (x) to (y);
  5459. \draw (x) to (z);
  5460. \draw (y) to (t);
  5461. \end{tikzpicture}
  5462. \]
  5463. \fi}
  5464. %
  5465. {\if\edition\pythonEd
  5466. \[
  5467. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5468. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5469. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5470. \node (z) at (3,2) {$\ttm{z}$};
  5471. \node (x) at (6,2) {$\ttm{x}$};
  5472. \node (y) at (3,0) {$\ttm{y}$};
  5473. \node (w) at (6,0) {$\ttm{w}$};
  5474. \node (v) at (9,0) {$\ttm{v}$};
  5475. \draw (y) to (t0);
  5476. \draw (z) to (x);
  5477. \draw (z) to (t1);
  5478. \draw (x) to (y);
  5479. \draw (x) to (v);
  5480. \end{tikzpicture}
  5481. \]
  5482. \fi}
  5483. {\if\edition\racketEd
  5484. Now we replay the graph coloring, pausing to see the coloring of
  5485. \code{y}. Recall the following configuration. The most saturated vertices
  5486. were \code{w} and \code{y}.
  5487. \[
  5488. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5489. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5490. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5491. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5492. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5493. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5494. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5495. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5496. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5497. \draw (t1) to (rax);
  5498. \draw (t1) to (z);
  5499. \draw (z) to (y);
  5500. \draw (z) to (w);
  5501. \draw (x) to (w);
  5502. \draw (y) to (w);
  5503. \draw (v) to (w);
  5504. \draw (v) to (rsp);
  5505. \draw (w) to (rsp);
  5506. \draw (x) to (rsp);
  5507. \draw (y) to (rsp);
  5508. \path[-.,bend left=15] (z) edge node {} (rsp);
  5509. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5510. \draw (rax) to (rsp);
  5511. \end{tikzpicture}
  5512. \]
  5513. %
  5514. Last time we chose to color \code{w} with $0$. But this time we see
  5515. that \code{w} is not move related to any vertex, but \code{y} is move
  5516. related to \code{t}. So we choose to color \code{y} the same color as
  5517. \code{t}, $0$.
  5518. \[
  5519. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5520. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5521. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5522. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5523. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5524. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5525. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5526. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5527. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5528. \draw (t1) to (rax);
  5529. \draw (t1) to (z);
  5530. \draw (z) to (y);
  5531. \draw (z) to (w);
  5532. \draw (x) to (w);
  5533. \draw (y) to (w);
  5534. \draw (v) to (w);
  5535. \draw (v) to (rsp);
  5536. \draw (w) to (rsp);
  5537. \draw (x) to (rsp);
  5538. \draw (y) to (rsp);
  5539. \path[-.,bend left=15] (z) edge node {} (rsp);
  5540. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5541. \draw (rax) to (rsp);
  5542. \end{tikzpicture}
  5543. \]
  5544. Now \code{w} is the most saturated, so we color it $2$.
  5545. \[
  5546. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5547. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5548. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5549. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5550. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5551. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5552. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5553. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5554. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5555. \draw (t1) to (rax);
  5556. \draw (t1) to (z);
  5557. \draw (z) to (y);
  5558. \draw (z) to (w);
  5559. \draw (x) to (w);
  5560. \draw (y) to (w);
  5561. \draw (v) to (w);
  5562. \draw (v) to (rsp);
  5563. \draw (w) to (rsp);
  5564. \draw (x) to (rsp);
  5565. \draw (y) to (rsp);
  5566. \path[-.,bend left=15] (z) edge node {} (rsp);
  5567. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5568. \draw (rax) to (rsp);
  5569. \end{tikzpicture}
  5570. \]
  5571. At this point, vertices \code{x} and \code{v} are most saturated, but
  5572. \code{x} is move related to \code{y} and \code{z}, so we color
  5573. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5574. \[
  5575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5576. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5577. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5578. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5579. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5580. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5581. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5582. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5583. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5584. \draw (t1) to (rax);
  5585. \draw (t) to (z);
  5586. \draw (z) to (y);
  5587. \draw (z) to (w);
  5588. \draw (x) to (w);
  5589. \draw (y) to (w);
  5590. \draw (v) to (w);
  5591. \draw (v) to (rsp);
  5592. \draw (w) to (rsp);
  5593. \draw (x) to (rsp);
  5594. \draw (y) to (rsp);
  5595. \path[-.,bend left=15] (z) edge node {} (rsp);
  5596. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5597. \draw (rax) to (rsp);
  5598. \end{tikzpicture}
  5599. \]
  5600. \fi}
  5601. %
  5602. {\if\edition\pythonEd
  5603. Now we replay the graph coloring, pausing before the coloring of
  5604. \code{w}. Recall the following configuration. The most saturated vertices
  5605. were \code{tmp\_1}, \code{w}, and \code{y}.
  5606. \[
  5607. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5608. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5609. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5610. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5611. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5612. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5613. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5614. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5615. \draw (t0) to (t1);
  5616. \draw (t0) to (z);
  5617. \draw (z) to (y);
  5618. \draw (z) to (w);
  5619. \draw (x) to (w);
  5620. \draw (y) to (w);
  5621. \draw (v) to (w);
  5622. \end{tikzpicture}
  5623. \]
  5624. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5625. or \code{y}, but note that \code{w} is not move related to any
  5626. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5627. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5628. \code{y} and color it $0$, we can delete another move instruction.
  5629. \[
  5630. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5631. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5632. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5633. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5634. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5635. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5636. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5637. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5638. \draw (t0) to (t1);
  5639. \draw (t0) to (z);
  5640. \draw (z) to (y);
  5641. \draw (z) to (w);
  5642. \draw (x) to (w);
  5643. \draw (y) to (w);
  5644. \draw (v) to (w);
  5645. \end{tikzpicture}
  5646. \]
  5647. Now \code{w} is the most saturated, so we color it $2$.
  5648. \[
  5649. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5650. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5651. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5652. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5653. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5654. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5655. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5656. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5657. \draw (t0) to (t1);
  5658. \draw (t0) to (z);
  5659. \draw (z) to (y);
  5660. \draw (z) to (w);
  5661. \draw (x) to (w);
  5662. \draw (y) to (w);
  5663. \draw (v) to (w);
  5664. \end{tikzpicture}
  5665. \]
  5666. To finish the coloring, \code{x} and \code{v} get $0$ and
  5667. \code{tmp\_1} gets $1$.
  5668. \[
  5669. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5670. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5671. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5672. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5673. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5674. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5675. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5676. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5677. \draw (t0) to (t1);
  5678. \draw (t0) to (z);
  5679. \draw (z) to (y);
  5680. \draw (z) to (w);
  5681. \draw (x) to (w);
  5682. \draw (y) to (w);
  5683. \draw (v) to (w);
  5684. \end{tikzpicture}
  5685. \]
  5686. \fi}
  5687. So we have the following assignment of variables to registers.
  5688. {\if\edition\racketEd
  5689. \begin{gather*}
  5690. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5691. \ttm{w} \mapsto \key{\%rsi}, \,
  5692. \ttm{x} \mapsto \key{\%rcx}, \,
  5693. \ttm{y} \mapsto \key{\%rcx}, \,
  5694. \ttm{z} \mapsto \key{\%rdx}, \,
  5695. \ttm{t} \mapsto \key{\%rcx} \}
  5696. \end{gather*}
  5697. \fi}
  5698. {\if\edition\pythonEd
  5699. \begin{gather*}
  5700. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5701. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5702. \ttm{x} \mapsto \key{\%rcx}, \,
  5703. \ttm{y} \mapsto \key{\%rcx}, \\
  5704. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5705. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5706. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5707. \end{gather*}
  5708. \fi}
  5709. We apply this register assignment to the running example, on the left,
  5710. to obtain the code in the middle. The \code{patch\_instructions} then
  5711. deletes the trivial moves to obtain the code on the right.
  5712. {\if\edition\racketEd
  5713. \begin{minipage}{0.25\textwidth}
  5714. \begin{lstlisting}
  5715. movq $1, v
  5716. movq $42, w
  5717. movq v, x
  5718. addq $7, x
  5719. movq x, y
  5720. movq x, z
  5721. addq w, z
  5722. movq y, t
  5723. negq t
  5724. movq z, %rax
  5725. addq t, %rax
  5726. jmp conclusion
  5727. \end{lstlisting}
  5728. \end{minipage}
  5729. $\Rightarrow\qquad$
  5730. \begin{minipage}{0.25\textwidth}
  5731. \begin{lstlisting}
  5732. movq $1, %rcx
  5733. movq $42, %rsi
  5734. movq %rcx, %rcx
  5735. addq $7, %rcx
  5736. movq %rcx, %rcx
  5737. movq %rcx, %rdx
  5738. addq %rsi, %rdx
  5739. movq %rcx, %rcx
  5740. negq %rcx
  5741. movq %rdx, %rax
  5742. addq %rcx, %rax
  5743. jmp conclusion
  5744. \end{lstlisting}
  5745. \end{minipage}
  5746. $\Rightarrow\qquad$
  5747. \begin{minipage}{0.25\textwidth}
  5748. \begin{lstlisting}
  5749. movq $1, %rcx
  5750. movq $42, %rsi
  5751. addq $7, %rcx
  5752. movq %rcx, %rdx
  5753. addq %rsi, %rdx
  5754. negq %rcx
  5755. movq %rdx, %rax
  5756. addq %rcx, %rax
  5757. jmp conclusion
  5758. \end{lstlisting}
  5759. \end{minipage}
  5760. \fi}
  5761. {\if\edition\pythonEd
  5762. \begin{minipage}{0.20\textwidth}
  5763. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5764. movq $1, v
  5765. movq $42, w
  5766. movq v, x
  5767. addq $7, x
  5768. movq x, y
  5769. movq x, z
  5770. addq w, z
  5771. movq y, tmp_0
  5772. negq tmp_0
  5773. movq z, tmp_1
  5774. addq tmp_0, tmp_1
  5775. movq tmp_1, %rdi
  5776. callq _print_int
  5777. \end{lstlisting}
  5778. \end{minipage}
  5779. ${\Rightarrow\qquad}$
  5780. \begin{minipage}{0.30\textwidth}
  5781. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5782. movq $1, %rcx
  5783. movq $42, -16(%rbp)
  5784. movq %rcx, %rcx
  5785. addq $7, %rcx
  5786. movq %rcx, %rcx
  5787. movq %rcx, -8(%rbp)
  5788. addq -16(%rbp), -8(%rbp)
  5789. movq %rcx, %rcx
  5790. negq %rcx
  5791. movq -8(%rbp), -8(%rbp)
  5792. addq %rcx, -8(%rbp)
  5793. movq -8(%rbp), %rdi
  5794. callq _print_int
  5795. \end{lstlisting}
  5796. \end{minipage}
  5797. ${\Rightarrow\qquad}$
  5798. \begin{minipage}{0.20\textwidth}
  5799. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5800. movq $1, %rcx
  5801. movq $42, -16(%rbp)
  5802. addq $7, %rcx
  5803. movq %rcx, -8(%rbp)
  5804. movq -16(%rbp), %rax
  5805. addq %rax, -8(%rbp)
  5806. negq %rcx
  5807. addq %rcx, -8(%rbp)
  5808. movq -8(%rbp), %rdi
  5809. callq print_int
  5810. \end{lstlisting}
  5811. \end{minipage}
  5812. \fi}
  5813. \begin{exercise}\normalfont
  5814. Change your implementation of \code{allocate\_registers} to take move
  5815. biasing into account. Create two new tests that include at least one
  5816. opportunity for move biasing and visually inspect the output x86
  5817. programs to make sure that your move biasing is working properly. Make
  5818. sure that your compiler still passes all of the tests.
  5819. \end{exercise}
  5820. %To do: another neat challenge would be to do
  5821. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5822. %% \subsection{Output of the Running Example}
  5823. %% \label{sec:reg-alloc-output}
  5824. % challenge: prioritize variables based on execution frequencies
  5825. % and the number of uses of a variable
  5826. % challenge: enhance the coloring algorithm using Chaitin's
  5827. % approach of prioritizing high-degree variables
  5828. % by removing low-degree variables (coloring them later)
  5829. % from the interference graph
  5830. \section{Further Reading}
  5831. \label{sec:register-allocation-further-reading}
  5832. Early register allocation algorithms were developed for Fortran
  5833. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5834. of graph coloring began in the late 1970s and early 1980s with the
  5835. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5836. algorithm is based on the following observation of
  5837. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5838. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5839. $v$ removed is also $k$ colorable. To see why, suppose that the
  5840. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5841. different colors, but since there are less than $k$ neighbors, there
  5842. will be one or more colors left over to use for coloring $v$ in $G$.
  5843. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5844. less than $k$ from the graph and recursively colors the rest of the
  5845. graph. Upon returning from the recursion, it colors $v$ with one of
  5846. the available colors and returns. \citet{Chaitin:1982vn} augments
  5847. this algorithm to handle spilling as follows. If there are no vertices
  5848. of degree lower than $k$ then pick a vertex at random, spill it,
  5849. remove it from the graph, and proceed recursively to color the rest of
  5850. the graph.
  5851. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5852. move-related and that don't interfere with each other, a process
  5853. called \emph{coalescing}. While coalescing decreases the number of
  5854. moves, it can make the graph more difficult to
  5855. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5856. which two variables are merged only if they have fewer than $k$
  5857. neighbors of high degree. \citet{George:1996aa} observe that
  5858. conservative coalescing is sometimes too conservative and make it more
  5859. aggressive by iterating the coalescing with the removal of low-degree
  5860. vertices.
  5861. %
  5862. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5863. also propose \emph{biased coloring} in which a variable is assigned to
  5864. the same color as another move-related variable if possible, as
  5865. discussed in Section~\ref{sec:move-biasing}.
  5866. %
  5867. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5868. performs coalescing, graph coloring, and spill code insertion until
  5869. all variables have been assigned a location.
  5870. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5871. spills variables that don't have to be: a high-degree variable can be
  5872. colorable if many of its neighbors are assigned the same color.
  5873. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5874. high-degree vertex is not immediately spilled. Instead the decision is
  5875. deferred until after the recursive call, at which point it is apparent
  5876. whether there is actually an available color or not. We observe that
  5877. this algorithm is equivalent to the smallest-last ordering
  5878. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5879. be registers and the rest to be stack locations.
  5880. %% biased coloring
  5881. Earlier editions of the compiler course at Indiana University
  5882. \citep{Dybvig:2010aa} were based on the algorithm of
  5883. \citet{Briggs:1994kx}.
  5884. The smallest-last ordering algorithm is one of many \emph{greedy}
  5885. coloring algorithms. A greedy coloring algorithm visits all the
  5886. vertices in a particular order and assigns each one the first
  5887. available color. An \emph{offline} greedy algorithm chooses the
  5888. ordering up-front, prior to assigning colors. The algorithm of
  5889. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5890. ordering does not depend on the colors assigned. Other orderings are
  5891. possible. For example, \citet{Chow:1984ys} order variables according
  5892. to an estimate of runtime cost.
  5893. An \emph{online} greedy coloring algorithm uses information about the
  5894. current assignment of colors to influence the order in which the
  5895. remaining vertices are colored. The saturation-based algorithm
  5896. described in this chapter is one such algorithm. We choose to use
  5897. saturation-based coloring because it is fun to introduce graph
  5898. coloring via Sudoku!
  5899. A register allocator may choose to map each variable to just one
  5900. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5901. variable to one or more locations. The later can be achieved by
  5902. \emph{live range splitting}, where a variable is replaced by several
  5903. variables that each handle part of its live
  5904. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5905. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5906. %% replacement algorithm, bottom-up local
  5907. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5908. %% Cooper: top-down (priority bassed), bottom-up
  5909. %% top-down
  5910. %% order variables by priority (estimated cost)
  5911. %% caveat: split variables into two groups:
  5912. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5913. %% color the constrained ones first
  5914. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5915. %% cite J. Cocke for an algorithm that colors variables
  5916. %% in a high-degree first ordering
  5917. %Register Allocation via Usage Counts, Freiburghouse CACM
  5918. \citet{Palsberg:2007si} observe that many of the interference graphs
  5919. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5920. that is, every cycle with four or more edges has an edge which is not
  5921. part of the cycle but which connects two vertices on the cycle. Such
  5922. graphs can be optimally colored by the greedy algorithm with a vertex
  5923. ordering determined by maximum cardinality search.
  5924. In situations where compile time is of utmost importance, such as in
  5925. just-in-time compilers, graph coloring algorithms can be too expensive
  5926. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5927. appropriate.
  5928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5929. \chapter{Booleans and Conditionals}
  5930. \label{ch:Lif}
  5931. \index{subject}{Boolean}
  5932. \index{subject}{control flow}
  5933. \index{subject}{conditional expression}
  5934. The \LangInt{} and \LangVar{} languages only have a single kind of
  5935. value, the integers. In this chapter we add a second kind of value,
  5936. the Booleans, to create the \LangIf{} language. The Boolean values
  5937. \emph{true} and \emph{false} are written \TRUE{} and \FALSE{}
  5938. respectively in \racket{Racket}\python{Python}. The \LangIf{}
  5939. language includes several operations that involve Booleans (\key{and},
  5940. \key{not}, \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the
  5941. \key{if} expression \python{and statement}. With the addition of
  5942. \key{if}, programs can have non-trivial control flow which
  5943. %
  5944. \racket{impacts \code{explicate\_control} and liveness analysis}
  5945. %
  5946. \python{impacts liveness analysis and motivates a new pass named
  5947. \code{explicate\_control}}.
  5948. %
  5949. Also, because we now have two kinds of values, we need to handle
  5950. programs that apply an operation to the wrong kind of value, such as
  5951. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5952. There are two language design options for such situations. One option
  5953. is to signal an error and the other is to provide a wider
  5954. interpretation of the operation. \racket{The Racket
  5955. language}\python{Python} uses a mixture of these two options,
  5956. depending on the operation and the kind of value. For example, the
  5957. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  5958. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  5959. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  5960. %
  5961. \racket{On the other hand, \code{(car 1)} results in a run-time error
  5962. in Racket because \code{car} expects a pair.}
  5963. %
  5964. \python{On the other hand, \code{1[0]} results in a run-time error
  5965. in Python because an ``\code{int} object is not subscriptable''.}
  5966. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  5967. design choices as \racket{Racket}\python{Python}, except much of the
  5968. error detection happens at compile time instead of run
  5969. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  5970. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  5971. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  5972. Racket}\python{MyPy} reports a compile-time error
  5973. %
  5974. \racket{because Racket expects the type of the argument to be of the form
  5975. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  5976. %
  5977. \python{stating that a ``value of type \code{int} is not indexable''.}
  5978. The \LangIf{} language performs type checking during compilation like
  5979. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study the
  5980. alternative choice, that is, a dynamically typed language like
  5981. \racket{Racket}\python{Python}.
  5982. The \LangIf{} language is a subset of \racket{Typed Racket}\python{MyPy};
  5983. for some operations we are more restrictive, for example, rejecting
  5984. \racket{\code{(not 1)}}\python{\code{not 1}}.
  5985. This chapter is organized as follows. We begin by defining the syntax
  5986. and interpreter for the \LangIf{} language
  5987. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  5988. checking and define a type checker for \LangIf{}
  5989. (Section~\ref{sec:type-check-Lif}).
  5990. %
  5991. \racket{To compile \LangIf{} we need to enlarge the intermediate
  5992. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  5993. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  5994. %
  5995. The remaining sections of this chapter discuss how the addition of
  5996. Booleans and conditional control flow to the language requires changes
  5997. to the existing compiler passes and the addition of new ones. In
  5998. particular, we introduce the \code{shrink} pass to translates some
  5999. operators into others, thereby reducing the number of operators that
  6000. need to be handled in later passes.
  6001. %
  6002. The main event of this chapter is the \code{explicate\_control} pass
  6003. that is responsible for translating \code{if}'s into conditional
  6004. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6005. %
  6006. Regarding register allocation, there is the interesting question of
  6007. how to handle conditional \code{goto}'s during liveness analysis.
  6008. \section{The \LangIf{} Language}
  6009. \label{sec:lang-if}
  6010. The concrete and abstract syntax of the \LangIf{} language are defined in
  6011. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6012. respectively. The \LangIf{} language includes all of
  6013. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6014. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6015. \code{if} statement}. We expand the set of operators to include
  6016. \begin{enumerate}
  6017. \item subtraction on integers,
  6018. \item the logical operators \key{and}, \key{or}, and \key{not},
  6019. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6020. for comparing integers or Booleans for equality, and
  6021. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6022. comparing integers.
  6023. \end{enumerate}
  6024. \racket{We reorganize the abstract syntax for the primitive
  6025. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6026. rule for all of them. This means that the grammar no longer checks
  6027. whether the arity of an operators matches the number of
  6028. arguments. That responsibility is moved to the type checker for
  6029. \LangIf{}, which we introduce in Section~\ref{sec:type-check-Lif}.}
  6030. \newcommand{\LifGrammarRacket}{
  6031. \begin{array}{lcl}
  6032. \Type &::=& \key{Boolean} \\
  6033. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6034. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6035. \Exp &::=& \CSUB{\Exp}{\Exp} \MID \itm{bool}
  6036. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6037. \MID (\key{not}\;\Exp) \\
  6038. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6039. \end{array}
  6040. }
  6041. \newcommand{\LifASTRacket}{
  6042. \begin{array}{lcl}
  6043. \Type &::=& \key{Boolean} \\
  6044. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6045. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6046. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6047. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6048. \end{array}
  6049. }
  6050. \newcommand{\LintOpAST}{
  6051. \begin{array}{rcl}
  6052. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6053. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6054. \end{array}
  6055. }
  6056. \newcommand{\LifGrammarPython}{
  6057. \begin{array}{rcl}
  6058. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6059. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6060. \MID \key{not}~\Exp \\
  6061. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6062. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6063. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6064. \end{array}
  6065. }
  6066. \newcommand{\LifASTPython}{
  6067. \begin{array}{lcl}
  6068. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6069. \itm{unaryop} &::=& \code{Not()} \\
  6070. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6071. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6072. \Exp &::=& \BOOL{\itm{bool}}
  6073. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6074. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6075. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6076. \end{array}
  6077. }
  6078. \begin{figure}[tp]
  6079. \centering
  6080. \fbox{
  6081. \begin{minipage}{0.96\textwidth}
  6082. {\if\edition\racketEd
  6083. \[
  6084. \begin{array}{l}
  6085. \gray{\LintGrammarRacket{}} \\ \hline
  6086. \gray{\LvarGrammarRacket{}} \\ \hline
  6087. \LifGrammarRacket{} \\
  6088. \begin{array}{lcl}
  6089. \LangIfM{} &::=& \Exp
  6090. \end{array}
  6091. \end{array}
  6092. \]
  6093. \fi}
  6094. {\if\edition\pythonEd
  6095. \[
  6096. \begin{array}{l}
  6097. \gray{\LintGrammarPython} \\ \hline
  6098. \gray{\LvarGrammarPython} \\ \hline
  6099. \LifGrammarPython \\
  6100. \begin{array}{rcl}
  6101. \LangIfM{} &::=& \Stmt^{*}
  6102. \end{array}
  6103. \end{array}
  6104. \]
  6105. \fi}
  6106. \end{minipage}
  6107. }
  6108. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6109. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6110. \label{fig:Lif-concrete-syntax}
  6111. \end{figure}
  6112. \begin{figure}[tp]
  6113. \centering
  6114. \fbox{
  6115. \begin{minipage}{0.96\textwidth}
  6116. {\if\edition\racketEd
  6117. \[
  6118. \begin{array}{l}
  6119. \gray{\LintOpAST} \\ \hline
  6120. \gray{\LvarASTRacket{}} \\ \hline
  6121. \LifASTRacket{} \\
  6122. \begin{array}{lcl}
  6123. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6124. \end{array}
  6125. \end{array}
  6126. \]
  6127. \fi}
  6128. {\if\edition\pythonEd
  6129. \[
  6130. \begin{array}{l}
  6131. \gray{\LintASTPython} \\ \hline
  6132. \gray{\LvarASTPython} \\ \hline
  6133. \LifASTPython \\
  6134. \begin{array}{lcl}
  6135. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6136. \end{array}
  6137. \end{array}
  6138. \]
  6139. \fi}
  6140. \end{minipage}
  6141. }
  6142. \caption{The abstract syntax of \LangIf{}.}
  6143. \label{fig:Lif-syntax}
  6144. \end{figure}
  6145. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6146. which inherits from the interpreter for \LangVar{}
  6147. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6148. evaluate to the corresponding Boolean values. The conditional
  6149. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6150. and then either evaluates $e_2$ or $e_3$ depending on whether
  6151. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6152. \code{and}, \code{or}, and \code{not} behave according to
  6153. propositional logic. In addition, the \code{and} and \code{or}
  6154. operations perform \emph{short-circuit evaluation}.
  6155. %
  6156. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6157. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6158. %
  6159. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6160. evaluated if $e_1$ evaluates to \TRUE{}.
  6161. \racket{With the increase in the number of primitive operations, the
  6162. interpreter would become repetitive without some care. We refactor
  6163. the case for \code{Prim}, moving the code that differs with each
  6164. operation into the \code{interp\_op} method shown in in
  6165. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6166. \code{or} operations separately because of their short-circuiting
  6167. behavior.}
  6168. \begin{figure}[tbp]
  6169. {\if\edition\racketEd
  6170. \begin{lstlisting}
  6171. (define interp_Lif_class
  6172. (class interp_Lvar_class
  6173. (super-new)
  6174. (define/public (interp_op op) ...)
  6175. (define/override ((interp_exp env) e)
  6176. (define recur (interp_exp env))
  6177. (match e
  6178. [(Bool b) b]
  6179. [(If cnd thn els)
  6180. (match (recur cnd)
  6181. [#t (recur thn)]
  6182. [#f (recur els)])]
  6183. [(Prim 'and (list e1 e2))
  6184. (match (recur e1)
  6185. [#t (match (recur e2) [#t #t] [#f #f])]
  6186. [#f #f])]
  6187. [(Prim 'or (list e1 e2))
  6188. (define v1 (recur e1))
  6189. (match v1
  6190. [#t #t]
  6191. [#f (match (recur e2) [#t #t] [#f #f])])]
  6192. [(Prim op args)
  6193. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6194. [else ((super interp_exp env) e)]))
  6195. ))
  6196. (define (interp_Lif p)
  6197. (send (new interp_Lif_class) interp_program p))
  6198. \end{lstlisting}
  6199. \fi}
  6200. {\if\edition\pythonEd
  6201. \begin{lstlisting}
  6202. class InterpLif(InterpLvar):
  6203. def interp_exp(self, e, env):
  6204. match e:
  6205. case IfExp(test, body, orelse):
  6206. if self.interp_exp(test, env):
  6207. return self.interp_exp(body, env)
  6208. else:
  6209. return self.interp_exp(orelse, env)
  6210. case BinOp(left, Sub(), right):
  6211. return self.interp_exp(left, env) - self.interp_exp(right, env)
  6212. case UnaryOp(Not(), v):
  6213. return not self.interp_exp(v, env)
  6214. case BoolOp(And(), values):
  6215. if self.interp_exp(values[0], env):
  6216. return self.interp_exp(values[1], env)
  6217. else:
  6218. return False
  6219. case BoolOp(Or(), values):
  6220. if self.interp_exp(values[0], env):
  6221. return True
  6222. else:
  6223. return self.interp_exp(values[1], env)
  6224. case Compare(left, [cmp], [right]):
  6225. l = self.interp_exp(left, env)
  6226. r = self.interp_exp(right, env)
  6227. return self.interp_cmp(cmp)(l, r)
  6228. case _:
  6229. return super().interp_exp(e, env)
  6230. def interp_stmts(self, ss, env):
  6231. if len(ss) == 0:
  6232. return
  6233. match ss[0]:
  6234. case If(test, body, orelse):
  6235. if self.interp_exp(test, env):
  6236. return self.interp_stmts(body + ss[1:], env)
  6237. else:
  6238. return self.interp_stmts(orelse + ss[1:], env)
  6239. case _:
  6240. return super().interp_stmts(ss, env)
  6241. ...
  6242. \end{lstlisting}
  6243. \fi}
  6244. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6245. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6246. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6247. \label{fig:interp-Lif}
  6248. \end{figure}
  6249. {\if\edition\racketEd
  6250. \begin{figure}[tbp]
  6251. \begin{lstlisting}
  6252. (define/public (interp_op op)
  6253. (match op
  6254. ['+ fx+]
  6255. ['- fx-]
  6256. ['read read-fixnum]
  6257. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6258. ['eq? (lambda (v1 v2)
  6259. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6260. (and (boolean? v1) (boolean? v2))
  6261. (and (vector? v1) (vector? v2)))
  6262. (eq? v1 v2)]))]
  6263. ['< (lambda (v1 v2)
  6264. (cond [(and (fixnum? v1) (fixnum? v2))
  6265. (< v1 v2)]))]
  6266. ['<= (lambda (v1 v2)
  6267. (cond [(and (fixnum? v1) (fixnum? v2))
  6268. (<= v1 v2)]))]
  6269. ['> (lambda (v1 v2)
  6270. (cond [(and (fixnum? v1) (fixnum? v2))
  6271. (> v1 v2)]))]
  6272. ['>= (lambda (v1 v2)
  6273. (cond [(and (fixnum? v1) (fixnum? v2))
  6274. (>= v1 v2)]))]
  6275. [else (error 'interp_op "unknown operator")]))
  6276. \end{lstlisting}
  6277. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6278. \label{fig:interp-op-Lif}
  6279. \end{figure}
  6280. \fi}
  6281. {\if\edition\pythonEd
  6282. \begin{figure}
  6283. \begin{lstlisting}
  6284. class InterpLif(InterpLvar):
  6285. ...
  6286. def interp_cmp(self, cmp):
  6287. match cmp:
  6288. case Lt():
  6289. return lambda x, y: x < y
  6290. case LtE():
  6291. return lambda x, y: x <= y
  6292. case Gt():
  6293. return lambda x, y: x > y
  6294. case GtE():
  6295. return lambda x, y: x >= y
  6296. case Eq():
  6297. return lambda x, y: x == y
  6298. case NotEq():
  6299. return lambda x, y: x != y
  6300. \end{lstlisting}
  6301. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6302. \label{fig:interp-cmp-Lif}
  6303. \end{figure}
  6304. \fi}
  6305. \section{Type Checking \LangIf{} Programs}
  6306. \label{sec:type-check-Lif}
  6307. \index{subject}{type checking}
  6308. \index{subject}{semantic analysis}
  6309. It is helpful to think about type checking in two complementary
  6310. ways. A type checker predicts the type of value that will be produced
  6311. by each expression in the program. For \LangIf{}, we have just two types,
  6312. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6313. {\if\edition\racketEd
  6314. \begin{lstlisting}
  6315. (+ 10 (- (+ 12 20)))
  6316. \end{lstlisting}
  6317. \fi}
  6318. {\if\edition\pythonEd
  6319. \begin{lstlisting}
  6320. 10 + -(12 + 20)
  6321. \end{lstlisting}
  6322. \fi}
  6323. \noindent produces a value of type \INTTY{} while
  6324. {\if\edition\racketEd
  6325. \begin{lstlisting}
  6326. (and (not #f) #t)
  6327. \end{lstlisting}
  6328. \fi}
  6329. {\if\edition\pythonEd
  6330. \begin{lstlisting}
  6331. (not False) and True
  6332. \end{lstlisting}
  6333. \fi}
  6334. \noindent produces a value of type \BOOLTY{}.
  6335. A second way to think about type checking is that it enforces a set of
  6336. rules about which operators can be applied to which kinds of
  6337. values. For example, our type checker for \LangIf{} signals an error
  6338. for the below expression {\if\edition\racketEd
  6339. \begin{lstlisting}
  6340. (not (+ 10 (- (+ 12 20))))
  6341. \end{lstlisting}
  6342. \fi}
  6343. {\if\edition\pythonEd
  6344. \begin{lstlisting}
  6345. not (10 + -(12 + 20))
  6346. \end{lstlisting}
  6347. \fi}
  6348. The subexpression
  6349. \racket{\code{(+ 10 (- (+ 12 20)))}}\python{\code{(10 + -(12 + 20))}}
  6350. has type \INTTY{} but the type checker enforces the rule that the argument of
  6351. \code{not} must be an expression of type \BOOLTY{}.
  6352. We implement type checking using classes and methods because they
  6353. provide the open recursion needed to reuse code as we extend the type
  6354. checker in later chapters, analogous to the use of classes and methods
  6355. for the interpreters (Section~\ref{sec:extensible-interp}).
  6356. We separate the type checker for the \LangVar{} subset into its own
  6357. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6358. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6359. from the type checker for \LangVar{}. These type checkers are in the
  6360. files
  6361. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6362. and
  6363. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6364. of the support code.
  6365. %
  6366. Each type checker is a structurally recursive function over the AST.
  6367. Given an input expression \code{e}, the type checker either signals an
  6368. error or returns \racket{an expression and} its type (\INTTY{} or
  6369. \BOOLTY{}).
  6370. %
  6371. \racket{It returns an expression because there are situations in which
  6372. we want to change or update the expression.}
  6373. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6374. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6375. \INTTY{}. To handle variables, the type checker uses the environment
  6376. \code{env} to map variables to types.
  6377. %
  6378. \racket{Consider the case for \key{let}. We type check the
  6379. initializing expression to obtain its type \key{T} and then
  6380. associate type \code{T} with the variable \code{x} in the
  6381. environment used to type check the body of the \key{let}. Thus,
  6382. when the type checker encounters a use of variable \code{x}, it can
  6383. find its type in the environment.}
  6384. %
  6385. \python{Consider the case for assignment. We type check the
  6386. initializing expression to obtain its type \key{t}. If the variable
  6387. \code{lhs.id} is already in the environment because there was a
  6388. prior assignment, we check that this initializer has the same type
  6389. as the prior one. If this is the first assignment to the variable,
  6390. we associate type \code{t} with the variable \code{lhs.id} in the
  6391. environment. Thus, when the type checker encounters a use of
  6392. variable \code{x}, it can find its type in the environment.}
  6393. %
  6394. \racket{Regarding primitive operators, we recursively analyze the
  6395. arguments and then invoke \code{type\_check\_op} to check whether
  6396. the argument types are allowed.}
  6397. %
  6398. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6399. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6400. \racket{Several auxiliary methods are used in the type checker. The
  6401. method \code{operator-types} defines a dictionary that maps the
  6402. operator names to their parameter and return types. The
  6403. \code{type-equal?} method determines whether two types are equal,
  6404. which for now simply dispatches to \code{equal?} (deep
  6405. equality). The \code{check-type-equal?} method triggers an error if
  6406. the two types are not equal. The \code{type-check-op} method looks
  6407. up the operator in the \code{operator-types} dictionary and then
  6408. checks whether the argument types are equal to the parameter types.
  6409. The result is the return type of the operator.}
  6410. %
  6411. \python{The auxiliary method \code{check\_type\_equal} triggers
  6412. an error if the two types are not equal.}
  6413. \begin{figure}[tbp]
  6414. {\if\edition\racketEd
  6415. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6416. (define type-check-Lvar_class
  6417. (class object%
  6418. (super-new)
  6419. (define/public (operator-types)
  6420. '((+ . ((Integer Integer) . Integer))
  6421. (- . ((Integer) . Integer))
  6422. (read . (() . Integer))))
  6423. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6424. (define/public (check-type-equal? t1 t2 e)
  6425. (unless (type-equal? t1 t2)
  6426. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6427. (define/public (type-check-op op arg-types e)
  6428. (match (dict-ref (operator-types) op)
  6429. [`(,param-types . ,return-type)
  6430. (for ([at arg-types] [pt param-types])
  6431. (check-type-equal? at pt e))
  6432. return-type]
  6433. [else (error 'type-check-op "unrecognized ~a" op)]))
  6434. (define/public (type-check-exp env)
  6435. (lambda (e)
  6436. (match e
  6437. [(Int n) (values (Int n) 'Integer)]
  6438. [(Var x) (values (Var x) (dict-ref env x))]
  6439. [(Let x e body)
  6440. (define-values (e^ Te) ((type-check-exp env) e))
  6441. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6442. (values (Let x e^ b) Tb)]
  6443. [(Prim op es)
  6444. (define-values (new-es ts)
  6445. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6446. (values (Prim op new-es) (type-check-op op ts e))]
  6447. [else (error 'type-check-exp "couldn't match" e)])))
  6448. (define/public (type-check-program e)
  6449. (match e
  6450. [(Program info body)
  6451. (define-values (body^ Tb) ((type-check-exp '()) body))
  6452. (check-type-equal? Tb 'Integer body)
  6453. (Program info body^)]
  6454. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6455. ))
  6456. (define (type-check-Lvar p)
  6457. (send (new type-check-Lvar_class) type-check-program p))
  6458. \end{lstlisting}
  6459. \fi}
  6460. {\if\edition\pythonEd
  6461. \begin{lstlisting}[escapechar=`]
  6462. class TypeCheckLvar:
  6463. def check_type_equal(self, t1, t2, e):
  6464. if t1 != t2:
  6465. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6466. raise Exception(msg)
  6467. def type_check_exp(self, e, env):
  6468. match e:
  6469. case BinOp(left, (Add() | Sub()), right):
  6470. l = self.type_check_exp(left, env)
  6471. check_type_equal(l, int, left)
  6472. r = self.type_check_exp(right, env)
  6473. check_type_equal(r, int, right)
  6474. return int
  6475. case UnaryOp(USub(), v):
  6476. t = self.type_check_exp(v, env)
  6477. check_type_equal(t, int, v)
  6478. return int
  6479. case Name(id):
  6480. return env[id]
  6481. case Constant(value) if isinstance(value, int):
  6482. return int
  6483. case Call(Name('input_int'), []):
  6484. return int
  6485. def type_check_stmts(self, ss, env):
  6486. if len(ss) == 0:
  6487. return
  6488. match ss[0]:
  6489. case Assign([lhs], value):
  6490. t = self.type_check_exp(value, env)
  6491. if lhs.id in env:
  6492. check_type_equal(env[lhs.id], t, value)
  6493. else:
  6494. env[lhs.id] = t
  6495. return self.type_check_stmts(ss[1:], env)
  6496. case Expr(Call(Name('print'), [arg])):
  6497. t = self.type_check_exp(arg, env)
  6498. check_type_equal(t, int, arg)
  6499. return self.type_check_stmts(ss[1:], env)
  6500. case Expr(value):
  6501. self.type_check_exp(value, env)
  6502. return self.type_check_stmts(ss[1:], env)
  6503. def type_check_P(self, p):
  6504. match p:
  6505. case Module(body):
  6506. self.type_check_stmts(body, {})
  6507. \end{lstlisting}
  6508. \fi}
  6509. \caption{Type checker for the \LangVar{} language.}
  6510. \label{fig:type-check-Lvar}
  6511. \end{figure}
  6512. \begin{figure}[tbp]
  6513. {\if\edition\racketEd
  6514. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6515. (define type-check-Lif_class
  6516. (class type-check-Lvar_class
  6517. (super-new)
  6518. (inherit check-type-equal?)
  6519. (define/override (operator-types)
  6520. (append '((- . ((Integer Integer) . Integer))
  6521. (and . ((Boolean Boolean) . Boolean))
  6522. (or . ((Boolean Boolean) . Boolean))
  6523. (< . ((Integer Integer) . Boolean))
  6524. (<= . ((Integer Integer) . Boolean))
  6525. (> . ((Integer Integer) . Boolean))
  6526. (>= . ((Integer Integer) . Boolean))
  6527. (not . ((Boolean) . Boolean))
  6528. )
  6529. (super operator-types)))
  6530. (define/override (type-check-exp env)
  6531. (lambda (e)
  6532. (match e
  6533. [(Bool b) (values (Bool b) 'Boolean)]
  6534. [(Prim 'eq? (list e1 e2))
  6535. (define-values (e1^ T1) ((type-check-exp env) e1))
  6536. (define-values (e2^ T2) ((type-check-exp env) e2))
  6537. (check-type-equal? T1 T2 e)
  6538. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6539. [(If cnd thn els)
  6540. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6541. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6542. (define-values (els^ Te) ((type-check-exp env) els))
  6543. (check-type-equal? Tc 'Boolean e)
  6544. (check-type-equal? Tt Te e)
  6545. (values (If cnd^ thn^ els^) Te)]
  6546. [else ((super type-check-exp env) e)])))
  6547. ))
  6548. (define (type-check-Lif p)
  6549. (send (new type-check-Lif_class) type-check-program p))
  6550. \end{lstlisting}
  6551. \fi}
  6552. {\if\edition\pythonEd
  6553. \begin{lstlisting}
  6554. class TypeCheckLif(TypeCheckLvar):
  6555. def type_check_exp(self, e, env):
  6556. match e:
  6557. case Constant(value) if isinstance(value, bool):
  6558. return bool
  6559. case BinOp(left, Sub(), right):
  6560. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6561. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6562. return int
  6563. case UnaryOp(Not(), v):
  6564. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6565. return bool
  6566. case BoolOp(op, values):
  6567. left = values[0] ; right = values[1]
  6568. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6569. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6570. return bool
  6571. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6572. or isinstance(cmp, NotEq):
  6573. l = self.type_check_exp(left, env)
  6574. r = self.type_check_exp(right, env)
  6575. check_type_equal(l, r, e)
  6576. return bool
  6577. case Compare(left, [cmp], [right]):
  6578. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6579. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6580. return bool
  6581. case IfExp(test, body, orelse):
  6582. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6583. b = self.type_check_exp(body, env)
  6584. o = self.type_check_exp(orelse, env)
  6585. check_type_equal(b, o, e)
  6586. return b
  6587. case _:
  6588. return super().type_check_exp(e, env)
  6589. def type_check_stmts(self, ss, env):
  6590. if len(ss) == 0:
  6591. return
  6592. match ss[0]:
  6593. case If(test, body, orelse):
  6594. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6595. b = self.type_check_stmts(body, env)
  6596. o = self.type_check_stmts(orelse, env)
  6597. check_type_equal(b, o, ss[0])
  6598. return self.type_check_stmts(ss[1:], env)
  6599. case _:
  6600. return super().type_check_stmts(ss, env)
  6601. \end{lstlisting}
  6602. \fi}
  6603. \caption{Type checker for the \LangIf{} language.}
  6604. \label{fig:type-check-Lif}
  6605. \end{figure}
  6606. We shift our focus to Figure~\ref{fig:type-check-Lif}, the type
  6607. checker for \LangIf{}.
  6608. %
  6609. The type of a Boolean constant is \BOOLTY{}.
  6610. %
  6611. \racket{The \code{operator-types} function adds dictionary entries for
  6612. the other new operators.}
  6613. %
  6614. \python{Logical not requires its argument to be a \BOOLTY{} and
  6615. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6616. %
  6617. The equality operators require the two arguments to have the same
  6618. type.
  6619. %
  6620. \python{The other comparisons (less-than, etc.) require their
  6621. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6622. %
  6623. The condition of an \code{if} must
  6624. be of \BOOLTY{} type and the two branches must have the same type.
  6625. \begin{exercise}\normalfont
  6626. Create 10 new test programs in \LangIf{}. Half of the programs should
  6627. have a type error. For those programs, create an empty file with the
  6628. same base name but with file extension \code{.tyerr}. For example, if
  6629. the test
  6630. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6631. is expected to error, then create
  6632. an empty file named \code{cond\_test\_14.tyerr}.
  6633. %
  6634. \racket{This indicates to \code{interp-tests} and
  6635. \code{compiler-tests} that a type error is expected. }
  6636. %
  6637. The other half of the test programs should not have type errors.
  6638. %
  6639. \racket{In the \code{run-tests.rkt} script, change the second argument
  6640. of \code{interp-tests} and \code{compiler-tests} to
  6641. \code{type-check-Lif}, which causes the type checker to run prior to
  6642. the compiler passes. Temporarily change the \code{passes} to an
  6643. empty list and run the script, thereby checking that the new test
  6644. programs either type check or not as intended.}
  6645. %
  6646. Run the test script to check that these test programs type check as
  6647. expected.
  6648. \end{exercise}
  6649. \clearpage
  6650. \section{The \LangCIf{} Intermediate Language}
  6651. \label{sec:Cif}
  6652. {\if\edition\racketEd
  6653. %
  6654. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6655. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6656. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6657. language adds logical and comparison operators to the \Exp{}
  6658. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6659. non-terminal.
  6660. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6661. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6662. statement is a comparison operation and the branches are \code{goto}
  6663. statements, making it straightforward to compile \code{if} statements
  6664. to x86.
  6665. %
  6666. \fi}
  6667. %
  6668. {\if\edition\pythonEd
  6669. %
  6670. The output of \key{explicate\_control} is a language similar to the
  6671. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6672. \code{goto} statements, so we name it \LangCIf{}. The
  6673. concrete syntax for \LangCIf{} is defined in
  6674. Figure~\ref{fig:c1-concrete-syntax}
  6675. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6676. %
  6677. The \LangCIf{} language supports the same operators as \LangIf{} but
  6678. the arguments of operators are restricted to atomic expressions. The
  6679. \LangCIf{} language does not include \code{if} expressions but it does
  6680. include a restricted form of \code{if} statment. The condition must be
  6681. a comparison and the two branches may only contain \code{goto}
  6682. statements. These restrictions make it easier to translate \code{if}
  6683. statements to x86.
  6684. %
  6685. \fi}
  6686. %
  6687. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6688. \code{return} statement to finish a function call with a specified value.
  6689. %
  6690. The \key{CProgram} construct contains
  6691. %
  6692. \racket{an alist}\python{a dictionary}
  6693. %
  6694. mapping labels to
  6695. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6696. an assignment statement followed by a $\Tail$ expression, a
  6697. \code{goto}, or a conditional \code{goto}.}
  6698. \python{lists of statements, which comprise of assignment statements
  6699. and end in a \code{return} statement, a \code{goto}, or a
  6700. conditional \code{goto}.
  6701. \index{subject}{basic block}
  6702. Statement lists of this form are called
  6703. \emph{basic blocks}: there is a control transfer at the end and
  6704. control only enters at the beginning of the list, which is marked by
  6705. the label. }
  6706. \newcommand{\CifGrammarRacket}{
  6707. \begin{array}{lcl}
  6708. \Atm &::=& \itm{bool} \\
  6709. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6710. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6711. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6712. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6713. \end{array}
  6714. }
  6715. \newcommand{\CifASTRacket}{
  6716. \begin{array}{lcl}
  6717. \Atm &::=& \BOOL{\itm{bool}} \\
  6718. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6719. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6720. \Tail &::= & \GOTO{\itm{label}} \\
  6721. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6722. \end{array}
  6723. }
  6724. \newcommand{\CifGrammarPython}{
  6725. \begin{array}{lcl}
  6726. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6727. \Exp &::= & \Atm \MID \CREAD{}
  6728. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6729. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6730. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6731. \Stmt &::=& \CPRINT{\Exp} \MID \Exp \\
  6732. &\MID& \CASSIGN{\Var}{\Exp}
  6733. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6734. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6735. \end{array}
  6736. }
  6737. \newcommand{\CifASTPython}{
  6738. \begin{array}{lcl}
  6739. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6740. \Exp &::= & \Atm \MID \READ{} \\
  6741. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6742. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6743. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6744. \Stmt &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  6745. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6746. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6747. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6748. \end{array}
  6749. }
  6750. \begin{figure}[tbp]
  6751. \fbox{
  6752. \begin{minipage}{0.96\textwidth}
  6753. \small
  6754. {\if\edition\racketEd
  6755. \[
  6756. \begin{array}{l}
  6757. \gray{\CvarGrammarRacket} \\ \hline
  6758. \CifGrammarRacket \\
  6759. \begin{array}{lcl}
  6760. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6761. \end{array}
  6762. \end{array}
  6763. \]
  6764. \fi}
  6765. {\if\edition\pythonEd
  6766. \[
  6767. \begin{array}{l}
  6768. \CifGrammarPython \\
  6769. \begin{array}{lcl}
  6770. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6771. \end{array}
  6772. \end{array}
  6773. \]
  6774. \fi}
  6775. \end{minipage}
  6776. }
  6777. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6778. \label{fig:c1-concrete-syntax}
  6779. \end{figure}
  6780. \begin{figure}[tp]
  6781. \fbox{
  6782. \begin{minipage}{0.96\textwidth}
  6783. \small
  6784. {\if\edition\racketEd
  6785. \[
  6786. \begin{array}{l}
  6787. \gray{\CvarASTRacket} \\ \hline
  6788. \CifASTRacket \\
  6789. \begin{array}{lcl}
  6790. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6791. \end{array}
  6792. \end{array}
  6793. \]
  6794. \fi}
  6795. {\if\edition\pythonEd
  6796. \[
  6797. \begin{array}{l}
  6798. \CifASTPython \\
  6799. \begin{array}{lcl}
  6800. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6801. \end{array}
  6802. \end{array}
  6803. \]
  6804. \fi}
  6805. \end{minipage}
  6806. }
  6807. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6808. (Figure~\ref{fig:c0-syntax})}.}
  6809. \label{fig:c1-syntax}
  6810. \end{figure}
  6811. \section{The \LangXIf{} Language}
  6812. \label{sec:x86-if}
  6813. \index{subject}{x86} To implement the new logical operations, the comparison
  6814. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6815. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6816. define the concrete and abstract syntax for the \LangXIf{} subset
  6817. of x86, which includes instructions for logical operations,
  6818. comparisons, and \racket{conditional} jumps.
  6819. One challenge is that x86 does not provide an instruction that
  6820. directly implements logical negation (\code{not} in \LangIf{} and
  6821. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6822. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6823. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6824. bit of its arguments, and writes the results into its second argument.
  6825. Recall the truth table for exclusive-or:
  6826. \begin{center}
  6827. \begin{tabular}{l|cc}
  6828. & 0 & 1 \\ \hline
  6829. 0 & 0 & 1 \\
  6830. 1 & 1 & 0
  6831. \end{tabular}
  6832. \end{center}
  6833. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6834. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6835. for the bit $1$, the result is the opposite of the second bit. Thus,
  6836. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6837. the first argument as follows, where $\Arg$ is the translation of
  6838. $\Atm$.
  6839. \[
  6840. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6841. \qquad\Rightarrow\qquad
  6842. \begin{array}{l}
  6843. \key{movq}~ \Arg\key{,} \Var\\
  6844. \key{xorq}~ \key{\$1,} \Var
  6845. \end{array}
  6846. \]
  6847. \begin{figure}[tp]
  6848. \fbox{
  6849. \begin{minipage}{0.96\textwidth}
  6850. \[
  6851. \begin{array}{lcl}
  6852. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6853. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6854. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6855. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6856. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6857. \key{subq} \; \Arg\key{,} \Arg \MID
  6858. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6859. && \gray{ \key{callq} \; \itm{label} \MID
  6860. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6861. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6862. \MID \key{xorq}~\Arg\key{,}~\Arg
  6863. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6864. && \key{set}cc~\Arg
  6865. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6866. \MID \key{j}cc~\itm{label}
  6867. \\
  6868. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6869. & & \gray{ \key{main:} \; \Instr\ldots }
  6870. \end{array}
  6871. \]
  6872. \end{minipage}
  6873. }
  6874. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6875. \label{fig:x86-1-concrete}
  6876. \end{figure}
  6877. \begin{figure}[tp]
  6878. \fbox{
  6879. \begin{minipage}{0.98\textwidth}
  6880. \small
  6881. {\if\edition\racketEd
  6882. \[
  6883. \begin{array}{lcl}
  6884. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6885. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6886. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6887. \MID \BYTEREG{\itm{bytereg}} \\
  6888. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6889. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6890. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6891. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6892. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6893. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6894. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6895. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6896. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6897. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6898. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6899. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6900. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6901. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6902. \end{array}
  6903. \]
  6904. \fi}
  6905. %
  6906. {\if\edition\pythonEd
  6907. \[
  6908. \begin{array}{lcl}
  6909. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6910. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6911. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6912. \MID \BYTEREG{\itm{bytereg}} \\
  6913. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6914. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6915. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6916. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6917. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6918. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6919. \MID \PUSHQ{\Arg}} \\
  6920. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6921. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6922. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6923. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6924. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6925. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6926. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6927. \end{array}
  6928. \]
  6929. \fi}
  6930. \end{minipage}
  6931. }
  6932. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6933. \label{fig:x86-1}
  6934. \end{figure}
  6935. Next we consider the x86 instructions that are relevant for compiling
  6936. the comparison operations. The \key{cmpq} instruction compares its two
  6937. arguments to determine whether one argument is less than, equal, or
  6938. greater than the other argument. The \key{cmpq} instruction is unusual
  6939. regarding the order of its arguments and where the result is
  6940. placed. The argument order is backwards: if you want to test whether
  6941. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6942. \key{cmpq} is placed in the special EFLAGS register. This register
  6943. cannot be accessed directly but it can be queried by a number of
  6944. instructions, including the \key{set} instruction. The instruction
  6945. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  6946. depending on whether the comparison comes out according to the
  6947. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  6948. for less-or-equal, \key{g} for greater, \key{ge} for
  6949. greater-or-equal). The \key{set} instruction has a quirk in
  6950. that its destination argument must be single byte register, such as
  6951. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  6952. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  6953. instruction can be used to move from a single byte register to a
  6954. normal 64-bit register. The abstract syntax for the \code{set}
  6955. instruction differs from the concrete syntax in that it separates the
  6956. instruction name from the condition code.
  6957. \python{The x86 instructions for jumping are relevant to the
  6958. compilation of \key{if} expressions.}
  6959. %
  6960. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  6961. counter to the address of the instruction after the specified
  6962. label.}
  6963. %
  6964. \racket{The x86 instruction for conditional jump is relevant to the
  6965. compilation of \key{if} expressions.}
  6966. %
  6967. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  6968. counter to point to the instruction after \itm{label} depending on
  6969. whether the result in the EFLAGS register matches the condition code
  6970. \itm{cc}, otherwise the jump instruction falls through to the next
  6971. instruction. Like the abstract syntax for \code{set}, the abstract
  6972. syntax for conditional jump separates the instruction name from the
  6973. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  6974. to \code{jle foo}. Because the conditional jump instruction relies on
  6975. the EFLAGS register, it is common for it to be immediately preceded by
  6976. a \key{cmpq} instruction to set the EFLAGS register.
  6977. \section{Shrink the \LangIf{} Language}
  6978. \label{sec:shrink-Lif}
  6979. The \LangIf{} language includes several features that are easily
  6980. expressible with other features. For example, \code{and} and \code{or}
  6981. are expressible using \code{if} as follows.
  6982. \begin{align*}
  6983. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  6984. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  6985. \end{align*}
  6986. By performing these translations in the front-end of the compiler,
  6987. subsequent passes of the compiler do not need to deal with these features,
  6988. making the passes shorter.
  6989. %% For example, subtraction is
  6990. %% expressible using addition and negation.
  6991. %% \[
  6992. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  6993. %% \]
  6994. %% Several of the comparison operations are expressible using less-than
  6995. %% and logical negation.
  6996. %% \[
  6997. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  6998. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  6999. %% \]
  7000. %% The \key{let} is needed in the above translation to ensure that
  7001. %% expression $e_1$ is evaluated before $e_2$.
  7002. On the other hand, sometimes translations reduce the efficiency of the
  7003. generated code by increasing the number of instructions. For example,
  7004. expressing subtraction in terms of negation
  7005. \[
  7006. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7007. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7008. \]
  7009. produces code with two x86 instructions (\code{negq} and \code{addq})
  7010. instead of just one (\code{subq}).
  7011. %% However,
  7012. %% these differences typically do not affect the number of accesses to
  7013. %% memory, which is the primary factor that determines execution time on
  7014. %% modern computer architectures.
  7015. \begin{exercise}\normalfont
  7016. %
  7017. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7018. the language by translating them to \code{if} expressions in \LangIf{}.
  7019. %
  7020. Create four test programs that involve these operators.
  7021. %
  7022. {\if\edition\racketEd
  7023. In the \code{run-tests.rkt} script, add the following entry for
  7024. \code{shrink} to the list of passes (it should be the only pass at
  7025. this point).
  7026. \begin{lstlisting}
  7027. (list "shrink" shrink interp_Lif type-check-Lif)
  7028. \end{lstlisting}
  7029. This instructs \code{interp-tests} to run the intepreter
  7030. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7031. output of \code{shrink}.
  7032. \fi}
  7033. %
  7034. Run the script to test your compiler on all the test programs.
  7035. \end{exercise}
  7036. {\if\edition\racketEd
  7037. \section{Uniquify Variables}
  7038. \label{sec:uniquify-Lif}
  7039. Add cases to \code{uniquify-exp} to handle Boolean constants and
  7040. \code{if} expressions.
  7041. \begin{exercise}\normalfont
  7042. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7043. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7044. \begin{lstlisting}
  7045. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7046. \end{lstlisting}
  7047. Run the script to test your compiler.
  7048. \end{exercise}
  7049. \fi}
  7050. \section{Remove Complex Operands}
  7051. \label{sec:remove-complex-opera-Lif}
  7052. The output language of \code{remove\_complex\_operands} is
  7053. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7054. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7055. but the \code{if} expression is not. All three sub-expressions of an
  7056. \code{if} are allowed to be complex expressions but the operands of
  7057. \code{not} and the comparisons must be atomic.
  7058. %
  7059. \python{We add a new language form, the \code{Begin} expression, to aid
  7060. in the translation of \code{if} expressions. When we recursively
  7061. process the two branches of the \code{if}, we generate temporary
  7062. variables and their initializing expressions. However, these
  7063. expressions may contain side effects and should only be executed
  7064. when the condition of the \code{if} is true (for the ``then''
  7065. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7066. a way to initialize the temporary variables within the two branches
  7067. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7068. form execute the statements $ss$ and then returns the result of
  7069. expression $e$.}
  7070. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7071. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7072. according to whether the output needs to be \Exp{} or \Atm{} as
  7073. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7074. particularly important to \textbf{not} replace its condition with a
  7075. temporary variable because that would interfere with the generation of
  7076. high-quality output in the \code{explicate\_control} pass.
  7077. \newcommand{\LifMonadASTPython}{
  7078. \begin{array}{rcl}
  7079. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7080. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7081. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7082. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7083. \Atm &::=& \BOOL{\itm{bool}}\\
  7084. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7085. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7086. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7087. \end{array}
  7088. }
  7089. \begin{figure}[tp]
  7090. \centering
  7091. \fbox{
  7092. \begin{minipage}{0.96\textwidth}
  7093. {\if\edition\racketEd
  7094. \[
  7095. \begin{array}{rcl}
  7096. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7097. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7098. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7099. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7100. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7101. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7102. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7103. \end{array}
  7104. \]
  7105. \fi}
  7106. {\if\edition\pythonEd
  7107. \[
  7108. \begin{array}{l}
  7109. \gray{\LvarMonadASTPython} \\ \hline
  7110. \LifMonadASTPython \\
  7111. \begin{array}{rcl}
  7112. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7113. \end{array}
  7114. \end{array}
  7115. \]
  7116. \fi}
  7117. \end{minipage}
  7118. }
  7119. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7120. \label{fig:Lif-anf-syntax}
  7121. \end{figure}
  7122. \begin{exercise}\normalfont
  7123. %
  7124. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7125. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7126. %
  7127. Create three new \LangIf{} programs that exercise the interesting
  7128. code in this pass.
  7129. %
  7130. {\if\edition\racketEd
  7131. In the \code{run-tests.rkt} script, add the following entry to the
  7132. list of \code{passes} and then run the script to test your compiler.
  7133. \begin{lstlisting}
  7134. (list "remove-complex" remove-complex-opera* interp-Lif type-check-Lif)
  7135. \end{lstlisting}
  7136. \fi}
  7137. \end{exercise}
  7138. \section{Explicate Control}
  7139. \label{sec:explicate-control-Lif}
  7140. \racket{Recall that the purpose of \code{explicate\_control} is to
  7141. make the order of evaluation explicit in the syntax of the program.
  7142. With the addition of \key{if} this get more interesting.}
  7143. %
  7144. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7145. %
  7146. The main challenge to overcome is that the condition of an \key{if}
  7147. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7148. condition must be a comparison.
  7149. As a motivating example, consider the following program that has an
  7150. \key{if} expression nested in the condition of another \key{if}.%
  7151. \python{\footnote{Programmers rarely write nested \code{if}
  7152. expressions, but it is not uncommon for the condition of an
  7153. \code{if} statement to be a call of a function that also contains an
  7154. \code{if} statement. When such a function is inlined, the result is
  7155. a nested \code{if} that requires the techniques discussed in this
  7156. section.}}
  7157. % cond_test_41.rkt, if_lt_eq.py
  7158. \begin{center}
  7159. \begin{minipage}{0.96\textwidth}
  7160. {\if\edition\racketEd
  7161. \begin{lstlisting}
  7162. (let ([x (read)])
  7163. (let ([y (read)])
  7164. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7165. (+ y 2)
  7166. (+ y 10))))
  7167. \end{lstlisting}
  7168. \fi}
  7169. {\if\edition\pythonEd
  7170. \begin{lstlisting}
  7171. x = input_int()
  7172. y = input_int()
  7173. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7174. \end{lstlisting}
  7175. \fi}
  7176. \end{minipage}
  7177. \end{center}
  7178. %
  7179. The naive way to compile \key{if} and the comparison operations would
  7180. be to handle each of them in isolation, regardless of their context.
  7181. Each comparison would be translated into a \key{cmpq} instruction
  7182. followed by several instructions to move the result from the EFLAGS
  7183. register into a general purpose register or stack location. Each
  7184. \key{if} would be translated into a \key{cmpq} instruction followed by
  7185. a conditional jump. The generated code for the inner \key{if} in the
  7186. above example would be as follows.
  7187. \begin{center}
  7188. \begin{minipage}{0.96\textwidth}
  7189. \begin{lstlisting}
  7190. cmpq $1, x
  7191. setl %al
  7192. movzbq %al, tmp
  7193. cmpq $1, tmp
  7194. je then_branch_1
  7195. jmp else_branch_1
  7196. \end{lstlisting}
  7197. \end{minipage}
  7198. \end{center}
  7199. However, if we take context into account we can do better and reduce
  7200. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7201. Our goal will be to compile \key{if} expressions so that the relevant
  7202. comparison instruction appears directly before the conditional jump.
  7203. For example, we want to generate the following code for the inner
  7204. \code{if}.
  7205. \begin{center}
  7206. \begin{minipage}{0.96\textwidth}
  7207. \begin{lstlisting}
  7208. cmpq $1, x
  7209. jl then_branch_1
  7210. jmp else_branch_1
  7211. \end{lstlisting}
  7212. \end{minipage}
  7213. \end{center}
  7214. One way to achieve this goal is to reorganize the code at the level of
  7215. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7216. the following code.
  7217. \begin{center}
  7218. \begin{minipage}{0.96\textwidth}
  7219. {\if\edition\racketEd
  7220. \begin{lstlisting}
  7221. (let ([x (read)])
  7222. (let ([y (read)])
  7223. (if (< x 1)
  7224. (if (eq? x 0)
  7225. (+ y 2)
  7226. (+ y 10))
  7227. (if (eq? x 2)
  7228. (+ y 2)
  7229. (+ y 10)))))
  7230. \end{lstlisting}
  7231. \fi}
  7232. {\if\edition\pythonEd
  7233. \begin{lstlisting}
  7234. x = input_int()
  7235. y = intput_int()
  7236. print(((y + 2) if x == 0 else (y + 10)) \
  7237. if (x < 1) \
  7238. else ((y + 2) if (x == 2) else (y + 10)))
  7239. \end{lstlisting}
  7240. \fi}
  7241. \end{minipage}
  7242. \end{center}
  7243. Unfortunately, this approach duplicates the two branches from the
  7244. outer \code{if} and a compiler must never duplicate code! After all,
  7245. the two branches could have been very large expressions.
  7246. We need a way to perform the above transformation but without
  7247. duplicating code. That is, we need a way for different parts of a
  7248. program to refer to the same piece of code.
  7249. %
  7250. Put another way, we need to move away from abstract syntax
  7251. \emph{trees} and instead use \emph{graphs}.
  7252. %
  7253. At the level of x86 assembly this is straightforward because we can
  7254. label the code for each branch and insert jumps in all the places that
  7255. need to execute the branch.
  7256. %
  7257. Likewise, our language \LangCIf{} provides the ability to label a
  7258. sequence of code and to jump to a label via \code{goto}.
  7259. %
  7260. %% In particular, we use a standard program representation called a
  7261. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7262. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7263. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7264. %% edge represents a jump to another block.
  7265. %
  7266. %% The nice thing about the output of \code{explicate\_control} is that
  7267. %% there are no unnecessary comparisons and every comparison is part of a
  7268. %% conditional jump.
  7269. %% The down-side of this output is that it includes
  7270. %% trivial blocks, such as the blocks labeled \code{block92} through
  7271. %% \code{block95}, that only jump to another block. We discuss a solution
  7272. %% to this problem in Section~\ref{sec:opt-jumps}.
  7273. {\if\edition\racketEd
  7274. %
  7275. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7276. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7277. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7278. former function translates expressions in tail position whereas the
  7279. later function translates expressions on the right-hand-side of a
  7280. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7281. have a new kind of position to deal with: the predicate position of
  7282. the \key{if}. We need another function, \code{explicate\_pred}, that
  7283. decides how to compile an \key{if} by analyzing its predicate. So
  7284. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7285. tails for the then-branch and else-branch and outputs a tail. In the
  7286. following paragraphs we discuss specific cases in the
  7287. \code{explicate\_tail}, \code{explicate\_assign}, and
  7288. \code{explicate\_pred} functions.
  7289. %
  7290. \fi}
  7291. %
  7292. {\if\edition\pythonEd
  7293. %
  7294. We recommend implementing \code{explicate\_control} using the
  7295. following four auxiliary functions.
  7296. \begin{description}
  7297. \item[\code{explicate\_effect}] generates code for expressions as
  7298. statements, so their result is ignored and only their side effects
  7299. matter.
  7300. \item[\code{explicate\_assign}] generates code for expressions
  7301. on the right-hand side of an assignment.
  7302. \item[\code{explicate\_pred}] generates code for an \code{if}
  7303. expression or statement by analyzing the condition expression.
  7304. \item[\code{explicate\_stmt}] generates code for statements.
  7305. \end{description}
  7306. These four functions should build the dictionary of basic blocks. The
  7307. following auxiliary function can be used to create a new basic block
  7308. from a list of statements. It returns a \code{goto} statement that
  7309. jumps to the new basic block.
  7310. \begin{center}
  7311. \begin{minipage}{\textwidth}
  7312. \begin{lstlisting}
  7313. def create_block(stmts, basic_blocks):
  7314. label = label_name(generate_name('block'))
  7315. basic_blocks[label] = stmts
  7316. return Goto(label)
  7317. \end{lstlisting}
  7318. \end{minipage}
  7319. \end{center}
  7320. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7321. \code{explicate\_control} pass.
  7322. The \code{explicate\_effect} function has three parameters: 1) the
  7323. expression to be compiled, 2) the already-compiled code for this
  7324. expression's \emph{continuation}, that is, the list of statements that
  7325. should execute after this expression, and 3) the dictionary of
  7326. generated basic blocks. The \code{explicate\_effect} function returns
  7327. a list of \LangCIf{} statements and it may add to the dictionary of
  7328. basic blocks.
  7329. %
  7330. Let's consider a few of the cases for the expression to be compiled.
  7331. If the expression to be compiled is a constant, then it can be
  7332. discarded because it has no side effects. If it's a \CREAD{}, then it
  7333. has a side-effect and should be preserved. So the expression should be
  7334. translated into a statement using the \code{Expr} AST class. If the
  7335. expression to be compiled is an \code{if} expression, we translate the
  7336. two branches using \code{explicate\_effect} and then translate the
  7337. condition expression using \code{explicate\_pred}, which generates
  7338. code for the entire \code{if}.
  7339. The \code{explicate\_assign} function has four parameters: 1) the
  7340. right-hand-side of the assignment, 2) the left-hand-side of the
  7341. assignment (the variable), 3) the continuation, and 4) the dictionary
  7342. of basic blocks. The \code{explicate\_assign} function returns a list
  7343. of \LangCIf{} statements and it may add to the dictionary of basic
  7344. blocks.
  7345. When the right-hand-side is an \code{if} expression, there is some
  7346. work to do. In particular, the two branches should be translated using
  7347. \code{explicate\_assign} and the condition expression should be
  7348. translated using \code{explicate\_pred}. Otherwise we can simply
  7349. generate an assignment statement, with the given left and right-hand
  7350. sides, concatenated with its continuation.
  7351. \begin{figure}[tbp]
  7352. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7353. def explicate_effect(e, cont, basic_blocks):
  7354. match e:
  7355. case IfExp(test, body, orelse):
  7356. ...
  7357. case Call(func, args):
  7358. ...
  7359. case Begin(body, result):
  7360. ...
  7361. case _:
  7362. ...
  7363. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7364. match rhs:
  7365. case IfExp(test, body, orelse):
  7366. ...
  7367. case Begin(body, result):
  7368. ...
  7369. case _:
  7370. return [Assign([lhs], rhs)] + cont
  7371. def explicate_pred(cnd, thn, els, basic_blocks):
  7372. match cnd:
  7373. case Compare(left, [op], [right]):
  7374. goto_thn = create_block(thn, basic_blocks)
  7375. goto_els = create_block(els, basic_blocks)
  7376. return [If(cnd, [goto_thn], [goto_els])]
  7377. case Constant(True):
  7378. return thn;
  7379. case Constant(False):
  7380. return els;
  7381. case UnaryOp(Not(), operand):
  7382. ...
  7383. case IfExp(test, body, orelse):
  7384. ...
  7385. case Begin(body, result):
  7386. ...
  7387. case _:
  7388. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7389. [create_block(els, basic_blocks)],
  7390. [create_block(thn, basic_blocks)])]
  7391. def explicate_stmt(s, cont, basic_blocks):
  7392. match s:
  7393. case Assign([lhs], rhs):
  7394. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7395. case Expr(value):
  7396. return explicate_effect(value, cont, basic_blocks)
  7397. case If(test, body, orelse):
  7398. ...
  7399. def explicate_control(p):
  7400. match p:
  7401. case Module(body):
  7402. new_body = [Return(Constant(0))]
  7403. basic_blocks = {}
  7404. for s in reversed(body):
  7405. new_body = explicate_stmt(s, new_body, basic_blocks)
  7406. basic_blocks[label_name('start')] = new_body
  7407. return CProgram(basic_blocks)
  7408. \end{lstlisting}
  7409. \caption{Skeleton for the \code{explicate\_control} pass.}
  7410. \label{fig:explicate-control-Lif}
  7411. \end{figure}
  7412. \fi}
  7413. {\if\edition\racketEd
  7414. %
  7415. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7416. additional cases for Boolean constants and \key{if}. The cases for
  7417. \code{if} should recursively compile the two branches using either
  7418. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7419. cases should then invoke \code{explicate\_pred} on the condition
  7420. expression, passing in the generated code for the two branches. For
  7421. example, consider the following program with an \code{if} in tail
  7422. position.
  7423. \begin{lstlisting}
  7424. (let ([x (read)])
  7425. (if (eq? x 0) 42 777))
  7426. \end{lstlisting}
  7427. The two branches are recursively compiled to \code{return 42;} and
  7428. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7429. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7430. used as the result for \code{explicate\_tail}.
  7431. Next let us consider a program with an \code{if} on the right-hand
  7432. side of a \code{let}.
  7433. \begin{lstlisting}
  7434. (let ([y (read)])
  7435. (let ([x (if (eq? y 0) 40 777)])
  7436. (+ x 2)))
  7437. \end{lstlisting}
  7438. Note that the body of the inner \code{let} will have already been
  7439. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7440. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7441. to recursively process both branches of the \code{if}, so we generate
  7442. the following block using an auxiliary function named \code{create\_block}.
  7443. \begin{lstlisting}
  7444. block_6:
  7445. return (+ x 2)
  7446. \end{lstlisting}
  7447. and use \code{goto block\_6;} as the \code{cont} argument for
  7448. compiling the branches. So the two branches compile to
  7449. \begin{lstlisting}
  7450. x = 40;
  7451. goto block_6;
  7452. \end{lstlisting}
  7453. and
  7454. \begin{lstlisting}
  7455. x = 777;
  7456. goto block_6;
  7457. \end{lstlisting}
  7458. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7459. 0)} and the above code for the branches.
  7460. \fi}
  7461. {\if\edition\racketEd
  7462. \begin{figure}[tbp]
  7463. \begin{lstlisting}
  7464. (define (explicate_pred cnd thn els)
  7465. (match cnd
  7466. [(Var x) ___]
  7467. [(Let x rhs body) ___]
  7468. [(Prim 'not (list e)) ___]
  7469. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7470. (IfStmt (Prim op es) (create_block thn)
  7471. (create_block els))]
  7472. [(Bool b) (if b thn els)]
  7473. [(If cnd^ thn^ els^) ___]
  7474. [else (error "explicate_pred unhandled case" cnd)]))
  7475. \end{lstlisting}
  7476. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7477. \label{fig:explicate-pred}
  7478. \end{figure}
  7479. \fi}
  7480. \racket{The skeleton for the \code{explicate\_pred} function is given
  7481. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7482. 1) \code{cnd}, the condition expression of the \code{if},
  7483. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7484. and 3) \code{els}, the code generated by
  7485. explicate for the ``else'' branch. The \code{explicate\_pred}
  7486. function should match on \code{cnd} with a case for
  7487. every kind of expression that can have type \code{Boolean}.}
  7488. %
  7489. \python{The \code{explicate\_pred} function has four parameters: 1)
  7490. the condition expression, 2) the generated statements for the
  7491. ``then'' branch, 3) the generated statements for the ``else''
  7492. branch, and 4) the dictionary of basic blocks. The
  7493. \code{explicate\_pred} function returns a list of \LangCIf{}
  7494. statements and it may add to the dictionary of basic blocks.}
  7495. Consider the case for comparison operators. We translate the
  7496. comparison to an \code{if} statement whose branches are \code{goto}
  7497. statements created by applying \code{create\_block} to the code
  7498. generated for the \code{thn} and \code{els} branches. Let us
  7499. illustrate this translation with an example. Returning
  7500. to the program with an \code{if} expression in tail position,
  7501. we invoke \code{explicate\_pred} on its condition
  7502. \racket{\code{(eq? x 0)}}
  7503. \python{\code{x == 0}}
  7504. which happens to be a comparison operator.
  7505. {\if\edition\racketEd
  7506. \begin{lstlisting}
  7507. (let ([x (read)])
  7508. (if (eq? x 0) 42 777))
  7509. \end{lstlisting}
  7510. \fi}
  7511. {\if\edition\pythonEd
  7512. \begin{lstlisting}
  7513. x = input_int()
  7514. 42 if x == 0 else 777
  7515. \end{lstlisting}
  7516. \fi}
  7517. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7518. statements, from which we now create the following blocks.
  7519. \begin{center}
  7520. \begin{minipage}{\textwidth}
  7521. \begin{lstlisting}
  7522. block_1:
  7523. return 42;
  7524. block_2:
  7525. return 777;
  7526. \end{lstlisting}
  7527. \end{minipage}
  7528. \end{center}
  7529. %
  7530. So \code{explicate\_pred} compiles the comparison
  7531. \racket{\code{(eq? x 0)}}
  7532. \python{\code{x == 0}}
  7533. to the following \code{if} statement.
  7534. %
  7535. {\if\edition\racketEd
  7536. \begin{center}
  7537. \begin{minipage}{\textwidth}
  7538. \begin{lstlisting}
  7539. if (eq? x 0)
  7540. goto block_1;
  7541. else
  7542. goto block_2;
  7543. \end{lstlisting}
  7544. \end{minipage}
  7545. \end{center}
  7546. \fi}
  7547. {\if\edition\pythonEd
  7548. \begin{center}
  7549. \begin{minipage}{\textwidth}
  7550. \begin{lstlisting}
  7551. if x == 0:
  7552. goto block_1;
  7553. else
  7554. goto block_2;
  7555. \end{lstlisting}
  7556. \end{minipage}
  7557. \end{center}
  7558. \fi}
  7559. Next consider the case for Boolean constants. We perform a kind of
  7560. partial evaluation\index{subject}{partial evaluation} and output
  7561. either the \code{thn} or \code{els} branch depending on whether the
  7562. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7563. following program.
  7564. {\if\edition\racketEd
  7565. \begin{center}
  7566. \begin{minipage}{\textwidth}
  7567. \begin{lstlisting}
  7568. (if #t 42 777)
  7569. \end{lstlisting}
  7570. \end{minipage}
  7571. \end{center}
  7572. \fi}
  7573. {\if\edition\pythonEd
  7574. \begin{center}
  7575. \begin{minipage}{\textwidth}
  7576. \begin{lstlisting}
  7577. 42 if True else 777
  7578. \end{lstlisting}
  7579. \end{minipage}
  7580. \end{center}
  7581. \fi}
  7582. %
  7583. Again, the two branches \code{42} and \code{777} were compiled to
  7584. \code{return} statements, so \code{explicate\_pred} compiles the
  7585. constant
  7586. \racket{\code{\#t}}
  7587. \python{\code{True}}
  7588. to the code for the ``then'' branch.
  7589. \begin{center}
  7590. \begin{minipage}{\textwidth}
  7591. \begin{lstlisting}
  7592. return 42;
  7593. \end{lstlisting}
  7594. \end{minipage}
  7595. \end{center}
  7596. %
  7597. This case demonstrates that we sometimes discard the \code{thn} or
  7598. \code{els} blocks that are input to \code{explicate\_pred}.
  7599. The case for \key{if} expressions in \code{explicate\_pred} is
  7600. particularly illuminating because it deals with the challenges we
  7601. discussed above regarding nested \key{if} expressions
  7602. (Figure~\ref{fig:explicate-control-s1-38}). The
  7603. \racket{\lstinline{thn^}}\python{\code{body}} and
  7604. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7605. \key{if} inherit their context from the current one, that is,
  7606. predicate context. So you should recursively apply
  7607. \code{explicate\_pred} to the
  7608. \racket{\lstinline{thn^}}\python{\code{body}} and
  7609. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7610. those recursive calls, pass \code{thn} and \code{els} as the extra
  7611. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7612. inside each recursive call. As discussed above, to avoid duplicating
  7613. code, we need to add them to the dictionary of basic blocks so that we
  7614. can instead refer to them by name and execute them with a \key{goto}.
  7615. {\if\edition\pythonEd
  7616. %
  7617. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7618. three parameters: 1) the statement to be compiled, 2) the code for its
  7619. continuation, and 3) the dictionary of basic blocks. The
  7620. \code{explicate\_stmt} returns a list of statements and it may add to
  7621. the dictionary of basic blocks. The cases for assignment and an
  7622. expression-statement are given in full in the skeleton code: they
  7623. simply dispatch to \code{explicate\_assign} and
  7624. \code{explicate\_effect}, respectively. The case for \code{if}
  7625. statements is not given, and is similar to the case for \code{if}
  7626. expressions.
  7627. The \code{explicate\_control} function itself is given in
  7628. Figure~\ref{fig:explicate-control-Lif}. It applies
  7629. \code{explicate\_stmt} to each statement in the program, from back to
  7630. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7631. used as the continuation parameter in the next call to
  7632. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7633. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7634. the dictionary of basic blocks, labeling it as the ``start'' block.
  7635. %
  7636. \fi}
  7637. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7638. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7639. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7640. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7641. %% results from the two recursive calls. We complete the case for
  7642. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7643. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7644. %% the result $B_5$.
  7645. %% \[
  7646. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7647. %% \quad\Rightarrow\quad
  7648. %% B_5
  7649. %% \]
  7650. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7651. %% inherit the current context, so they are in tail position. Thus, the
  7652. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7653. %% \code{explicate\_tail}.
  7654. %% %
  7655. %% We need to pass $B_0$ as the accumulator argument for both of these
  7656. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7657. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7658. %% to the control-flow graph and obtain a promised goto $G_0$.
  7659. %% %
  7660. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7661. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7662. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7663. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7664. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7665. %% \[
  7666. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7667. %% \]
  7668. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7669. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7670. %% should not be confused with the labels for the blocks that appear in
  7671. %% the generated code. We initially construct unlabeled blocks; we only
  7672. %% attach labels to blocks when we add them to the control-flow graph, as
  7673. %% we see in the next case.
  7674. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7675. %% function. The context of the \key{if} is an assignment to some
  7676. %% variable $x$ and then the control continues to some promised block
  7677. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7678. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7679. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7680. %% branches of the \key{if} inherit the current context, so they are in
  7681. %% assignment positions. Let $B_2$ be the result of applying
  7682. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7683. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7684. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7685. %% the result of applying \code{explicate\_pred} to the predicate
  7686. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7687. %% translates to the promise $B_4$.
  7688. %% \[
  7689. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7690. %% \]
  7691. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7692. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7693. \code{remove\_complex\_operands} pass and then the
  7694. \code{explicate\_control} pass on the example program. We walk through
  7695. the output program.
  7696. %
  7697. Following the order of evaluation in the output of
  7698. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7699. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7700. in the predicate of the inner \key{if}. In the output of
  7701. \code{explicate\_control}, in the
  7702. block labeled \code{start}, are two assignment statements followed by a
  7703. \code{if} statement that branches to \code{block\_8} or
  7704. \code{block\_9}. The blocks associated with those labels contain the
  7705. translations of the code
  7706. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7707. and
  7708. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7709. respectively. In particular, we start \code{block\_8} with the
  7710. comparison
  7711. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7712. and then branch to \code{block\_4} or \code{block\_5}.
  7713. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7714. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7715. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7716. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7717. and go directly to \code{block\_2} and \code{block\_3},
  7718. which we investigate in Section~\ref{sec:opt-jumps}.
  7719. Getting back to the example, \code{block\_2} and \code{block\_3},
  7720. corresponds to the two branches of the outer \key{if}, i.e.,
  7721. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7722. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7723. %
  7724. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7725. %
  7726. \python{The \code{block\_1} corresponds to the \code{print} statment
  7727. at the end of the program.}
  7728. \begin{figure}[tbp]
  7729. {\if\edition\racketEd
  7730. \begin{tabular}{lll}
  7731. \begin{minipage}{0.4\textwidth}
  7732. % cond_test_41.rkt
  7733. \begin{lstlisting}
  7734. (let ([x (read)])
  7735. (let ([y (read)])
  7736. (if (if (< x 1)
  7737. (eq? x 0)
  7738. (eq? x 2))
  7739. (+ y 2)
  7740. (+ y 10))))
  7741. \end{lstlisting}
  7742. \end{minipage}
  7743. &
  7744. $\Rightarrow$
  7745. &
  7746. \begin{minipage}{0.55\textwidth}
  7747. \begin{lstlisting}
  7748. start:
  7749. x = (read);
  7750. y = (read);
  7751. if (< x 1)
  7752. goto block_8;
  7753. else
  7754. goto block_9;
  7755. block_8:
  7756. if (eq? x 0)
  7757. goto block_4;
  7758. else
  7759. goto block_5;
  7760. block_9:
  7761. if (eq? x 2)
  7762. goto block_6;
  7763. else
  7764. goto block_7;
  7765. block_4:
  7766. goto block_2;
  7767. block_5:
  7768. goto block_3;
  7769. block_6:
  7770. goto block_2;
  7771. block_7:
  7772. goto block_3;
  7773. block_2:
  7774. return (+ y 2);
  7775. block_3:
  7776. return (+ y 10);
  7777. \end{lstlisting}
  7778. \end{minipage}
  7779. \end{tabular}
  7780. \fi}
  7781. {\if\edition\pythonEd
  7782. \begin{tabular}{lll}
  7783. \begin{minipage}{0.4\textwidth}
  7784. % cond_test_41.rkt
  7785. \begin{lstlisting}
  7786. x = input_int()
  7787. y = input_int()
  7788. print(y + 2 \
  7789. if (x == 0 \
  7790. if x < 1 \
  7791. else x == 2) \
  7792. else y + 10)
  7793. \end{lstlisting}
  7794. \end{minipage}
  7795. &
  7796. $\Rightarrow$
  7797. &
  7798. \begin{minipage}{0.55\textwidth}
  7799. \begin{lstlisting}
  7800. start:
  7801. x = input_int()
  7802. y = input_int()
  7803. if x < 1:
  7804. goto block_8
  7805. else:
  7806. goto block_9
  7807. block_8:
  7808. if x == 0:
  7809. goto block_4
  7810. else:
  7811. goto block_5
  7812. block_9:
  7813. if x == 2:
  7814. goto block_6
  7815. else:
  7816. goto block_7
  7817. block_4:
  7818. goto block_2
  7819. block_5:
  7820. goto block_3
  7821. block_6:
  7822. goto block_2
  7823. block_7:
  7824. goto block_3
  7825. block_2:
  7826. tmp_0 = y + 2
  7827. goto block_1
  7828. block_3:
  7829. tmp_0 = y + 10
  7830. goto block_1
  7831. block_1:
  7832. print(tmp_0)
  7833. return 0
  7834. \end{lstlisting}
  7835. \end{minipage}
  7836. \end{tabular}
  7837. \fi}
  7838. \caption{Translation from \LangIf{} to \LangCIf{}
  7839. via the \code{explicate\_control}.}
  7840. \label{fig:explicate-control-s1-38}
  7841. \end{figure}
  7842. {\if\edition\racketEd
  7843. The way in which the \code{shrink} pass transforms logical operations
  7844. such as \code{and} and \code{or} can impact the quality of code
  7845. generated by \code{explicate\_control}. For example, consider the
  7846. following program.
  7847. % cond_test_21.rkt, and_eq_input.py
  7848. \begin{lstlisting}
  7849. (if (and (eq? (read) 0) (eq? (read) 1))
  7850. 0
  7851. 42)
  7852. \end{lstlisting}
  7853. The \code{and} operation should transform into something that the
  7854. \code{explicate\_pred} function can still analyze and descend through to
  7855. reach the underlying \code{eq?} conditions. Ideally, your
  7856. \code{explicate\_control} pass should generate code similar to the
  7857. following for the above program.
  7858. \begin{center}
  7859. \begin{lstlisting}
  7860. start:
  7861. tmp1 = (read);
  7862. if (eq? tmp1 0) goto block40;
  7863. else goto block39;
  7864. block40:
  7865. tmp2 = (read);
  7866. if (eq? tmp2 1) goto block38;
  7867. else goto block39;
  7868. block38:
  7869. return 0;
  7870. block39:
  7871. return 42;
  7872. \end{lstlisting}
  7873. \end{center}
  7874. \fi}
  7875. \begin{exercise}\normalfont
  7876. \racket{
  7877. Implement the pass \code{explicate\_control} by adding the cases for
  7878. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7879. \code{explicate\_assign} functions. Implement the auxiliary function
  7880. \code{explicate\_pred} for predicate contexts.}
  7881. \python{Implement \code{explicate\_control} pass with its
  7882. four auxiliary functions.}
  7883. %
  7884. Create test cases that exercise all of the new cases in the code for
  7885. this pass.
  7886. %
  7887. {\if\edition\racketEd
  7888. Add the following entry to the list of \code{passes} in
  7889. \code{run-tests.rkt} and then run this script to test your compiler.
  7890. \begin{lstlisting}
  7891. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7892. \end{lstlisting}
  7893. \fi}
  7894. \end{exercise}
  7895. \clearpage
  7896. \section{Select Instructions}
  7897. \label{sec:select-Lif}
  7898. \index{subject}{instruction selection}
  7899. The \code{select\_instructions} pass translates \LangCIf{} to
  7900. \LangXIfVar{}.
  7901. %
  7902. \racket{Recall that we implement this pass using three auxiliary
  7903. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7904. $\Tail$.}
  7905. %
  7906. \racket{For $\Atm$, we have new cases for the Booleans.}
  7907. %
  7908. \python{We begin with the Boolean constants.}
  7909. We take the usual approach of encoding them as integers.
  7910. \[
  7911. \TRUE{} \quad\Rightarrow\quad \key{1}
  7912. \qquad\qquad
  7913. \FALSE{} \quad\Rightarrow\quad \key{0}
  7914. \]
  7915. For translating statements, we discuss a selection of cases. The \code{not}
  7916. operation can be implemented in terms of \code{xorq} as we discussed
  7917. at the beginning of this section. Given an assignment, if the
  7918. left-hand side variable is the same as the argument of \code{not},
  7919. then just the \code{xorq} instruction suffices.
  7920. \[
  7921. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7922. \quad\Rightarrow\quad
  7923. \key{xorq}~\key{\$}1\key{,}~\Var
  7924. \]
  7925. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7926. semantics of x86. In the following translation, let $\Arg$ be the
  7927. result of translating $\Atm$ to x86.
  7928. \[
  7929. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7930. \quad\Rightarrow\quad
  7931. \begin{array}{l}
  7932. \key{movq}~\Arg\key{,}~\Var\\
  7933. \key{xorq}~\key{\$}1\key{,}~\Var
  7934. \end{array}
  7935. \]
  7936. Next consider the cases for equality. Translating this operation to
  7937. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7938. instruction discussed above. We recommend translating an assignment
  7939. with an equality on the right-hand side into a sequence of three
  7940. instructions. \\
  7941. \begin{tabular}{lll}
  7942. \begin{minipage}{0.4\textwidth}
  7943. \begin{lstlisting}
  7944. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  7945. \end{lstlisting}
  7946. \end{minipage}
  7947. &
  7948. $\Rightarrow$
  7949. &
  7950. \begin{minipage}{0.4\textwidth}
  7951. \begin{lstlisting}
  7952. cmpq |$\Arg_2$|, |$\Arg_1$|
  7953. sete %al
  7954. movzbq %al, |$\Var$|
  7955. \end{lstlisting}
  7956. \end{minipage}
  7957. \end{tabular} \\
  7958. The translations for the other comparison operators are similar to the
  7959. above but use different suffixes for the \code{set} instruction.
  7960. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  7961. \key{goto} and \key{if} statements. Both are straightforward to
  7962. translate to x86.}
  7963. %
  7964. A \key{goto} statement becomes a jump instruction.
  7965. \[
  7966. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  7967. \]
  7968. %
  7969. An \key{if} statement becomes a compare instruction followed by a
  7970. conditional jump (for the ``then'' branch) and the fall-through is to
  7971. a regular jump (for the ``else'' branch).\\
  7972. \begin{tabular}{lll}
  7973. \begin{minipage}{0.4\textwidth}
  7974. \begin{lstlisting}
  7975. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  7976. goto |$\ell_1$||$\racket{\key{;}}$|
  7977. else|$\python{\key{:}}$|
  7978. goto |$\ell_2$||$\racket{\key{;}}$|
  7979. \end{lstlisting}
  7980. \end{minipage}
  7981. &
  7982. $\Rightarrow$
  7983. &
  7984. \begin{minipage}{0.4\textwidth}
  7985. \begin{lstlisting}
  7986. cmpq |$\Arg_2$|, |$\Arg_1$|
  7987. je |$\ell_1$|
  7988. jmp |$\ell_2$|
  7989. \end{lstlisting}
  7990. \end{minipage}
  7991. \end{tabular} \\
  7992. Again, the translations for the other comparison operators are similar to the
  7993. above but use different suffixes for the conditional jump instruction.
  7994. \python{Regarding the \key{return} statement, we recommend treating it
  7995. as an assignment to the \key{rax} register followed by a jump to the
  7996. conclusion of the \code{main} function.}
  7997. \begin{exercise}\normalfont
  7998. Expand your \code{select\_instructions} pass to handle the new
  7999. features of the \LangIf{} language.
  8000. %
  8001. {\if\edition\racketEd
  8002. Add the following entry to the list of \code{passes} in
  8003. \code{run-tests.rkt}
  8004. \begin{lstlisting}
  8005. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8006. \end{lstlisting}
  8007. \fi}
  8008. %
  8009. Run the script to test your compiler on all the test programs.
  8010. \end{exercise}
  8011. \section{Register Allocation}
  8012. \label{sec:register-allocation-Lif}
  8013. \index{subject}{register allocation}
  8014. The changes required for \LangIf{} affect liveness analysis, building the
  8015. interference graph, and assigning homes, but the graph coloring
  8016. algorithm itself does not change.
  8017. \subsection{Liveness Analysis}
  8018. \label{sec:liveness-analysis-Lif}
  8019. \index{subject}{liveness analysis}
  8020. Recall that for \LangVar{} we implemented liveness analysis for a
  8021. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8022. the addition of \key{if} expressions to \LangIf{},
  8023. \code{explicate\_control} produces many basic blocks.
  8024. %% We recommend that you create a new auxiliary function named
  8025. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8026. %% control-flow graph.
  8027. The first question is: in what order should we process the basic blocks?
  8028. Recall that to perform liveness analysis on a basic block we need to
  8029. know the live-after set for the last instruction in the block. If a
  8030. basic block has no successors (i.e. contains no jumps to other
  8031. blocks), then it has an empty live-after set and we can immediately
  8032. apply liveness analysis to it. If a basic block has some successors,
  8033. then we need to complete liveness analysis on those blocks
  8034. first. These ordering contraints are the reverse of a
  8035. \emph{topological order}\index{subject}{topological order} on a graph
  8036. representation of the program. In particular, the \emph{control flow
  8037. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8038. of a program has a node for each basic block and an edge for each jump
  8039. from one block to another. It is straightforward to generate a CFG
  8040. from the dictionary of basic blocks. One then transposes the CFG and
  8041. applies the topological sort algorithm.
  8042. %
  8043. %
  8044. \racket{We recommend using the \code{tsort} and \code{transpose}
  8045. functions of the Racket \code{graph} package to accomplish this.}
  8046. %
  8047. \python{We provide implementations of \code{topological\_sort} and
  8048. \code{transpose} in the file \code{graph.py} of the support code.}
  8049. %
  8050. As an aside, a topological ordering is only guaranteed to exist if the
  8051. graph does not contain any cycles. This is the case for the
  8052. control-flow graphs that we generate from \LangIf{} programs.
  8053. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8054. and learn how to handle cycles in the control-flow graph.
  8055. \racket{You'll need to construct a directed graph to represent the
  8056. control-flow graph. Do not use the \code{directed-graph} of the
  8057. \code{graph} package because that only allows at most one edge
  8058. between each pair of vertices, but a control-flow graph may have
  8059. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8060. file in the support code implements a graph representation that
  8061. allows multiple edges between a pair of vertices.}
  8062. {\if\edition\racketEd
  8063. The next question is how to analyze jump instructions. Recall that in
  8064. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8065. \code{label->live} that maps each label to the set of live locations
  8066. at the beginning of its block. We use \code{label->live} to determine
  8067. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8068. that we have many basic blocks, \code{label->live} needs to be updated
  8069. as we process the blocks. In particular, after performing liveness
  8070. analysis on a block, we take the live-before set of its first
  8071. instruction and associate that with the block's label in the
  8072. \code{label->live}.
  8073. \fi}
  8074. %
  8075. {\if\edition\pythonEd
  8076. %
  8077. The next question is how to analyze jump instructions. The locations
  8078. that are live before a \code{jmp} should be the locations in
  8079. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8080. maintaining a dictionary named \code{live\_before\_block} that maps each
  8081. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8082. block. After performing liveness analysis on each block, we take the
  8083. live-before set of its first instruction and associate that with the
  8084. block's label in the \code{live\_before\_block} dictionary.
  8085. %
  8086. \fi}
  8087. In \LangXIfVar{} we also have the conditional jump
  8088. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8089. this instruction is particularly interesting because, during
  8090. compilation, we do not know which way a conditional jump will go. So
  8091. we do not know whether to use the live-before set for the following
  8092. instruction or the live-before set for the block associated with the
  8093. $\itm{label}$. However, there is no harm to the correctness of the
  8094. generated code if we classify more locations as live than the ones
  8095. that are truly live during one particular execution of the
  8096. instruction. Thus, we can take the union of the live-before sets from
  8097. the following instruction and from the mapping for $\itm{label}$ in
  8098. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8099. The auxiliary functions for computing the variables in an
  8100. instruction's argument and for computing the variables read-from ($R$)
  8101. or written-to ($W$) by an instruction need to be updated to handle the
  8102. new kinds of arguments and instructions in \LangXIfVar{}.
  8103. \begin{exercise}\normalfont
  8104. {\if\edition\racketEd
  8105. %
  8106. Update the \code{uncover\_live} pass to apply liveness analysis to
  8107. every basic block in the program.
  8108. %
  8109. Add the following entry to the list of \code{passes} in the
  8110. \code{run-tests.rkt} script.
  8111. \begin{lstlisting}
  8112. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8113. \end{lstlisting}
  8114. \fi}
  8115. {\if\edition\pythonEd
  8116. %
  8117. Update the \code{uncover\_live} function to perform liveness analysis,
  8118. in reverse topological order, on all of the basic blocks in the
  8119. program.
  8120. %
  8121. \fi}
  8122. % Check that the live-after sets that you generate for
  8123. % example X matches the following... -Jeremy
  8124. \end{exercise}
  8125. \subsection{Build the Interference Graph}
  8126. \label{sec:build-interference-Lif}
  8127. Many of the new instructions in \LangXIfVar{} can be handled in the
  8128. same way as the instructions in \LangXVar{}.
  8129. % Thus, if your code was
  8130. % already quite general, it will not need to be changed to handle the
  8131. % new instructions. If your code is not general enough, we recommend that
  8132. % you change your code to be more general. For example, you can factor
  8133. % out the computing of the the read and write sets for each kind of
  8134. % instruction into auxiliary functions.
  8135. %
  8136. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8137. similar to the \key{movq} instruction. See rule number 1 in
  8138. Section~\ref{sec:build-interference}.
  8139. \begin{exercise}\normalfont
  8140. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8141. {\if\edition\racketEd
  8142. Add the following entries to the list of \code{passes} in the
  8143. \code{run-tests.rkt} script.
  8144. \begin{lstlisting}
  8145. (list "build_interference" build_interference interp-pseudo-x86-1)
  8146. (list "allocate_registers" allocate_registers interp-x86-1)
  8147. \end{lstlisting}
  8148. \fi}
  8149. % Check that the interference graph that you generate for
  8150. % example X matches the following graph G... -Jeremy
  8151. \end{exercise}
  8152. \section{Patch Instructions}
  8153. The new instructions \key{cmpq} and \key{movzbq} have some special
  8154. restrictions that need to be handled in the \code{patch\_instructions}
  8155. pass.
  8156. %
  8157. The second argument of the \key{cmpq} instruction must not be an
  8158. immediate value (such as an integer). So if you are comparing two
  8159. immediates, we recommend inserting a \key{movq} instruction to put the
  8160. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8161. one memory reference.
  8162. %
  8163. The second argument of the \key{movzbq} must be a register.
  8164. \begin{exercise}\normalfont
  8165. %
  8166. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8167. %
  8168. {\if\edition\racketEd
  8169. Add the following entry to the list of \code{passes} in
  8170. \code{run-tests.rkt} and then run this script to test your compiler.
  8171. \begin{lstlisting}
  8172. (list "patch_instructions" patch_instructions interp-x86-1)
  8173. \end{lstlisting}
  8174. \fi}
  8175. \end{exercise}
  8176. {\if\edition\pythonEd
  8177. \section{Prelude and Conclusion}
  8178. \label{sec:prelude-conclusion-cond}
  8179. The generation of the \code{main} function with its prelude and
  8180. conclusion must change to accomodate how the program now consists of
  8181. one or more basic blocks. After the prelude in \code{main}, jump to
  8182. the \code{start} block. Place the conclusion in a basic block labelled
  8183. with \code{conclusion}.
  8184. \fi}
  8185. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8186. \LangIf{} translated to x86, showing the results of
  8187. \code{explicate\_control}, \code{select\_instructions}, and the final
  8188. x86 assembly.
  8189. \begin{figure}[tbp]
  8190. {\if\edition\racketEd
  8191. \begin{tabular}{lll}
  8192. \begin{minipage}{0.4\textwidth}
  8193. % cond_test_20.rkt, eq_input.py
  8194. \begin{lstlisting}
  8195. (if (eq? (read) 1) 42 0)
  8196. \end{lstlisting}
  8197. $\Downarrow$
  8198. \begin{lstlisting}
  8199. start:
  8200. tmp7951 = (read);
  8201. if (eq? tmp7951 1)
  8202. goto block7952;
  8203. else
  8204. goto block7953;
  8205. block7952:
  8206. return 42;
  8207. block7953:
  8208. return 0;
  8209. \end{lstlisting}
  8210. $\Downarrow$
  8211. \begin{lstlisting}
  8212. start:
  8213. callq read_int
  8214. movq %rax, tmp7951
  8215. cmpq $1, tmp7951
  8216. je block7952
  8217. jmp block7953
  8218. block7953:
  8219. movq $0, %rax
  8220. jmp conclusion
  8221. block7952:
  8222. movq $42, %rax
  8223. jmp conclusion
  8224. \end{lstlisting}
  8225. \end{minipage}
  8226. &
  8227. $\Rightarrow\qquad$
  8228. \begin{minipage}{0.4\textwidth}
  8229. \begin{lstlisting}
  8230. start:
  8231. callq read_int
  8232. movq %rax, %rcx
  8233. cmpq $1, %rcx
  8234. je block7952
  8235. jmp block7953
  8236. block7953:
  8237. movq $0, %rax
  8238. jmp conclusion
  8239. block7952:
  8240. movq $42, %rax
  8241. jmp conclusion
  8242. .globl main
  8243. main:
  8244. pushq %rbp
  8245. movq %rsp, %rbp
  8246. pushq %r13
  8247. pushq %r12
  8248. pushq %rbx
  8249. pushq %r14
  8250. subq $0, %rsp
  8251. jmp start
  8252. conclusion:
  8253. addq $0, %rsp
  8254. popq %r14
  8255. popq %rbx
  8256. popq %r12
  8257. popq %r13
  8258. popq %rbp
  8259. retq
  8260. \end{lstlisting}
  8261. \end{minipage}
  8262. \end{tabular}
  8263. \fi}
  8264. {\if\edition\pythonEd
  8265. \begin{tabular}{lll}
  8266. \begin{minipage}{0.4\textwidth}
  8267. % cond_test_20.rkt, eq_input.py
  8268. \begin{lstlisting}
  8269. print(42 if input_int() == 1 else 0)
  8270. \end{lstlisting}
  8271. $\Downarrow$
  8272. \begin{lstlisting}
  8273. start:
  8274. tmp_0 = input_int()
  8275. if tmp_0 == 1:
  8276. goto block_3
  8277. else:
  8278. goto block_4
  8279. block_3:
  8280. tmp_1 = 42
  8281. goto block_2
  8282. block_4:
  8283. tmp_1 = 0
  8284. goto block_2
  8285. block_2:
  8286. print(tmp_1)
  8287. return 0
  8288. \end{lstlisting}
  8289. $\Downarrow$
  8290. \begin{lstlisting}
  8291. start:
  8292. callq read_int
  8293. movq %rax, tmp_0
  8294. cmpq 1, tmp_0
  8295. je block_3
  8296. jmp block_4
  8297. block_3:
  8298. movq 42, tmp_1
  8299. jmp block_2
  8300. block_4:
  8301. movq 0, tmp_1
  8302. jmp block_2
  8303. block_2:
  8304. movq tmp_1, %rdi
  8305. callq print_int
  8306. movq 0, %rax
  8307. jmp conclusion
  8308. \end{lstlisting}
  8309. \end{minipage}
  8310. &
  8311. $\Rightarrow\qquad$
  8312. \begin{minipage}{0.4\textwidth}
  8313. \begin{lstlisting}
  8314. .globl main
  8315. main:
  8316. pushq %rbp
  8317. movq %rsp, %rbp
  8318. subq $0, %rsp
  8319. jmp start
  8320. start:
  8321. callq read_int
  8322. movq %rax, %rcx
  8323. cmpq $1, %rcx
  8324. je block_3
  8325. jmp block_4
  8326. block_3:
  8327. movq $42, %rcx
  8328. jmp block_2
  8329. block_4:
  8330. movq $0, %rcx
  8331. jmp block_2
  8332. block_2:
  8333. movq %rcx, %rdi
  8334. callq print_int
  8335. movq $0, %rax
  8336. jmp conclusion
  8337. conclusion:
  8338. addq $0, %rsp
  8339. popq %rbp
  8340. retq
  8341. \end{lstlisting}
  8342. \end{minipage}
  8343. \end{tabular}
  8344. \fi}
  8345. \caption{Example compilation of an \key{if} expression to x86, showing
  8346. the results of \code{explicate\_control},
  8347. \code{select\_instructions}, and the final x86 assembly code. }
  8348. \label{fig:if-example-x86}
  8349. \end{figure}
  8350. \begin{figure}[tbp]
  8351. {\if\edition\racketEd
  8352. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8353. \node (Lif) at (0,2) {\large \LangIf{}};
  8354. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8355. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8356. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8357. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8358. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8359. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8360. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8361. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8362. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8363. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8364. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8365. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8366. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8367. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8368. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8369. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8370. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8371. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8372. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8373. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8374. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8375. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8376. \end{tikzpicture}
  8377. \fi}
  8378. {\if\edition\pythonEd
  8379. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8380. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8381. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8382. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8383. \node (C-1) at (3,0) {\large \LangCIf{}};
  8384. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8385. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8386. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8387. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8388. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8389. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8390. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8391. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8392. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8393. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8394. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8395. \end{tikzpicture}
  8396. \fi}
  8397. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8398. \label{fig:Lif-passes}
  8399. \end{figure}
  8400. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8401. compilation of \LangIf{}.
  8402. \section{Challenge: Optimize Blocks and Remove Jumps}
  8403. \label{sec:opt-jumps}
  8404. We discuss two optional challenges that involve optimizing the
  8405. control-flow of the program.
  8406. \subsection{Optimize Blocks}
  8407. The algorithm for \code{explicate\_control} that we discussed in
  8408. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8409. blocks. It does so in two different ways.
  8410. %
  8411. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8412. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8413. a new basic block from a single \code{goto} statement, whereas we
  8414. could have simply returned the \code{goto} statement. We can solve
  8415. this problem by modifying the \code{create\_block} function to
  8416. recognize this situation.
  8417. Second, \code{explicate\_control} creates a basic block whenever a
  8418. continuation \emph{might} get used more than once (whenever a
  8419. continuation is passed into two or more recursive calls). However,
  8420. some continuation parameters may not be used at all. For example, consider the
  8421. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8422. discard the \code{els} branch. So the question is how can we decide
  8423. whether to create a basic block?
  8424. The solution to this conundrum is to use \emph{lazy
  8425. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8426. to delay creating a basic block until the point in time where we know
  8427. it will be used.
  8428. %
  8429. {\if\edition\racketEd
  8430. %
  8431. Racket provides support for
  8432. lazy evaluation with the
  8433. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8434. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8435. \index{subject}{delay} creates a
  8436. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8437. expressions is postponed. When \key{(force}
  8438. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8439. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8440. result of $e_n$ is cached in the promise and returned. If \code{force}
  8441. is applied again to the same promise, then the cached result is
  8442. returned. If \code{force} is applied to an argument that is not a
  8443. promise, \code{force} simply returns the argument.
  8444. %
  8445. \fi}
  8446. %
  8447. {\if\edition\pythonEd
  8448. %
  8449. While Python does not provide direct support for lazy evaluation, it
  8450. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8451. by wrapping it inside a function with no parameters. We can
  8452. \emph{force} its evaluation by calling the function. However, in some
  8453. cases of \code{explicate\_pred}, etc., we will return a list of
  8454. statements and in other cases we will return a function that computes
  8455. a list of statements. We use the term \emph{promise} to refer to a
  8456. value that may be delayed. To uniformly deal with
  8457. promises, we define the following \code{force} function that checks
  8458. whether its input is delayed (i.e., whether it is a function) and then
  8459. either 1) calls the function, or 2) returns the input.
  8460. \begin{lstlisting}
  8461. def force(promise):
  8462. if isinstance(promise, types.FunctionType):
  8463. return promise()
  8464. else:
  8465. return promise
  8466. \end{lstlisting}
  8467. %
  8468. \fi}
  8469. We use promises for the input and output of the functions
  8470. \code{explicate\_pred}, \code{explicate\_assign},
  8471. %
  8472. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8473. %
  8474. So instead of taking and returning lists of statments, they take and
  8475. return promises. Furthermore, when we come to a situation in which a
  8476. continuation might be used more than once, as in the case for
  8477. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8478. that creates a basic block for each continuation (if there is not
  8479. already one) and then returns a \code{goto} statement to that basic
  8480. block.
  8481. %
  8482. {\if\edition\racketEd
  8483. %
  8484. The following auxiliary function named \code{create\_block} accomplishes
  8485. this task. It begins with \code{delay} to create a promise. When
  8486. forced, this promise will force the original promise. If that returns
  8487. a \code{goto} (because the block was already added to the control-flow
  8488. graph), then we return the \code{goto}. Otherwise we add the block to
  8489. the control-flow graph with another auxiliary function named
  8490. \code{add-node}. That function returns the label for the new block,
  8491. which we use to create a \code{goto}.
  8492. \begin{lstlisting}
  8493. (define (create_block tail)
  8494. (delay
  8495. (define t (force tail))
  8496. (match t
  8497. [(Goto label) (Goto label)]
  8498. [else (Goto (add-node t))])))
  8499. \end{lstlisting}
  8500. \fi}
  8501. {\if\edition\pythonEd
  8502. %
  8503. Here is the new version of the \code{create\_block} auxiliary function
  8504. that works on promises and that checks whether the block consists of a
  8505. solitary \code{goto} statement.\\
  8506. \begin{minipage}{\textwidth}
  8507. \begin{lstlisting}
  8508. def create_block(promise, basic_blocks):
  8509. stmts = force(promise)
  8510. match stmts:
  8511. case [Goto(l)]:
  8512. return Goto(l)
  8513. case _:
  8514. label = label_name(generate_name('block'))
  8515. basic_blocks[label] = stmts
  8516. return Goto(label)
  8517. \end{lstlisting}
  8518. \end{minipage}
  8519. \fi}
  8520. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8521. \code{explicate\_control} on the example of the nested \code{if}
  8522. expressions with the two improvements discussed above. As you can
  8523. see, the number of basic blocks has been reduced from 10 blocks (see
  8524. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8525. \begin{figure}[tbp]
  8526. {\if\edition\racketEd
  8527. \begin{tabular}{lll}
  8528. \begin{minipage}{0.4\textwidth}
  8529. % cond_test_41.rkt
  8530. \begin{lstlisting}
  8531. (let ([x (read)])
  8532. (let ([y (read)])
  8533. (if (if (< x 1)
  8534. (eq? x 0)
  8535. (eq? x 2))
  8536. (+ y 2)
  8537. (+ y 10))))
  8538. \end{lstlisting}
  8539. \end{minipage}
  8540. &
  8541. $\Rightarrow$
  8542. &
  8543. \begin{minipage}{0.55\textwidth}
  8544. \begin{lstlisting}
  8545. start:
  8546. x = (read);
  8547. y = (read);
  8548. if (< x 1) goto block40;
  8549. else goto block41;
  8550. block40:
  8551. if (eq? x 0) goto block38;
  8552. else goto block39;
  8553. block41:
  8554. if (eq? x 2) goto block38;
  8555. else goto block39;
  8556. block38:
  8557. return (+ y 2);
  8558. block39:
  8559. return (+ y 10);
  8560. \end{lstlisting}
  8561. \end{minipage}
  8562. \end{tabular}
  8563. \fi}
  8564. {\if\edition\pythonEd
  8565. \begin{tabular}{lll}
  8566. \begin{minipage}{0.4\textwidth}
  8567. % cond_test_41.rkt
  8568. \begin{lstlisting}
  8569. x = input_int()
  8570. y = input_int()
  8571. print(y + 2 \
  8572. if (x == 0 \
  8573. if x < 1 \
  8574. else x == 2) \
  8575. else y + 10)
  8576. \end{lstlisting}
  8577. \end{minipage}
  8578. &
  8579. $\Rightarrow$
  8580. &
  8581. \begin{minipage}{0.55\textwidth}
  8582. \begin{lstlisting}
  8583. start:
  8584. x = input_int()
  8585. y = input_int()
  8586. if x < 1:
  8587. goto block_4
  8588. else:
  8589. goto block_5
  8590. block_4:
  8591. if x == 0:
  8592. goto block_2
  8593. else:
  8594. goto block_3
  8595. block_5:
  8596. if x == 2:
  8597. goto block_2
  8598. else:
  8599. goto block_3
  8600. block_2:
  8601. tmp_0 = y + 2
  8602. goto block_1
  8603. block_3:
  8604. tmp_0 = y + 10
  8605. goto block_1
  8606. block_1:
  8607. print(tmp_0)
  8608. return 0
  8609. \end{lstlisting}
  8610. \end{minipage}
  8611. \end{tabular}
  8612. \fi}
  8613. \caption{Translation from \LangIf{} to \LangCIf{}
  8614. via the improved \code{explicate\_control}.}
  8615. \label{fig:explicate-control-challenge}
  8616. \end{figure}
  8617. %% Recall that in the example output of \code{explicate\_control} in
  8618. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8619. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8620. %% block. The first goal of this challenge assignment is to remove those
  8621. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8622. %% \code{explicate\_control} on the left and shows the result of bypassing
  8623. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8624. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8625. %% \code{block55}. The optimized code on the right of
  8626. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8627. %% \code{then} branch jumping directly to \code{block55}. The story is
  8628. %% similar for the \code{else} branch, as well as for the two branches in
  8629. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8630. %% have been optimized in this way, there are no longer any jumps to
  8631. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8632. %% \begin{figure}[tbp]
  8633. %% \begin{tabular}{lll}
  8634. %% \begin{minipage}{0.4\textwidth}
  8635. %% \begin{lstlisting}
  8636. %% block62:
  8637. %% tmp54 = (read);
  8638. %% if (eq? tmp54 2) then
  8639. %% goto block59;
  8640. %% else
  8641. %% goto block60;
  8642. %% block61:
  8643. %% tmp53 = (read);
  8644. %% if (eq? tmp53 0) then
  8645. %% goto block57;
  8646. %% else
  8647. %% goto block58;
  8648. %% block60:
  8649. %% goto block56;
  8650. %% block59:
  8651. %% goto block55;
  8652. %% block58:
  8653. %% goto block56;
  8654. %% block57:
  8655. %% goto block55;
  8656. %% block56:
  8657. %% return (+ 700 77);
  8658. %% block55:
  8659. %% return (+ 10 32);
  8660. %% start:
  8661. %% tmp52 = (read);
  8662. %% if (eq? tmp52 1) then
  8663. %% goto block61;
  8664. %% else
  8665. %% goto block62;
  8666. %% \end{lstlisting}
  8667. %% \end{minipage}
  8668. %% &
  8669. %% $\Rightarrow$
  8670. %% &
  8671. %% \begin{minipage}{0.55\textwidth}
  8672. %% \begin{lstlisting}
  8673. %% block62:
  8674. %% tmp54 = (read);
  8675. %% if (eq? tmp54 2) then
  8676. %% goto block55;
  8677. %% else
  8678. %% goto block56;
  8679. %% block61:
  8680. %% tmp53 = (read);
  8681. %% if (eq? tmp53 0) then
  8682. %% goto block55;
  8683. %% else
  8684. %% goto block56;
  8685. %% block56:
  8686. %% return (+ 700 77);
  8687. %% block55:
  8688. %% return (+ 10 32);
  8689. %% start:
  8690. %% tmp52 = (read);
  8691. %% if (eq? tmp52 1) then
  8692. %% goto block61;
  8693. %% else
  8694. %% goto block62;
  8695. %% \end{lstlisting}
  8696. %% \end{minipage}
  8697. %% \end{tabular}
  8698. %% \caption{Optimize jumps by removing trivial blocks.}
  8699. %% \label{fig:optimize-jumps}
  8700. %% \end{figure}
  8701. %% The name of this pass is \code{optimize-jumps}. We recommend
  8702. %% implementing this pass in two phases. The first phrase builds a hash
  8703. %% table that maps labels to possibly improved labels. The second phase
  8704. %% changes the target of each \code{goto} to use the improved label. If
  8705. %% the label is for a trivial block, then the hash table should map the
  8706. %% label to the first non-trivial block that can be reached from this
  8707. %% label by jumping through trivial blocks. If the label is for a
  8708. %% non-trivial block, then the hash table should map the label to itself;
  8709. %% we do not want to change jumps to non-trivial blocks.
  8710. %% The first phase can be accomplished by constructing an empty hash
  8711. %% table, call it \code{short-cut}, and then iterating over the control
  8712. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8713. %% then update the hash table, mapping the block's source to the target
  8714. %% of the \code{goto}. Also, the hash table may already have mapped some
  8715. %% labels to the block's source, to you must iterate through the hash
  8716. %% table and update all of those so that they instead map to the target
  8717. %% of the \code{goto}.
  8718. %% For the second phase, we recommend iterating through the $\Tail$ of
  8719. %% each block in the program, updating the target of every \code{goto}
  8720. %% according to the mapping in \code{short-cut}.
  8721. \begin{exercise}\normalfont
  8722. Implement the improvements to the \code{explicate\_control} pass.
  8723. Check that it removes trivial blocks in a few example programs. Then
  8724. check that your compiler still passes all of your tests.
  8725. \end{exercise}
  8726. \subsection{Remove Jumps}
  8727. There is an opportunity for removing jumps that is apparent in the
  8728. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8729. ends with a jump to \code{block7953} and there are no other jumps to
  8730. \code{block7953} in the rest of the program. In this situation we can
  8731. avoid the runtime overhead of this jump by merging \code{block7953}
  8732. into the preceding block, in this case the \code{start} block.
  8733. Figure~\ref{fig:remove-jumps} shows the output of
  8734. \code{select\_instructions} on the left and the result of this
  8735. optimization on the right.
  8736. \begin{figure}[tbp]
  8737. {\if\edition\racketEd
  8738. \begin{tabular}{lll}
  8739. \begin{minipage}{0.5\textwidth}
  8740. % cond_test_20.rkt
  8741. \begin{lstlisting}
  8742. start:
  8743. callq read_int
  8744. movq %rax, tmp7951
  8745. cmpq $1, tmp7951
  8746. je block7952
  8747. jmp block7953
  8748. block7953:
  8749. movq $0, %rax
  8750. jmp conclusion
  8751. block7952:
  8752. movq $42, %rax
  8753. jmp conclusion
  8754. \end{lstlisting}
  8755. \end{minipage}
  8756. &
  8757. $\Rightarrow\qquad$
  8758. \begin{minipage}{0.4\textwidth}
  8759. \begin{lstlisting}
  8760. start:
  8761. callq read_int
  8762. movq %rax, tmp7951
  8763. cmpq $1, tmp7951
  8764. je block7952
  8765. movq $0, %rax
  8766. jmp conclusion
  8767. block7952:
  8768. movq $42, %rax
  8769. jmp conclusion
  8770. \end{lstlisting}
  8771. \end{minipage}
  8772. \end{tabular}
  8773. \fi}
  8774. {\if\edition\pythonEd
  8775. \begin{tabular}{lll}
  8776. \begin{minipage}{0.5\textwidth}
  8777. % cond_test_20.rkt
  8778. \begin{lstlisting}
  8779. start:
  8780. callq read_int
  8781. movq %rax, tmp_0
  8782. cmpq 1, tmp_0
  8783. je block_3
  8784. jmp block_4
  8785. block_3:
  8786. movq 42, tmp_1
  8787. jmp block_2
  8788. block_4:
  8789. movq 0, tmp_1
  8790. jmp block_2
  8791. block_2:
  8792. movq tmp_1, %rdi
  8793. callq print_int
  8794. movq 0, %rax
  8795. jmp conclusion
  8796. \end{lstlisting}
  8797. \end{minipage}
  8798. &
  8799. $\Rightarrow\qquad$
  8800. \begin{minipage}{0.4\textwidth}
  8801. \begin{lstlisting}
  8802. start:
  8803. callq read_int
  8804. movq %rax, tmp_0
  8805. cmpq 1, tmp_0
  8806. je block_3
  8807. movq 0, tmp_1
  8808. jmp block_2
  8809. block_3:
  8810. movq 42, tmp_1
  8811. jmp block_2
  8812. block_2:
  8813. movq tmp_1, %rdi
  8814. callq print_int
  8815. movq 0, %rax
  8816. jmp conclusion
  8817. \end{lstlisting}
  8818. \end{minipage}
  8819. \end{tabular}
  8820. \fi}
  8821. \caption{Merging basic blocks by removing unnecessary jumps.}
  8822. \label{fig:remove-jumps}
  8823. \end{figure}
  8824. \begin{exercise}\normalfont
  8825. %
  8826. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8827. into their preceding basic block, when there is only one preceding
  8828. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8829. %
  8830. {\if\edition\racketEd
  8831. In the \code{run-tests.rkt} script, add the following entry to the
  8832. list of \code{passes} between \code{allocate\_registers}
  8833. and \code{patch\_instructions}.
  8834. \begin{lstlisting}
  8835. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8836. \end{lstlisting}
  8837. \fi}
  8838. %
  8839. Run the script to test your compiler.
  8840. %
  8841. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8842. blocks on several test programs.
  8843. \end{exercise}
  8844. \section{Further Reading}
  8845. \label{sec:cond-further-reading}
  8846. The algorithm for the \code{explicate\_control} pass is based on the
  8847. \code{explose-basic-blocks} pass in the course notes of
  8848. \citet{Dybvig:2010aa}.
  8849. %
  8850. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8851. \citet{Appel:2003fk}, and is related to translations into continuation
  8852. passing
  8853. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8854. %
  8855. The treatment of conditionals in the \code{explicate\_control} pass is
  8856. similar to short-cut boolean
  8857. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8858. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8859. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8860. \chapter{Loops and Dataflow Analysis}
  8861. \label{ch:Lwhile}
  8862. % TODO: define R'_8
  8863. % TODO: multi-graph
  8864. {\if\edition\racketEd
  8865. %
  8866. In this chapter we study two features that are the hallmarks of
  8867. imperative programming languages: loops and assignments to local
  8868. variables. The following example demonstrates these new features by
  8869. computing the sum of the first five positive integers.
  8870. % similar to loop_test_1.rkt
  8871. \begin{lstlisting}
  8872. (let ([sum 0])
  8873. (let ([i 5])
  8874. (begin
  8875. (while (> i 0)
  8876. (begin
  8877. (set! sum (+ sum i))
  8878. (set! i (- i 1))))
  8879. sum)))
  8880. \end{lstlisting}
  8881. The \code{while} loop consists of a condition and a
  8882. body\footnote{The \code{while} loop in particular is not a built-in
  8883. feature of the Racket language, but Racket includes many looping
  8884. constructs and it is straightforward to define \code{while} as a
  8885. macro.}. The body is evaluated repeatedly so long as the condition
  8886. remains true.
  8887. %
  8888. The \code{set!} consists of a variable and a right-hand-side
  8889. expression. The \code{set!} updates value of the variable to the
  8890. value of the right-hand-side.
  8891. %
  8892. The primary purpose of both the \code{while} loop and \code{set!} is
  8893. to cause side effects, so they do not have a meaningful result
  8894. value. Instead their result is the \code{\#<void>} value. The
  8895. expression \code{(void)} is an explicit way to create the
  8896. \code{\#<void>} value and it has type \code{Void}. The
  8897. \code{\#<void>} value can be passed around just like other values
  8898. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8899. compared for equality with another \code{\#<void>} value. However,
  8900. there are no other operations specific to the the \code{\#<void>}
  8901. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8902. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8903. \code{\#f} otherwise.
  8904. %
  8905. \footnote{Racket's \code{Void} type corresponds to what is called the
  8906. \code{Unit} type in the programming languages literature. Racket's
  8907. \code{Void} type is inhabited by a single value \code{\#<void>}
  8908. which corresponds to \code{unit} or \code{()} in the
  8909. literature~\citep{Pierce:2002hj}.}.
  8910. %
  8911. With the addition of side-effecting features such as \code{while} loop
  8912. and \code{set!}, it is helpful to also include in a language feature
  8913. for sequencing side effects: the \code{begin} expression. It consists
  8914. of one or more subexpressions that are evaluated left-to-right.
  8915. %
  8916. \fi}
  8917. {\if\edition\pythonEd
  8918. %
  8919. In this chapter we study loops, one of the hallmarks of imperative
  8920. programming languages. The following example demonstrates the
  8921. \code{while} loop by computing the sum of the first five positive
  8922. integers.
  8923. \begin{lstlisting}
  8924. sum = 0
  8925. i = 5
  8926. while i > 0:
  8927. sum = sum + i
  8928. i = i - 1
  8929. print(sum)
  8930. \end{lstlisting}
  8931. The \code{while} loop consists of a condition expression and a body (a
  8932. sequence of statements). The body is evaluated repeatedly so long as
  8933. the condition remains true.
  8934. %
  8935. \fi}
  8936. \section{The \LangLoop{} Language}
  8937. \newcommand{\LwhileGrammarRacket}{
  8938. \begin{array}{lcl}
  8939. \Type &::=& \key{Void}\\
  8940. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8941. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8942. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8943. \end{array}
  8944. }
  8945. \newcommand{\LwhileASTRacket}{
  8946. \begin{array}{lcl}
  8947. \Type &::=& \key{Void}\\
  8948. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  8949. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  8950. \end{array}
  8951. }
  8952. \newcommand{\LwhileGrammarPython}{
  8953. \begin{array}{rcl}
  8954. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  8955. \end{array}
  8956. }
  8957. \newcommand{\LwhileASTPython}{
  8958. \begin{array}{lcl}
  8959. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  8960. \end{array}
  8961. }
  8962. \begin{figure}[tp]
  8963. \centering
  8964. \fbox{
  8965. \begin{minipage}{0.96\textwidth}
  8966. \small
  8967. {\if\edition\racketEd
  8968. \[
  8969. \begin{array}{l}
  8970. \gray{\LintGrammarRacket{}} \\ \hline
  8971. \gray{\LvarGrammarRacket{}} \\ \hline
  8972. \gray{\LifGrammarRacket{}} \\ \hline
  8973. \LwhileGrammarRacket \\
  8974. \begin{array}{lcl}
  8975. \LangLoopM{} &::=& \Exp
  8976. \end{array}
  8977. \end{array}
  8978. \]
  8979. \fi}
  8980. {\if\edition\pythonEd
  8981. \[
  8982. \begin{array}{l}
  8983. \gray{\LintGrammarPython} \\ \hline
  8984. \gray{\LvarGrammarPython} \\ \hline
  8985. \gray{\LifGrammarPython} \\ \hline
  8986. \LwhileGrammarPython \\
  8987. \begin{array}{rcl}
  8988. \LangLoopM{} &::=& \Stmt^{*}
  8989. \end{array}
  8990. \end{array}
  8991. \]
  8992. \fi}
  8993. \end{minipage}
  8994. }
  8995. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  8996. \label{fig:Lwhile-concrete-syntax}
  8997. \end{figure}
  8998. \begin{figure}[tp]
  8999. \centering
  9000. \fbox{
  9001. \begin{minipage}{0.96\textwidth}
  9002. \small
  9003. {\if\edition\racketEd
  9004. \[
  9005. \begin{array}{l}
  9006. \gray{\LintOpAST} \\ \hline
  9007. \gray{\LvarASTRacket{}} \\ \hline
  9008. \gray{\LifASTRacket{}} \\ \hline
  9009. \LwhileASTRacket{} \\
  9010. \begin{array}{lcl}
  9011. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9012. \end{array}
  9013. \end{array}
  9014. \]
  9015. \fi}
  9016. {\if\edition\pythonEd
  9017. \[
  9018. \begin{array}{l}
  9019. \gray{\LintASTPython} \\ \hline
  9020. \gray{\LvarASTPython} \\ \hline
  9021. \gray{\LifASTPython} \\ \hline
  9022. \LwhileASTPython \\
  9023. \begin{array}{lcl}
  9024. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9025. \end{array}
  9026. \end{array}
  9027. \]
  9028. \fi}
  9029. \end{minipage}
  9030. }
  9031. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9032. \label{fig:Lwhile-syntax}
  9033. \end{figure}
  9034. The concrete syntax of \LangLoop{} is defined in
  9035. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9036. in Figure~\ref{fig:Lwhile-syntax}.
  9037. %
  9038. The definitional interpreter for \LangLoop{} is shown in
  9039. Figure~\ref{fig:interp-Rwhile}.
  9040. %
  9041. {\if\edition\racketEd
  9042. %
  9043. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9044. and \code{Void} and we make changes to the cases for \code{Var} and
  9045. \code{Let} regarding variables. To support assignment to variables and
  9046. to make their lifetimes indefinite (see the second example in
  9047. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9048. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9049. value.
  9050. %
  9051. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9052. variable in the environment to obtain a boxed value and then we change
  9053. it using \code{set-box!} to the result of evaluating the right-hand
  9054. side. The result value of a \code{SetBang} is \code{void}.
  9055. %
  9056. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9057. if the result is true, 2) evaluate the body.
  9058. The result value of a \code{while} loop is also \code{void}.
  9059. %
  9060. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9061. subexpressions \itm{es} for their effects and then evaluates
  9062. and returns the result from \itm{body}.
  9063. %
  9064. The $\VOID{}$ expression produces the \code{void} value.
  9065. %
  9066. \fi}
  9067. {\if\edition\pythonEd
  9068. %
  9069. We add a new case for \code{While} in the \code{interp\_stmts}
  9070. function, where we repeatedly interpret the \code{body} so long as the
  9071. \code{test} expression remains true.
  9072. %
  9073. \fi}
  9074. \begin{figure}[tbp]
  9075. {\if\edition\racketEd
  9076. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9077. (define interp-Rwhile_class
  9078. (class interp-Rany_class
  9079. (super-new)
  9080. (define/override ((interp-exp env) e)
  9081. (define recur (interp-exp env))
  9082. (match e
  9083. [(SetBang x rhs)
  9084. (set-box! (lookup x env) (recur rhs))]
  9085. [(WhileLoop cnd body)
  9086. (define (loop)
  9087. (cond [(recur cnd) (recur body) (loop)]
  9088. [else (void)]))
  9089. (loop)]
  9090. [(Begin es body)
  9091. (for ([e es]) (recur e))
  9092. (recur body)]
  9093. [(Void) (void)]
  9094. [else ((super interp-exp env) e)]))
  9095. ))
  9096. (define (interp-Rwhile p)
  9097. (send (new interp-Rwhile_class) interp-program p))
  9098. \end{lstlisting}
  9099. \fi}
  9100. {\if\edition\pythonEd
  9101. \begin{lstlisting}
  9102. class InterpLwhile(InterpLif):
  9103. def interp_stmts(self, ss, env):
  9104. if len(ss) == 0:
  9105. return
  9106. match ss[0]:
  9107. case While(test, body, []):
  9108. while self.interp_exp(test, env):
  9109. self.interp_stmts(body, env)
  9110. return self.interp_stmts(ss[1:], env)
  9111. case _:
  9112. return super().interp_stmts(ss, env)
  9113. \end{lstlisting}
  9114. \fi}
  9115. \caption{Interpreter for \LangLoop{}.}
  9116. \label{fig:interp-Rwhile}
  9117. \end{figure}
  9118. The type checker for \LangLoop{} is defined in
  9119. Figure~\ref{fig:type-check-Rwhile}.
  9120. %
  9121. {\if\edition\racketEd
  9122. %
  9123. For \LangLoop{} we add a type named \code{Void} and the only value of
  9124. this type is the \code{void} value.
  9125. %
  9126. The type checking of the \code{SetBang} expression requires the type of
  9127. the variable and the right-hand-side to agree. The result type is
  9128. \code{Void}. For \code{while}, the condition must be a
  9129. \code{Boolean}. The result type is also \code{Void}. For
  9130. \code{Begin}, the result type is the type of its last subexpression.
  9131. %
  9132. \fi}
  9133. %
  9134. {\if\edition\pythonEd
  9135. %
  9136. A \code{while} loop is well typed if the type of the \code{test}
  9137. expression is \code{bool} and the statements in the \code{body} are
  9138. well typed.
  9139. %
  9140. \fi}
  9141. \begin{figure}[tbp]
  9142. {\if\edition\racketEd
  9143. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9144. (define type-check-Rwhile_class
  9145. (class type-check-Rany_class
  9146. (super-new)
  9147. (inherit check-type-equal?)
  9148. (define/override (type-check-exp env)
  9149. (lambda (e)
  9150. (define recur (type-check-exp env))
  9151. (match e
  9152. [(SetBang x rhs)
  9153. (define-values (rhs^ rhsT) (recur rhs))
  9154. (define varT (dict-ref env x))
  9155. (check-type-equal? rhsT varT e)
  9156. (values (SetBang x rhs^) 'Void)]
  9157. [(WhileLoop cnd body)
  9158. (define-values (cnd^ Tc) (recur cnd))
  9159. (check-type-equal? Tc 'Boolean e)
  9160. (define-values (body^ Tbody) ((type-check-exp env) body))
  9161. (values (WhileLoop cnd^ body^) 'Void)]
  9162. [(Begin es body)
  9163. (define-values (es^ ts)
  9164. (for/lists (l1 l2) ([e es]) (recur e)))
  9165. (define-values (body^ Tbody) (recur body))
  9166. (values (Begin es^ body^) Tbody)]
  9167. [else ((super type-check-exp env) e)])))
  9168. ))
  9169. (define (type-check-Rwhile p)
  9170. (send (new type-check-Rwhile_class) type-check-program p))
  9171. \end{lstlisting}
  9172. \fi}
  9173. {\if\edition\pythonEd
  9174. \begin{lstlisting}
  9175. class TypeCheckLwhile(TypeCheckLif):
  9176. def type_check_stmts(self, ss, env):
  9177. if len(ss) == 0:
  9178. return
  9179. match ss[0]:
  9180. case While(test, body, []):
  9181. test_t = self.type_check_exp(test, env)
  9182. check_type_equal(bool, test_t, test)
  9183. body_t = self.type_check_stmts(body, env)
  9184. return self.type_check_stmts(ss[1:], env)
  9185. case _:
  9186. return super().type_check_stmts(ss, env)
  9187. \end{lstlisting}
  9188. \fi}
  9189. \caption{Type checker for the \LangLoop{} language.}
  9190. \label{fig:type-check-Rwhile}
  9191. \end{figure}
  9192. {\if\edition\racketEd
  9193. %
  9194. At first glance, the translation of these language features to x86
  9195. seems straightforward because the \LangCIf{} intermediate language
  9196. already supports all of the ingredients that we need: assignment,
  9197. \code{goto}, conditional branching, and sequencing. However, there are
  9198. complications that arise which we discuss in the next section. After
  9199. that we introduce the changes necessary to the existing passes.
  9200. %
  9201. \fi}
  9202. {\if\edition\pythonEd
  9203. %
  9204. At first glance, the translation of \code{while} loops to x86 seems
  9205. straightforward because the \LangCIf{} intermediate language already
  9206. supports \code{goto} and conditional branching. However, there are
  9207. complications that arise which we discuss in the next section. After
  9208. that we introduce the changes necessary to the existing passes.
  9209. %
  9210. \fi}
  9211. \section{Cyclic Control Flow and Dataflow Analysis}
  9212. \label{sec:dataflow-analysis}
  9213. Up until this point the control-flow graphs of the programs generated
  9214. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9215. each \code{while} loop introduces a cycle in the control-flow graph.
  9216. But does that matter?
  9217. %
  9218. Indeed it does. Recall that for register allocation, the compiler
  9219. performs liveness analysis to determine which variables can share the
  9220. same register. To accomplish this we analyzed the control-flow graph
  9221. in reverse topological order
  9222. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9223. only well-defined for acyclic graphs.
  9224. Let us return to the example of computing the sum of the first five
  9225. positive integers. Here is the program after instruction selection but
  9226. before register allocation.
  9227. \begin{center}
  9228. {\if\edition\racketEd
  9229. \begin{minipage}{0.45\textwidth}
  9230. \begin{lstlisting}
  9231. (define (main) : Integer
  9232. mainstart:
  9233. movq $0, sum
  9234. movq $5, i
  9235. jmp block5
  9236. block5:
  9237. movq i, tmp3
  9238. cmpq tmp3, $0
  9239. jl block7
  9240. jmp block8
  9241. \end{lstlisting}
  9242. \end{minipage}
  9243. \begin{minipage}{0.45\textwidth}
  9244. \begin{lstlisting}
  9245. block7:
  9246. addq i, sum
  9247. movq $1, tmp4
  9248. negq tmp4
  9249. addq tmp4, i
  9250. jmp block5
  9251. block8:
  9252. movq $27, %rax
  9253. addq sum, %rax
  9254. jmp mainconclusion
  9255. )
  9256. \end{lstlisting}
  9257. \end{minipage}
  9258. \fi}
  9259. {\if\edition\pythonEd
  9260. \begin{minipage}{0.45\textwidth}
  9261. \begin{lstlisting}
  9262. mainstart:
  9263. movq $0, sum
  9264. movq $5, i
  9265. jmp block5
  9266. block5:
  9267. cmpq $0, i
  9268. jg block7
  9269. jmp block8
  9270. \end{lstlisting}
  9271. \end{minipage}
  9272. \begin{minipage}{0.45\textwidth}
  9273. \begin{lstlisting}
  9274. block7:
  9275. addq i, sum
  9276. subq $1, i
  9277. jmp block5
  9278. block8:
  9279. movq sum, %rdi
  9280. callq print_int
  9281. movq $0, %rax
  9282. jmp mainconclusion
  9283. \end{lstlisting}
  9284. \end{minipage}
  9285. \fi}
  9286. \end{center}
  9287. Recall that liveness analysis works backwards, starting at the end
  9288. of each function. For this example we could start with \code{block8}
  9289. because we know what is live at the beginning of the conclusion,
  9290. just \code{rax} and \code{rsp}. So the live-before set
  9291. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9292. %
  9293. Next we might try to analyze \code{block5} or \code{block7}, but
  9294. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9295. we are stuck.
  9296. The way out of this impasse is to realize that we can compute an
  9297. under-approximation of the live-before set by starting with empty
  9298. live-after sets. By \emph{under-approximation}, we mean that the set
  9299. only contains variables that are live for some execution of the
  9300. program, but the set may be missing some variables. Next, the
  9301. under-approximations for each block can be improved by 1) updating the
  9302. live-after set for each block using the approximate live-before sets
  9303. from the other blocks and 2) perform liveness analysis again on each
  9304. block. In fact, by iterating this process, the under-approximations
  9305. eventually become the correct solutions!
  9306. %
  9307. This approach of iteratively analyzing a control-flow graph is
  9308. applicable to many static analysis problems and goes by the name
  9309. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9310. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9311. Washington.
  9312. Let us apply this approach to the above example. We use the empty set
  9313. for the initial live-before set for each block. Let $m_0$ be the
  9314. following mapping from label names to sets of locations (variables and
  9315. registers).
  9316. \begin{center}
  9317. \begin{lstlisting}
  9318. mainstart: {}, block5: {}, block7: {}, block8: {}
  9319. \end{lstlisting}
  9320. \end{center}
  9321. Using the above live-before approximations, we determine the
  9322. live-after for each block and then apply liveness analysis to each
  9323. block. This produces our next approximation $m_1$ of the live-before
  9324. sets.
  9325. \begin{center}
  9326. \begin{lstlisting}
  9327. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9328. \end{lstlisting}
  9329. \end{center}
  9330. For the second round, the live-after for \code{mainstart} is the
  9331. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9332. liveness analysis for \code{mainstart} computes the empty set. The
  9333. live-after for \code{block5} is the union of the live-before sets for
  9334. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9335. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9336. sum\}}. The live-after for \code{block7} is the live-before for
  9337. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9338. So the liveness analysis for \code{block7} remains \code{\{i,
  9339. sum\}}. Together these yield the following approximation $m_2$ of
  9340. the live-before sets.
  9341. \begin{center}
  9342. \begin{lstlisting}
  9343. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9344. \end{lstlisting}
  9345. \end{center}
  9346. In the preceding iteration, only \code{block5} changed, so we can
  9347. limit our attention to \code{mainstart} and \code{block7}, the two
  9348. blocks that jump to \code{block5}. As a result, the live-before sets
  9349. for \code{mainstart} and \code{block7} are updated to include
  9350. \code{rsp}, yielding the following approximation $m_3$.
  9351. \begin{center}
  9352. \begin{lstlisting}
  9353. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9354. \end{lstlisting}
  9355. \end{center}
  9356. Because \code{block7} changed, we analyze \code{block5} once more, but
  9357. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9358. our approximations have converged, so $m_3$ is the solution.
  9359. This iteration process is guaranteed to converge to a solution by the
  9360. Kleene Fixed-Point Theorem, a general theorem about functions on
  9361. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9362. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9363. elements, a least element $\bot$ (pronounced bottom), and a join
  9364. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9365. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9366. working with join semi-lattices.} When two elements are ordered $m_i
  9367. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9368. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9369. approximation than $m_i$. The bottom element $\bot$ represents the
  9370. complete lack of information, i.e., the worst approximation. The join
  9371. operator takes two lattice elements and combines their information,
  9372. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9373. bound}
  9374. A dataflow analysis typically involves two lattices: one lattice to
  9375. represent abstract states and another lattice that aggregates the
  9376. abstract states of all the blocks in the control-flow graph. For
  9377. liveness analysis, an abstract state is a set of locations. We form
  9378. the lattice $L$ by taking its elements to be sets of locations, the
  9379. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9380. set, and the join operator to be set union.
  9381. %
  9382. We form a second lattice $M$ by taking its elements to be mappings
  9383. from the block labels to sets of locations (elements of $L$). We
  9384. order the mappings point-wise, using the ordering of $L$. So given any
  9385. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9386. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9387. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9388. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9389. We can think of one iteration of liveness analysis applied to the
  9390. whole program as being a function $f$ on the lattice $M$. It takes a
  9391. mapping as input and computes a new mapping.
  9392. \[
  9393. f(m_i) = m_{i+1}
  9394. \]
  9395. Next let us think for a moment about what a final solution $m_s$
  9396. should look like. If we perform liveness analysis using the solution
  9397. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9398. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9399. \[
  9400. f(m_s) = m_s
  9401. \]
  9402. Furthermore, the solution should only include locations that are
  9403. forced to be there by performing liveness analysis on the program, so
  9404. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9405. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9406. monotone (better inputs produce better outputs), then the least fixed
  9407. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9408. chain} obtained by starting at $\bot$ and iterating $f$ as
  9409. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9410. \[
  9411. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9412. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9413. \]
  9414. When a lattice contains only finitely-long ascending chains, then
  9415. every Kleene chain tops out at some fixed point after some number of
  9416. iterations of $f$.
  9417. \[
  9418. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9419. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9420. \]
  9421. The liveness analysis is indeed a monotone function and the lattice
  9422. $M$ only has finitely-long ascending chains because there are only a
  9423. finite number of variables and blocks in the program. Thus we are
  9424. guaranteed that iteratively applying liveness analysis to all blocks
  9425. in the program will eventually produce the least fixed point solution.
  9426. Next let us consider dataflow analysis in general and discuss the
  9427. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9428. %
  9429. The algorithm has four parameters: the control-flow graph \code{G}, a
  9430. function \code{transfer} that applies the analysis to one block, the
  9431. \code{bottom} and \code{join} operator for the lattice of abstract
  9432. states. The \code{analyze\_dataflow} function is formulated as a
  9433. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9434. function come from the predecessor nodes in the control-flow
  9435. graph. However, liveness analysis is a \emph{backward} dataflow
  9436. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9437. function with the transpose of the control-flow graph.
  9438. The algorithm begins by creating the bottom mapping, represented by a
  9439. hash table. It then pushes all of the nodes in the control-flow graph
  9440. onto the work list (a queue). The algorithm repeats the \code{while}
  9441. loop as long as there are items in the work list. In each iteration, a
  9442. node is popped from the work list and processed. The \code{input} for
  9443. the node is computed by taking the join of the abstract states of all
  9444. the predecessor nodes. The \code{transfer} function is then applied to
  9445. obtain the \code{output} abstract state. If the output differs from
  9446. the previous state for this block, the mapping for this block is
  9447. updated and its successor nodes are pushed onto the work list.
  9448. \begin{figure}[tb]
  9449. {\if\edition\racketEd
  9450. \begin{lstlisting}
  9451. (define (analyze_dataflow G transfer bottom join)
  9452. (define mapping (make-hash))
  9453. (for ([v (in-vertices G)])
  9454. (dict-set! mapping v bottom))
  9455. (define worklist (make-queue))
  9456. (for ([v (in-vertices G)])
  9457. (enqueue! worklist v))
  9458. (define trans-G (transpose G))
  9459. (while (not (queue-empty? worklist))
  9460. (define node (dequeue! worklist))
  9461. (define input (for/fold ([state bottom])
  9462. ([pred (in-neighbors trans-G node)])
  9463. (join state (dict-ref mapping pred))))
  9464. (define output (transfer node input))
  9465. (cond [(not (equal? output (dict-ref mapping node)))
  9466. (dict-set! mapping node output)
  9467. (for ([v (in-neighbors G node)])
  9468. (enqueue! worklist v))]))
  9469. mapping)
  9470. \end{lstlisting}
  9471. \fi}
  9472. {\if\edition\pythonEd
  9473. \begin{lstlisting}
  9474. def analyze_dataflow(G, transfer, bottom, join):
  9475. trans_G = transpose(G)
  9476. mapping = dict((v, bottom) for v in G.vertices())
  9477. worklist = deque(G.vertices)
  9478. while worklist:
  9479. node = worklist.pop()
  9480. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9481. output = transfer(node, input)
  9482. if output != mapping[node]:
  9483. mapping[node] = output
  9484. worklist.extend(G.adjacent(node))
  9485. \end{lstlisting}
  9486. \fi}
  9487. \caption{Generic work list algorithm for dataflow analysis}
  9488. \label{fig:generic-dataflow}
  9489. \end{figure}
  9490. {\if\edition\racketEd
  9491. \section{Mutable Variables \& Remove Complex Operands}
  9492. There is a subtle interaction between the addition of \code{set!}, the
  9493. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9494. evaluation of Racket. Consider the following example.
  9495. \begin{lstlisting}
  9496. (let ([x 2])
  9497. (+ x (begin (set! x 40) x)))
  9498. \end{lstlisting}
  9499. The result of this program is \code{42} because the first read from
  9500. \code{x} produces \code{2} and the second produces \code{40}. However,
  9501. if we naively apply the \code{remove\_complex\_operands} pass to this
  9502. example we obtain the following program whose result is \code{80}!
  9503. \begin{lstlisting}
  9504. (let ([x 2])
  9505. (let ([tmp (begin (set! x 40) x)])
  9506. (+ x tmp)))
  9507. \end{lstlisting}
  9508. The problem is that, with mutable variables, the ordering between
  9509. reads and writes is important, and the
  9510. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9511. before the first read of \code{x}.
  9512. We recommend solving this problem by giving special treatment to reads
  9513. from mutable variables, that is, variables that occur on the left-hand
  9514. side of a \code{set!}. We mark each read from a mutable variable with
  9515. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9516. that the read operation is effectful in that it can produce different
  9517. results at different points in time. Let's apply this idea to the
  9518. following variation that also involves a variable that is not mutated.
  9519. % loop_test_24.rkt
  9520. \begin{lstlisting}
  9521. (let ([x 2])
  9522. (let ([y 0])
  9523. (+ y (+ x (begin (set! x 40) x)))))
  9524. \end{lstlisting}
  9525. We analyze the above program to discover that variable \code{x} is
  9526. mutable but \code{y} is not. We then transform the program as follows,
  9527. replacing each occurence of \code{x} with \code{(get! x)}.
  9528. \begin{lstlisting}
  9529. (let ([x 2])
  9530. (let ([y 0])
  9531. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9532. \end{lstlisting}
  9533. Now that we have a clear distinction between reads from mutable and
  9534. immutable variables, we can apply the \code{remove\_complex\_operands}
  9535. pass, where reads from immutable variables are still classified as
  9536. atomic expressions but reads from mutable variables are classified as
  9537. complex. Thus, \code{remove\_complex\_operands} yields the following
  9538. program.
  9539. \begin{lstlisting}
  9540. (let ([x 2])
  9541. (let ([y 0])
  9542. (+ y (let ([t1 (get! x)])
  9543. (let ([t2 (begin (set! x 40) (get! x))])
  9544. (+ t1 t2))))))
  9545. \end{lstlisting}
  9546. The temporary variable \code{t1} gets the value of \code{x} before the
  9547. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9548. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9549. do not generate a temporary variable for the occurence of \code{y}
  9550. because it's an immutable variable. We want to avoid such unnecessary
  9551. extra temporaries because they would needless increase the number of
  9552. variables, making it more likely for some of them to be spilled. The
  9553. result of this program is \code{42}, the same as the result prior to
  9554. \code{remove\_complex\_operands}.
  9555. The approach that we've sketched above requires only a small
  9556. modification to \code{remove\_complex\_operands} to handle
  9557. \code{get!}. However, it requires a new pass, called
  9558. \code{uncover-get!}, that we discuss in
  9559. Section~\ref{sec:uncover-get-bang}.
  9560. As an aside, this problematic interaction between \code{set!} and the
  9561. pass \code{remove\_complex\_operands} is particular to Racket and not
  9562. its predecessor, the Scheme language. The key difference is that
  9563. Scheme does not specify an order of evaluation for the arguments of an
  9564. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9565. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9566. would be correct results for the example program. Interestingly,
  9567. Racket is implemented on top of the Chez Scheme
  9568. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9569. presented in this section (using extra \code{let} bindings to control
  9570. the order of evaluation) is used in the translation from Racket to
  9571. Scheme~\citep{Flatt:2019tb}.
  9572. \fi} % racket
  9573. Having discussed the complications that arise from adding support for
  9574. assignment and loops, we turn to discussing the individual compilation
  9575. passes.
  9576. {\if\edition\racketEd
  9577. \section{Uncover \texttt{get!}}
  9578. \label{sec:uncover-get-bang}
  9579. The goal of this pass it to mark uses of mutable variables so that
  9580. \code{remove\_complex\_operands} can treat them as complex expressions
  9581. and thereby preserve their ordering relative to the side-effects in
  9582. other operands. So the first step is to collect all the mutable
  9583. variables. We recommend creating an auxilliary function for this,
  9584. named \code{collect-set!}, that recursively traverses expressions,
  9585. returning a set of all variables that occur on the left-hand side of a
  9586. \code{set!}. Here's an exerpt of its implementation.
  9587. \begin{center}
  9588. \begin{minipage}{\textwidth}
  9589. \begin{lstlisting}
  9590. (define (collect-set! e)
  9591. (match e
  9592. [(Var x) (set)]
  9593. [(Int n) (set)]
  9594. [(Let x rhs body)
  9595. (set-union (collect-set! rhs) (collect-set! body))]
  9596. [(SetBang var rhs)
  9597. (set-union (set var) (collect-set! rhs))]
  9598. ...))
  9599. \end{lstlisting}
  9600. \end{minipage}
  9601. \end{center}
  9602. By placing this pass after \code{uniquify}, we need not worry about
  9603. variable shadowing and our logic for \code{let} can remain simple, as
  9604. in the exerpt above.
  9605. The second step is to mark the occurences of the mutable variables
  9606. with the new \code{GetBang} AST node (\code{get!} in concrete
  9607. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9608. function, which takes two parameters: the set of mutable varaibles
  9609. \code{set!-vars}, and the expression \code{e} to be processed. The
  9610. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9611. mutable variable or leaves it alone if not.
  9612. \begin{center}
  9613. \begin{minipage}{\textwidth}
  9614. \begin{lstlisting}
  9615. (define ((uncover-get!-exp set!-vars) e)
  9616. (match e
  9617. [(Var x)
  9618. (if (set-member? set!-vars x)
  9619. (GetBang x)
  9620. (Var x))]
  9621. ...))
  9622. \end{lstlisting}
  9623. \end{minipage}
  9624. \end{center}
  9625. To wrap things up, define the \code{uncover-get!} function for
  9626. processing a whole program, using \code{collect-set!} to obtain the
  9627. set of mutable variables and then \code{uncover-get!-exp} to replace
  9628. their occurences with \code{GetBang}.
  9629. \fi}
  9630. \section{Remove Complex Operands}
  9631. \label{sec:rco-loop}
  9632. {\if\edition\racketEd
  9633. %
  9634. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9635. \code{while} are all complex expressions. The subexpressions of
  9636. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9637. %
  9638. \fi}
  9639. {\if\edition\pythonEd
  9640. %
  9641. The change needed for this pass is to add a case for the \code{while}
  9642. statement. The condition of a \code{while} loop is allowed to be a
  9643. complex expression, just like the condition of the \code{if}
  9644. statement.
  9645. %
  9646. \fi}
  9647. %
  9648. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9649. \LangLoopANF{} of this pass.
  9650. \newcommand{\LwhileMonadASTPython}{
  9651. \begin{array}{rcl}
  9652. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9653. \end{array}
  9654. }
  9655. \begin{figure}[tp]
  9656. \centering
  9657. \fbox{
  9658. \begin{minipage}{0.96\textwidth}
  9659. \small
  9660. {\if\edition\racketEd
  9661. \[
  9662. \begin{array}{rcl}
  9663. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9664. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9665. &\MID& \GETBANG{\Var}
  9666. \MID \SETBANG{\Var}{\Exp} \\
  9667. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9668. \MID \WHILE{\Exp}{\Exp} \\
  9669. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9670. \LangLoopANF &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9671. \end{array}
  9672. \]
  9673. \fi}
  9674. {\if\edition\pythonEd
  9675. \[
  9676. \begin{array}{l}
  9677. \gray{\LvarMonadASTPython} \\ \hline
  9678. \gray{\LifMonadASTPython} \\ \hline
  9679. \LwhileMonadASTPython \\
  9680. \begin{array}{rcl}
  9681. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9682. \end{array}
  9683. \end{array}
  9684. %% \begin{array}{rcl}
  9685. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9686. %% \Exp &::=& \Atm \MID \READ{} \\
  9687. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9688. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9689. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9690. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9691. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9692. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9693. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9694. %% \end{array}
  9695. \]
  9696. \fi}
  9697. \end{minipage}
  9698. }
  9699. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9700. \label{fig:Rwhile-anf-syntax}
  9701. \end{figure}
  9702. {\if\edition\racketEd
  9703. As usual, when a complex expression appears in a grammar position that
  9704. needs to be atomic, such as the argument of a primitive operator, we
  9705. must introduce a temporary variable and bind it to the complex
  9706. expression. This approach applies, unchanged, to handle the new
  9707. language forms. For example, in the following code there are two
  9708. \code{begin} expressions appearing as arguments to \code{+}. The
  9709. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9710. expressions have been bound to temporary variables. Recall that
  9711. \code{let} expressions in \LangLoopANF{} are allowed to have
  9712. arbitrary expressions in their right-hand-side expression, so it is
  9713. fine to place \code{begin} there.
  9714. \begin{center}
  9715. \begin{minipage}{\textwidth}
  9716. \begin{lstlisting}
  9717. (let ([x0 10])
  9718. (let ([y1 0])
  9719. (+ (+ (begin (set! y1 (read)) x0)
  9720. (begin (set! x0 (read)) y1))
  9721. x0)))
  9722. |$\Rightarrow$|
  9723. (let ([x0 10])
  9724. (let ([y1 0])
  9725. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9726. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9727. (let ([tmp4 (+ tmp2 tmp3)])
  9728. (+ tmp4 x0))))))
  9729. \end{lstlisting}
  9730. \end{minipage}
  9731. \end{center}
  9732. \fi}
  9733. \section{Explicate Control \racket{and \LangCLoop{}}}
  9734. \label{sec:explicate-loop}
  9735. \newcommand{\CloopASTRacket}{
  9736. \begin{array}{lcl}
  9737. \Atm &::=& \VOID \\
  9738. \Stmt &::=& \READ{}\\
  9739. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9740. \end{array}
  9741. }
  9742. {\if\edition\racketEd
  9743. Recall that in the \code{explicate\_control} pass we define one helper
  9744. function for each kind of position in the program. For the \LangVar{}
  9745. language of integers and variables we needed kinds of positions:
  9746. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9747. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9748. yet another kind of position: effect position. Except for the last
  9749. subexpression, the subexpressions inside a \code{begin} are evaluated
  9750. only for their effect. Their result values are discarded. We can
  9751. generate better code by taking this fact into account.
  9752. The output language of \code{explicate\_control} is \LangCLoop{}
  9753. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9754. \LangCIf{}. The only syntactic difference is that \code{read} may also
  9755. appear as a statement. The most significant difference between the
  9756. programs generated by \code{explicate\_control} in
  9757. Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this chapter
  9758. is that the control-flow graphs of the later may contain cycles.
  9759. \begin{figure}[tp]
  9760. \fbox{
  9761. \begin{minipage}{0.96\textwidth}
  9762. \small
  9763. \[
  9764. \begin{array}{l}
  9765. \gray{\CvarASTRacket} \\ \hline
  9766. \gray{\CifASTRacket} \\ \hline
  9767. \CloopASTRacket \\
  9768. \begin{array}{lcl}
  9769. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9770. \end{array}
  9771. \end{array}
  9772. \]
  9773. \end{minipage}
  9774. }
  9775. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9776. \label{fig:c7-syntax}
  9777. \end{figure}
  9778. The new auxiliary function \code{explicate\_effect} takes an
  9779. expression (in an effect position) and a continuation. The function
  9780. returns a $\Tail$ that includes the generated code for the input
  9781. expression followed by the continuation. If the expression is
  9782. obviously pure, that is, never causes side effects, then the
  9783. expression can be removed, so the result is just the continuation.
  9784. %
  9785. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9786. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9787. the loop. Recursively process the \itm{body} (in effect position)
  9788. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9789. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9790. \itm{body'} as the then-branch and the continuation block as the
  9791. else-branch. The result should be added to the control-flow graph with
  9792. the label \itm{loop}. The result for the whole \code{while} loop is a
  9793. \code{goto} to the \itm{loop} label.
  9794. The auxiliary functions for tail, assignment, and predicate positions
  9795. need to be updated. The three new language forms, \code{while},
  9796. \code{set!}, and \code{begin}, can appear in assignment and tail
  9797. positions. Only \code{begin} may appear in predicate positions; the
  9798. other two have result type \code{Void}.
  9799. \fi}
  9800. %
  9801. {\if\edition\pythonEd
  9802. %
  9803. The output of this pass is the language \LangCIf{}. No new language
  9804. features are needed in the output because a \code{while} loop can be
  9805. expressed in terms of \code{goto} and \code{if} statements, which are
  9806. already in \LangCIf{}.
  9807. %
  9808. Add a case for the \code{while} statement to the
  9809. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9810. the condition expression.
  9811. %
  9812. \fi}
  9813. {\if\edition\racketEd
  9814. \section{Select Instructions}
  9815. \label{sec:select-instructions-loop}
  9816. Only three small additions are needed in the
  9817. \code{select\_instructions} pass to handle the changes to
  9818. \LangCLoop{}. That is, a call to
  9819. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9820. stand-alone statement instead of only appearing on the right-hand side
  9821. of an assignment statement. The code generation is nearly identical;
  9822. just leave off the instruction for moving the result into the
  9823. left-hand side.
  9824. \fi}
  9825. \section{Register Allocation}
  9826. \label{sec:register-allocation-loop}
  9827. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9828. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9829. which complicates the liveness analysis needed for register
  9830. allocation.
  9831. \subsection{Liveness Analysis}
  9832. \label{sec:liveness-analysis-r8}
  9833. We recommend using the generic \code{analyze\_dataflow} function that
  9834. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9835. perform liveness analysis, replacing the code in
  9836. \code{uncover\_live} that processed the basic blocks in topological
  9837. order (Section~\ref{sec:liveness-analysis-Lif}).
  9838. The \code{analyze\_dataflow} function has four parameters.
  9839. \begin{enumerate}
  9840. \item The first parameter \code{G} should be a directed graph from the
  9841. \racket{
  9842. \code{racket/graph} package (see the sidebar in
  9843. Section~\ref{sec:build-interference})}
  9844. \python{\code{graph.py} file in the support code}
  9845. that represents the
  9846. control-flow graph.
  9847. \item The second parameter \code{transfer} is a function that applies
  9848. liveness analysis to a basic block. It takes two parameters: the
  9849. label for the block to analyze and the live-after set for that
  9850. block. The transfer function should return the live-before set for
  9851. the block.
  9852. %
  9853. \racket{Also, as a side-effect, it should update the block's
  9854. $\itm{info}$ with the liveness information for each instruction.}
  9855. %
  9856. \python{Also, as a side-effect, it should update the live-before and
  9857. live-after sets for each instruction.}
  9858. %
  9859. To implement the \code{transfer} function, you should be able to
  9860. reuse the code you already have for analyzing basic blocks.
  9861. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9862. \code{bottom} and \code{join} for the lattice of abstract states,
  9863. i.e. sets of locations. The bottom of the lattice is the empty set
  9864. and the join operator is set union.
  9865. \end{enumerate}
  9866. \begin{figure}[p]
  9867. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9868. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9869. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9870. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9871. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9872. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9873. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9874. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9875. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9876. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9877. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9878. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9879. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9880. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9881. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9882. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9883. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9884. %% \path[->,bend left=15] (Rfun) edge [above] node
  9885. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9886. \path[->,bend left=15] (Rfun) edge [above] node
  9887. {\ttfamily\footnotesize shrink} (Rfun-2);
  9888. \path[->,bend left=15] (Rfun-2) edge [above] node
  9889. {\ttfamily\footnotesize uniquify} (F1-4);
  9890. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9891. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9892. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9893. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9894. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9895. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9896. %% \path[->,bend right=15] (F1-2) edge [above] node
  9897. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9898. %% \path[->,bend right=15] (F1-3) edge [above] node
  9899. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9900. \path[->,bend left=15] (F1-4) edge [above] node
  9901. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9902. \path[->,bend left=15] (F1-5) edge [right] node
  9903. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9904. \path[->,bend left=15] (C3-2) edge [left] node
  9905. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9906. \path[->,bend right=15] (x86-2) edge [left] node
  9907. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9908. \path[->,bend right=15] (x86-2-1) edge [below] node
  9909. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9910. \path[->,bend right=15] (x86-2-2) edge [left] node
  9911. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9912. \path[->,bend left=15] (x86-3) edge [above] node
  9913. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9914. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9915. \end{tikzpicture}
  9916. \caption{Diagram of the passes for \LangLoop{}.}
  9917. \label{fig:Rwhile-passes}
  9918. \end{figure}
  9919. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9920. for the compilation of \LangLoop{}.
  9921. % Further Reading: dataflow analysis
  9922. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9923. \chapter{Tuples and Garbage Collection}
  9924. \label{ch:Lvec}
  9925. \index{subject}{tuple}
  9926. \index{subject}{vector}
  9927. \index{subject}{allocate}
  9928. \index{subject}{heap allocate}
  9929. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9930. %% all the IR grammars are spelled out! \\ --Jeremy}
  9931. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9932. %% the root stack. \\ --Jeremy}
  9933. In this chapter we study the implementation of
  9934. tuples\racket{, called vectors in Racket}.
  9935. %
  9936. This language feature is the first to use the computer's
  9937. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9938. indefinite, that is, a tuple lives forever from the programmer's
  9939. viewpoint. Of course, from an implementer's viewpoint, it is important
  9940. to reclaim the space associated with a tuple when it is no longer
  9941. needed, which is why we also study \emph{garbage collection}
  9942. \index{garbage collection} techniques in this chapter.
  9943. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9944. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9945. language of Chapter~\ref{ch:Lwhile} with tuples.
  9946. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  9947. copying live tuples back and forth between two halves of the heap. The
  9948. garbage collector requires coordination with the compiler so that it
  9949. can find all of the live tuples.
  9950. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  9951. discuss the necessary changes and additions to the compiler passes,
  9952. including a new compiler pass named \code{expose\_allocation}.
  9953. \section{The \LangVec{} Language}
  9954. \label{sec:r3}
  9955. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  9956. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  9957. %
  9958. \racket{The \LangVec{} language includes the forms: \code{vector} for
  9959. creating a tuple, \code{vector-ref} for reading an element of a
  9960. tuple, \code{vector-set!} for writing to an element of a tuple, and
  9961. \code{vector-length} for obtaining the number of elements of a
  9962. tuple.}
  9963. %
  9964. \python{The \LangVec{} language adds 1) tuple creation via a
  9965. comma-separated list of expressions, 2) accessing an element of a
  9966. tuple with the square bracket notation, i.e., \code{t[n]} returns
  9967. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  9968. operator, and 4) obtaining the number of elements (the length) of a
  9969. tuple. In this chapter, we restrict access indices to constant
  9970. integers.}
  9971. %
  9972. The program below shows an example use of tuples. It creates a tuple
  9973. \code{t} containing the elements \code{40},
  9974. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  9975. contains just \code{2}. The element at index $1$ of \code{t} is
  9976. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  9977. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  9978. to which we add \code{2}, the element at index $0$ of the tuple. So
  9979. the result of the program is \code{42}.
  9980. %
  9981. {\if\edition\racketEd
  9982. \begin{lstlisting}
  9983. (let ([t (vector 40 #t (vector 2))])
  9984. (if (vector-ref t 1)
  9985. (+ (vector-ref t 0)
  9986. (vector-ref (vector-ref t 2) 0))
  9987. 44))
  9988. \end{lstlisting}
  9989. \fi}
  9990. {\if\edition\pythonEd
  9991. \begin{lstlisting}
  9992. t = 40, True, (2,)
  9993. print( t[0] + t[2][0] if t[1] else 44 )
  9994. \end{lstlisting}
  9995. \fi}
  9996. \newcommand{\LtupGrammarRacket}{
  9997. \begin{array}{lcl}
  9998. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  9999. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  10000. \MID \LP\key{vector-length}\;\Exp\RP \\
  10001. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10002. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10003. \end{array}
  10004. }
  10005. \newcommand{\LtupASTRacket}{
  10006. \begin{array}{lcl}
  10007. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10008. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10009. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10010. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10011. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10012. \end{array}
  10013. }
  10014. \newcommand{\LtupGrammarPython}{
  10015. \begin{array}{rcl}
  10016. \itm{cmp} &::= & \key{is} \\
  10017. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10018. \end{array}
  10019. }
  10020. \newcommand{\LtupASTPython}{
  10021. \begin{array}{lcl}
  10022. \itm{cmp} &::= & \code{Is()} \\
  10023. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10024. &\MID& \LEN{\Exp}
  10025. \end{array}
  10026. }
  10027. \begin{figure}[tbp]
  10028. \centering
  10029. \fbox{
  10030. \begin{minipage}{0.96\textwidth}
  10031. {\if\edition\racketEd
  10032. \[
  10033. \begin{array}{l}
  10034. \gray{\LintGrammarRacket{}} \\ \hline
  10035. \gray{\LvarGrammarRacket{}} \\ \hline
  10036. \gray{\LifGrammarRacket{}} \\ \hline
  10037. \gray{\LwhileGrammarRacket} \\ \hline
  10038. \LtupGrammarRacket \\
  10039. \begin{array}{lcl}
  10040. \LangVecM{} &::=& \Exp
  10041. \end{array}
  10042. \end{array}
  10043. \]
  10044. \fi}
  10045. {\if\edition\pythonEd
  10046. \[
  10047. \begin{array}{l}
  10048. \gray{\LintGrammarPython{}} \\ \hline
  10049. \gray{\LvarGrammarPython{}} \\ \hline
  10050. \gray{\LifGrammarPython{}} \\ \hline
  10051. \gray{\LwhileGrammarPython} \\ \hline
  10052. \LtupGrammarPython \\
  10053. \begin{array}{rcl}
  10054. \LangVecM{} &::=& \Stmt^{*}
  10055. \end{array}
  10056. \end{array}
  10057. \]
  10058. \fi}
  10059. \end{minipage}
  10060. }
  10061. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10062. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10063. \label{fig:Lvec-concrete-syntax}
  10064. \end{figure}
  10065. \begin{figure}[tp]
  10066. \centering
  10067. \fbox{
  10068. \begin{minipage}{0.96\textwidth}
  10069. {\if\edition\racketEd
  10070. \[
  10071. \begin{array}{l}
  10072. \gray{\LintOpAST} \\ \hline
  10073. \gray{\LvarASTRacket{}} \\ \hline
  10074. \gray{\LifASTRacket{}} \\ \hline
  10075. \gray{\LwhileASTRacket{}} \\ \hline
  10076. \LtupASTRacket{} \\
  10077. \begin{array}{lcl}
  10078. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10079. \end{array}
  10080. \end{array}
  10081. \]
  10082. \fi}
  10083. {\if\edition\pythonEd
  10084. \[
  10085. \begin{array}{l}
  10086. \gray{\LintASTPython} \\ \hline
  10087. \gray{\LvarASTPython} \\ \hline
  10088. \gray{\LifASTPython} \\ \hline
  10089. \gray{\LwhileASTPython} \\ \hline
  10090. \LtupASTPython \\
  10091. \begin{array}{lcl}
  10092. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10093. \end{array}
  10094. \end{array}
  10095. \]
  10096. \fi}
  10097. \end{minipage}
  10098. }
  10099. \caption{The abstract syntax of \LangVec{}.}
  10100. \label{fig:Lvec-syntax}
  10101. \end{figure}
  10102. Tuples raise several interesting new issues. First, variable binding
  10103. performs a shallow-copy when dealing with tuples, which means that
  10104. different variables can refer to the same tuple, that is, two
  10105. variables can be \emph{aliases}\index{subject}{alias} for the same
  10106. entity. Consider the following example in which both \code{t1} and
  10107. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10108. different tuple value but with equal elements. The result of the
  10109. program is \code{42}.
  10110. \begin{center}
  10111. \begin{minipage}{0.96\textwidth}
  10112. {\if\edition\racketEd
  10113. \begin{lstlisting}
  10114. (let ([t1 (vector 3 7)])
  10115. (let ([t2 t1])
  10116. (let ([t3 (vector 3 7)])
  10117. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10118. 42
  10119. 0))))
  10120. \end{lstlisting}
  10121. \fi}
  10122. {\if\edition\pythonEd
  10123. \begin{lstlisting}
  10124. t1 = 3, 7
  10125. t2 = t1
  10126. t3 = 3, 7
  10127. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10128. \end{lstlisting}
  10129. \fi}
  10130. \end{minipage}
  10131. \end{center}
  10132. {\if\edition\racketEd
  10133. Whether two variables are aliased or not affects what happens
  10134. when the underlying tuple is mutated\index{subject}{mutation}.
  10135. Consider the following example in which \code{t1} and \code{t2}
  10136. again refer to the same tuple value.
  10137. \begin{center}
  10138. \begin{minipage}{0.96\textwidth}
  10139. \begin{lstlisting}
  10140. (let ([t1 (vector 3 7)])
  10141. (let ([t2 t1])
  10142. (let ([_ (vector-set! t2 0 42)])
  10143. (vector-ref t1 0))))
  10144. \end{lstlisting}
  10145. \end{minipage}
  10146. \end{center}
  10147. The mutation through \code{t2} is visible when referencing the tuple
  10148. from \code{t1}, so the result of this program is \code{42}.
  10149. \fi}
  10150. The next issue concerns the lifetime of tuples. When does their
  10151. lifetime end? Notice that \LangVec{} does not include an operation
  10152. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10153. to any notion of static scoping.
  10154. %
  10155. {\if\edition\racketEd
  10156. %
  10157. For example, the following program returns \code{42} even though the
  10158. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10159. that reads from the vector it was bound to.
  10160. \begin{center}
  10161. \begin{minipage}{0.96\textwidth}
  10162. \begin{lstlisting}
  10163. (let ([v (vector (vector 44))])
  10164. (let ([x (let ([w (vector 42)])
  10165. (let ([_ (vector-set! v 0 w)])
  10166. 0))])
  10167. (+ x (vector-ref (vector-ref v 0) 0))))
  10168. \end{lstlisting}
  10169. \end{minipage}
  10170. \end{center}
  10171. \fi}
  10172. %
  10173. {\if\edition\pythonEd
  10174. %
  10175. For example, the following program returns \code{42} even though the
  10176. variable \code{x} goes out of scope when the function returns, prior
  10177. to reading the tuple element at index zero. (We study the compilation
  10178. of functions in Chapter~\ref{ch:Lfun}.)
  10179. %
  10180. \begin{center}
  10181. \begin{minipage}{0.96\textwidth}
  10182. \begin{lstlisting}
  10183. def f():
  10184. x = 42, 43
  10185. return x
  10186. t = f()
  10187. print( t[0] )
  10188. \end{lstlisting}
  10189. \end{minipage}
  10190. \end{center}
  10191. \fi}
  10192. %
  10193. From the perspective of programmer-observable behavior, tuples live
  10194. forever. However, if they really lived forever then many long-running
  10195. programs would run out of memory. To solve this problem, the
  10196. language's runtime system performs automatic garbage collection.
  10197. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10198. \LangVec{} language.
  10199. %
  10200. \racket{We define the \code{vector}, \code{vector-ref},
  10201. \code{vector-set!}, and \code{vector-length} operations for
  10202. \LangVec{} in terms of the corresponding operations in Racket. One
  10203. subtle point is that the \code{vector-set!} operation returns the
  10204. \code{\#<void>} value.}
  10205. %
  10206. \python{We represent tuples with Python lists in the interpreter
  10207. because we need to write to them
  10208. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10209. immutable.) We define element access, the \code{is} operator, and
  10210. the \code{len} operator for \LangVec{} in terms of the corresponding
  10211. operations in Python.}
  10212. \begin{figure}[tbp]
  10213. {\if\edition\racketEd
  10214. \begin{lstlisting}
  10215. (define interp-Lvec_class
  10216. (class interp-Lif_class
  10217. (super-new)
  10218. (define/override (interp-op op)
  10219. (match op
  10220. ['eq? (lambda (v1 v2)
  10221. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10222. (and (boolean? v1) (boolean? v2))
  10223. (and (vector? v1) (vector? v2))
  10224. (and (void? v1) (void? v2)))
  10225. (eq? v1 v2)]))]
  10226. ['vector vector]
  10227. ['vector-length vector-length]
  10228. ['vector-ref vector-ref]
  10229. ['vector-set! vector-set!]
  10230. [else (super interp-op op)]
  10231. ))
  10232. (define/override ((interp-exp env) e)
  10233. (define recur (interp-exp env))
  10234. (match e
  10235. [(HasType e t) (recur e)]
  10236. [(Void) (void)]
  10237. [else ((super interp-exp env) e)]
  10238. ))
  10239. ))
  10240. (define (interp-Lvec p)
  10241. (send (new interp-Lvec_class) interp-program p))
  10242. \end{lstlisting}
  10243. \fi}
  10244. %
  10245. {\if\edition\pythonEd
  10246. \begin{lstlisting}
  10247. class InterpLtup(InterpLwhile):
  10248. def interp_cmp(self, cmp):
  10249. match cmp:
  10250. case Is():
  10251. return lambda x, y: x is y
  10252. case _:
  10253. return super().interp_cmp(cmp)
  10254. def interp_exp(self, e, env):
  10255. match e:
  10256. case Tuple(es, Load()):
  10257. return tuple([self.interp_exp(e, env) for e in es])
  10258. case Subscript(tup, index, Load()):
  10259. t = self.interp_exp(tup, env)
  10260. n = self.interp_exp(index, env)
  10261. return t[n]
  10262. case _:
  10263. return super().interp_exp(e, env)
  10264. \end{lstlisting}
  10265. \fi}
  10266. \caption{Interpreter for the \LangVec{} language.}
  10267. \label{fig:interp-Lvec}
  10268. \end{figure}
  10269. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10270. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10271. we need to know which elements of the tuple are themselves tuples for
  10272. the purposes of garbage collection. We can obtain this information
  10273. during type checking. The type checker in
  10274. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10275. expression, it also
  10276. %
  10277. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10278. where $T$ is the vector's type.
  10279. To create the s-expression for the \code{Vector} type in
  10280. Figure~\ref{fig:type-check-Lvec}, we use the
  10281. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10282. operator} \code{,@} to insert the list \code{t*} without its usual
  10283. start and end parentheses. \index{subject}{unquote-slicing}}
  10284. %
  10285. \python{records the type of each tuple expression in a new field
  10286. named \code{has\_type}. Because the type checker has to compute the type
  10287. of each tuple access, the index must be a constant.}
  10288. \begin{figure}[tp]
  10289. {\if\edition\racketEd
  10290. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10291. (define type-check-Lvec_class
  10292. (class type-check-Lif_class
  10293. (super-new)
  10294. (inherit check-type-equal?)
  10295. (define/override (type-check-exp env)
  10296. (lambda (e)
  10297. (define recur (type-check-exp env))
  10298. (match e
  10299. [(Void) (values (Void) 'Void)]
  10300. [(Prim 'vector es)
  10301. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10302. (define t `(Vector ,@t*))
  10303. (values (HasType (Prim 'vector e*) t) t)]
  10304. [(Prim 'vector-ref (list e1 (Int i)))
  10305. (define-values (e1^ t) (recur e1))
  10306. (match t
  10307. [`(Vector ,ts ...)
  10308. (unless (and (0 . <= . i) (i . < . (length ts)))
  10309. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10310. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10311. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10312. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10313. (define-values (e-vec t-vec) (recur e1))
  10314. (define-values (e-arg^ t-arg) (recur arg))
  10315. (match t-vec
  10316. [`(Vector ,ts ...)
  10317. (unless (and (0 . <= . i) (i . < . (length ts)))
  10318. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10319. (check-type-equal? (list-ref ts i) t-arg e)
  10320. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10321. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10322. [(Prim 'vector-length (list e))
  10323. (define-values (e^ t) (recur e))
  10324. (match t
  10325. [`(Vector ,ts ...)
  10326. (values (Prim 'vector-length (list e^)) 'Integer)]
  10327. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10328. [(Prim 'eq? (list arg1 arg2))
  10329. (define-values (e1 t1) (recur arg1))
  10330. (define-values (e2 t2) (recur arg2))
  10331. (match* (t1 t2)
  10332. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10333. [(other wise) (check-type-equal? t1 t2 e)])
  10334. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10335. [(HasType (Prim 'vector es) t)
  10336. ((type-check-exp env) (Prim 'vector es))]
  10337. [(HasType e1 t)
  10338. (define-values (e1^ t^) (recur e1))
  10339. (check-type-equal? t t^ e)
  10340. (values (HasType e1^ t) t)]
  10341. [else ((super type-check-exp env) e)]
  10342. )))
  10343. ))
  10344. (define (type-check-Lvec p)
  10345. (send (new type-check-Lvec_class) type-check-program p))
  10346. \end{lstlisting}
  10347. \fi}
  10348. {\if\edition\pythonEd
  10349. \begin{lstlisting}
  10350. class TypeCheckLtup(TypeCheckLwhile):
  10351. def type_check_exp(self, e, env):
  10352. match e:
  10353. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10354. l = self.type_check_exp(left, env)
  10355. r = self.type_check_exp(right, env)
  10356. check_type_equal(l, r, e)
  10357. return bool
  10358. case Tuple(es, Load()):
  10359. ts = [self.type_check_exp(e, env) for e in es]
  10360. e.has_type = tuple(ts)
  10361. return e.has_type
  10362. case Subscript(tup, Constant(index), Load()):
  10363. tup_ty = self.type_check_exp(tup, env)
  10364. index_ty = self.type_check_exp(Constant(index), env)
  10365. check_type_equal(index_ty, int, index)
  10366. match tup_ty:
  10367. case tuple(ts):
  10368. return ts[index]
  10369. case _:
  10370. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10371. case _:
  10372. return super().type_check_exp(e, env)
  10373. \end{lstlisting}
  10374. \fi}
  10375. \caption{Type checker for the \LangVec{} language.}
  10376. \label{fig:type-check-Lvec}
  10377. \end{figure}
  10378. \section{Garbage Collection}
  10379. \label{sec:GC}
  10380. Garbage collection is a runtime technique for reclaiming space on the
  10381. heap that will not be used in the future of the running program. We
  10382. use the term \emph{object}\index{subject}{object} to refer to any
  10383. value that is stored in the heap, which for now only includes
  10384. tuples.%
  10385. %
  10386. \footnote{The term ``object'' as used in the context of
  10387. object-oriented programming has a more specific meaning than how we
  10388. are using the term here.}
  10389. %
  10390. Unfortunately, it is impossible to know precisely which objects will
  10391. be accessed in the future and which will not. Instead, garbage
  10392. collectors overapproximate the set of objects that will be accessed by
  10393. identifying which objects can possibly be accessed. The running
  10394. program can directly access objects that are in registers and on the
  10395. procedure call stack. It can also transitively access the elements of
  10396. tuples, starting with a tuple whose address is in a register or on the
  10397. procedure call stack. We define the \emph{root
  10398. set}\index{subject}{root set} to be all the tuple addresses that are
  10399. in registers or on the procedure call stack. We define the \emph{live
  10400. objects}\index{subject}{live objects} to be the objects that are
  10401. reachable from the root set. Garbage collectors reclaim the space that
  10402. is allocated to objects that are no longer live. That means that some
  10403. objects may not get reclaimed as soon as they could be, but at least
  10404. garbage collectors do not reclaim the space dedicated to objects that
  10405. will be accessed in the future! The programmer can influence which
  10406. objects get reclaimed by causing them to become unreachable.
  10407. So the goal of the garbage collector is twofold:
  10408. \begin{enumerate}
  10409. \item preserve all the live objects, and
  10410. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10411. \end{enumerate}
  10412. \subsection{Two-Space Copying Collector}
  10413. Here we study a relatively simple algorithm for garbage collection
  10414. that is the basis of many state-of-the-art garbage
  10415. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10416. particular, we describe a two-space copying
  10417. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10418. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10419. collector} \index{subject}{two-space copying collector}
  10420. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10421. what happens in a two-space collector, showing two time steps, prior
  10422. to garbage collection (on the top) and after garbage collection (on
  10423. the bottom). In a two-space collector, the heap is divided into two
  10424. parts named the FromSpace\index{subject}{FromSpace} and the
  10425. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10426. FromSpace until there is not enough room for the next allocation
  10427. request. At that point, the garbage collector goes to work to room for
  10428. the next allocation.
  10429. A copying collector makes more room by copying all of the live objects
  10430. from the FromSpace into the ToSpace and then performs a sleight of
  10431. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10432. as the new ToSpace. In the example of
  10433. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10434. root set, one in a register and two on the stack. All of the live
  10435. objects have been copied to the ToSpace (the right-hand side of
  10436. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10437. pointer relationships. For example, the pointer in the register still
  10438. points to a tuple that in turn points to two other tuples. There are
  10439. four tuples that are not reachable from the root set and therefore do
  10440. not get copied into the ToSpace.
  10441. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10442. created by a well-typed program in \LangVec{} because it contains a
  10443. cycle. However, creating cycles will be possible once we get to
  10444. \LangDyn{}. We design the garbage collector to deal with cycles to
  10445. begin with so we will not need to revisit this issue.
  10446. \begin{figure}[tbp]
  10447. \centering
  10448. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10449. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10450. \\[5ex]
  10451. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10452. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10453. \caption{A copying collector in action.}
  10454. \label{fig:copying-collector}
  10455. \end{figure}
  10456. \subsection{Graph Copying via Cheney's Algorithm}
  10457. \label{sec:cheney}
  10458. \index{subject}{Cheney's algorithm}
  10459. Let us take a closer look at the copying of the live objects. The
  10460. allocated objects and pointers can be viewed as a graph and we need to
  10461. copy the part of the graph that is reachable from the root set. To
  10462. make sure we copy all of the reachable vertices in the graph, we need
  10463. an exhaustive graph traversal algorithm, such as depth-first search or
  10464. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10465. such algorithms take into account the possibility of cycles by marking
  10466. which vertices have already been visited, so as to ensure termination
  10467. of the algorithm. These search algorithms also use a data structure
  10468. such as a stack or queue as a to-do list to keep track of the vertices
  10469. that need to be visited. We use breadth-first search and a trick
  10470. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10471. and copying tuples into the ToSpace.
  10472. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10473. copy progresses. The queue is represented by a chunk of contiguous
  10474. memory at the beginning of the ToSpace, using two pointers to track
  10475. the front and the back of the queue, called the \emph{free pointer}
  10476. and the \emph{scan pointer} respectively. The algorithm starts by
  10477. copying all tuples that are immediately reachable from the root set
  10478. into the ToSpace to form the initial queue. When we copy a tuple, we
  10479. mark the old tuple to indicate that it has been visited. We discuss
  10480. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10481. that any pointers inside the copied tuples in the queue still point
  10482. back to the FromSpace. Once the initial queue has been created, the
  10483. algorithm enters a loop in which it repeatedly processes the tuple at
  10484. the front of the queue and pops it off the queue. To process a tuple,
  10485. the algorithm copies all the tuple that are directly reachable from it
  10486. to the ToSpace, placing them at the back of the queue. The algorithm
  10487. then updates the pointers in the popped tuple so they point to the
  10488. newly copied tuples.
  10489. \begin{figure}[tbp]
  10490. \centering
  10491. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10492. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10493. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10494. \label{fig:cheney}
  10495. \end{figure}
  10496. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10497. tuple whose second element is $42$ to the back of the queue. The other
  10498. pointer goes to a tuple that has already been copied, so we do not
  10499. need to copy it again, but we do need to update the pointer to the new
  10500. location. This can be accomplished by storing a \emph{forwarding
  10501. pointer}\index{subect}{forwarding pointer} to the new location in the
  10502. old tuple, back when we initially copied the tuple into the
  10503. ToSpace. This completes one step of the algorithm. The algorithm
  10504. continues in this way until the queue is empty, that is, when the scan
  10505. pointer catches up with the free pointer.
  10506. \subsection{Data Representation}
  10507. \label{sec:data-rep-gc}
  10508. The garbage collector places some requirements on the data
  10509. representations used by our compiler. First, the garbage collector
  10510. needs to distinguish between pointers and other kinds of data such as
  10511. integers. There are several ways to accomplish this.
  10512. \begin{enumerate}
  10513. \item Attached a tag to each object that identifies what type of
  10514. object it is~\citep{McCarthy:1960dz}.
  10515. \item Store different types of objects in different
  10516. regions~\citep{Steele:1977ab}.
  10517. \item Use type information from the program to either generate
  10518. type-specific code for collecting or to generate tables that can
  10519. guide the
  10520. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10521. \end{enumerate}
  10522. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10523. need to tag objects anyways, so option 1 is a natural choice for those
  10524. languages. However, \LangVec{} is a statically typed language, so it
  10525. would be unfortunate to require tags on every object, especially small
  10526. and pervasive objects like integers and Booleans. Option 3 is the
  10527. best-performing choice for statically typed languages, but comes with
  10528. a relatively high implementation complexity. To keep this chapter
  10529. within a reasonable time budget, we recommend a combination of options
  10530. 1 and 2, using separate strategies for the stack and the heap.
  10531. Regarding the stack, we recommend using a separate stack for pointers,
  10532. which we call the \emph{root stack}\index{subject}{root stack}
  10533. (a.k.a. ``shadow
  10534. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10535. is, when a local variable needs to be spilled and is of type
  10536. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10537. root stack instead of putting it on the procedure call
  10538. stack. Furthermore, we always spill tuple-typed variables if they are
  10539. live during a call to the collector, thereby ensuring that no pointers
  10540. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10541. reproduces the example from Figure~\ref{fig:copying-collector} and
  10542. contrasts it with the data layout using a root stack. The root stack
  10543. contains the two pointers from the regular stack and also the pointer
  10544. in the second register.
  10545. \begin{figure}[tbp]
  10546. \centering
  10547. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10548. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10549. \caption{Maintaining a root stack to facilitate garbage collection.}
  10550. \label{fig:shadow-stack}
  10551. \end{figure}
  10552. The problem of distinguishing between pointers and other kinds of data
  10553. also arises inside of each tuple on the heap. We solve this problem by
  10554. attaching a tag, an extra 64-bits, to each
  10555. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10556. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10557. that we have drawn the bits in a big-endian way, from right-to-left,
  10558. with bit location 0 (the least significant bit) on the far right,
  10559. which corresponds to the direction of the x86 shifting instructions
  10560. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10561. is dedicated to specifying which elements of the tuple are pointers,
  10562. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10563. indicates there is a pointer and a 0 bit indicates some other kind of
  10564. data. The pointer mask starts at bit location 7. We limit tuples to a
  10565. maximum size of 50 elements, so we just need 50 bits for the pointer
  10566. mask.%
  10567. %
  10568. \footnote{A production-quality compiler would handle
  10569. arbitrary-sized tuples and use a more complex approach.}
  10570. %
  10571. The tag also contains two other pieces of information. The length of
  10572. the tuple (number of elements) is stored in bits location 1 through
  10573. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10574. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10575. has not yet been copied. If the bit has value 0 then the entire tag
  10576. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10577. zero anyways because our tuples are 8-byte aligned.)
  10578. \begin{figure}[tbp]
  10579. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10580. \caption{Representation of tuples in the heap.}
  10581. \label{fig:tuple-rep}
  10582. \end{figure}
  10583. \subsection{Implementation of the Garbage Collector}
  10584. \label{sec:organize-gz}
  10585. \index{subject}{prelude}
  10586. An implementation of the copying collector is provided in the
  10587. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10588. interface to the garbage collector that is used by the compiler. The
  10589. \code{initialize} function creates the FromSpace, ToSpace, and root
  10590. stack and should be called in the prelude of the \code{main}
  10591. function. The arguments of \code{initialize} are the root stack size
  10592. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10593. good choice for both. The \code{initialize} function puts the address
  10594. of the beginning of the FromSpace into the global variable
  10595. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10596. the address that is 1-past the last element of the FromSpace. (We use
  10597. half-open intervals to represent chunks of
  10598. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10599. points to the first element of the root stack.
  10600. As long as there is room left in the FromSpace, your generated code
  10601. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10602. %
  10603. The amount of room left in FromSpace is the difference between the
  10604. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10605. function should be called when there is not enough room left in the
  10606. FromSpace for the next allocation. The \code{collect} function takes
  10607. a pointer to the current top of the root stack (one past the last item
  10608. that was pushed) and the number of bytes that need to be
  10609. allocated. The \code{collect} function performs the copying collection
  10610. and leaves the heap in a state such that the next allocation will
  10611. succeed.
  10612. \begin{figure}[tbp]
  10613. \begin{lstlisting}
  10614. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10615. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10616. int64_t* free_ptr;
  10617. int64_t* fromspace_begin;
  10618. int64_t* fromspace_end;
  10619. int64_t** rootstack_begin;
  10620. \end{lstlisting}
  10621. \caption{The compiler's interface to the garbage collector.}
  10622. \label{fig:gc-header}
  10623. \end{figure}
  10624. %% \begin{exercise}
  10625. %% In the file \code{runtime.c} you will find the implementation of
  10626. %% \code{initialize} and a partial implementation of \code{collect}.
  10627. %% The \code{collect} function calls another function, \code{cheney},
  10628. %% to perform the actual copy, and that function is left to the reader
  10629. %% to implement. The following is the prototype for \code{cheney}.
  10630. %% \begin{lstlisting}
  10631. %% static void cheney(int64_t** rootstack_ptr);
  10632. %% \end{lstlisting}
  10633. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10634. %% rootstack (which is an array of pointers). The \code{cheney} function
  10635. %% also communicates with \code{collect} through the global
  10636. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10637. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10638. %% the ToSpace:
  10639. %% \begin{lstlisting}
  10640. %% static int64_t* tospace_begin;
  10641. %% static int64_t* tospace_end;
  10642. %% \end{lstlisting}
  10643. %% The job of the \code{cheney} function is to copy all the live
  10644. %% objects (reachable from the root stack) into the ToSpace, update
  10645. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10646. %% update the root stack so that it points to the objects in the
  10647. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10648. %% and ToSpace.
  10649. %% \end{exercise}
  10650. The introduction of garbage collection has a non-trivial impact on our
  10651. compiler passes. We introduce a new compiler pass named
  10652. \code{expose\_allocation}. We make significant changes to
  10653. \code{select\_instructions}, \code{build\_interference},
  10654. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10655. make minor changes in several more passes. The following program will
  10656. serve as our running example. It creates two tuples, one nested
  10657. inside the other. Both tuples have length one. The program accesses
  10658. the element in the inner tuple.
  10659. % tests/vectors_test_17.rkt
  10660. {\if\edition\racketEd
  10661. \begin{lstlisting}
  10662. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10663. \end{lstlisting}
  10664. \fi}
  10665. {\if\edition\pythonEd
  10666. \begin{lstlisting}
  10667. print( ((42,),)[0][0] )
  10668. \end{lstlisting}
  10669. \fi}
  10670. {\if\edition\racketEd
  10671. \section{Shrink}
  10672. \label{sec:shrink-Lvec}
  10673. Recall that the \code{shrink} pass translates the primitives operators
  10674. into a smaller set of primitives.
  10675. %
  10676. This pass comes after type checking and the type checker adds a
  10677. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10678. need to add a case for \code{HasType} to the \code{shrink} pass.
  10679. \fi}
  10680. \section{Expose Allocation}
  10681. \label{sec:expose-allocation}
  10682. The pass \code{expose\_allocation} lowers tuple creation into a
  10683. conditional call to the collector followed by allocating the
  10684. appropriate amount of memory and initializing it. We choose to place
  10685. the \code{expose\_allocation} pass before
  10686. \code{remove\_complex\_operands} because the code generated by
  10687. \code{expose\_allocation} contains complex operands.
  10688. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10689. that extends \LangVec{} with new forms that we use in the translation
  10690. of tuple creation.
  10691. %
  10692. {\if\edition\racketEd
  10693. \[
  10694. \begin{array}{lcl}
  10695. \Exp &::=& \cdots
  10696. \MID (\key{collect} \,\itm{int})
  10697. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10698. \MID (\key{global-value} \,\itm{name})
  10699. \end{array}
  10700. \]
  10701. \fi}
  10702. {\if\edition\pythonEd
  10703. \[
  10704. \begin{array}{lcl}
  10705. \Exp &::=& \cdots\\
  10706. &\MID& \key{collect}(\itm{int})
  10707. \MID \key{allocate}(\itm{int},\itm{type})
  10708. \MID \key{global\_value}(\itm{name}) \\
  10709. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10710. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10711. \end{array}
  10712. \]
  10713. \fi}
  10714. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10715. make sure that there are $n$ bytes ready to be allocated. During
  10716. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10717. the \code{collect} function in \code{runtime.c}.
  10718. %
  10719. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10720. space at the front for the 64 bit tag), but the elements are not
  10721. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10722. of the tuple:
  10723. %
  10724. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10725. %
  10726. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10727. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10728. as \code{free\_ptr}.
  10729. %
  10730. \python{The \code{begin} form is an expression that executes a
  10731. sequence of statements and then produces the value of the expression
  10732. at the end.}
  10733. The following shows the transformation of tuple creation into 1) a
  10734. sequence of temporary variables bindings for the initializing
  10735. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10736. \code{allocate}, and 4) the initialization of the tuple. The
  10737. \itm{len} placeholder refers to the length of the tuple and
  10738. \itm{bytes} is how many total bytes need to be allocated for the
  10739. tuple, which is 8 for the tag plus \itm{len} times 8.
  10740. %
  10741. \python{The \itm{type} needed for the second argument of the
  10742. \code{allocate} form can be obtained from the \code{has\_type} field
  10743. of the tuple AST node, which is stored there by running the type
  10744. checker for \LangVec{} immediately before this pass.}
  10745. %
  10746. \begin{center}
  10747. \begin{minipage}{\textwidth}
  10748. {\if\edition\racketEd
  10749. \begin{lstlisting}
  10750. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10751. |$\Longrightarrow$|
  10752. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10753. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10754. (global-value fromspace_end))
  10755. (void)
  10756. (collect |\itm{bytes}|))])
  10757. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10758. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10759. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10760. |$v$|) ... )))) ...)
  10761. \end{lstlisting}
  10762. \fi}
  10763. {\if\edition\pythonEd
  10764. \begin{lstlisting}
  10765. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10766. |$\Longrightarrow$|
  10767. begin:
  10768. |$x_0$| = |$e_0$|
  10769. |$\vdots$|
  10770. |$x_{n-1}$| = |$e_{n-1}$|
  10771. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10772. 0
  10773. else:
  10774. collect(|\itm{bytes}|)
  10775. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10776. |$v$|[0] = |$x_0$|
  10777. |$\vdots$|
  10778. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10779. |$v$|
  10780. \end{lstlisting}
  10781. \fi}
  10782. \end{minipage}
  10783. \end{center}
  10784. %
  10785. \noindent The sequencing of the initializing expressions
  10786. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10787. they may trigger garbage collection and we cannot have an allocated
  10788. but uninitialized tuple on the heap during a collection.
  10789. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10790. \code{expose\_allocation} pass on our running example.
  10791. \begin{figure}[tbp]
  10792. % tests/s2_17.rkt
  10793. {\if\edition\racketEd
  10794. \begin{lstlisting}
  10795. (vector-ref
  10796. (vector-ref
  10797. (let ([vecinit7976
  10798. (let ([vecinit7972 42])
  10799. (let ([collectret7974
  10800. (if (< (+ (global-value free_ptr) 16)
  10801. (global-value fromspace_end))
  10802. (void)
  10803. (collect 16)
  10804. )])
  10805. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10806. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10807. alloc7971))))])
  10808. (let ([collectret7978
  10809. (if (< (+ (global-value free_ptr) 16)
  10810. (global-value fromspace_end))
  10811. (void)
  10812. (collect 16)
  10813. )])
  10814. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10815. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10816. alloc7975))))
  10817. 0)
  10818. 0)
  10819. \end{lstlisting}
  10820. \fi}
  10821. {\if\edition\pythonEd
  10822. \begin{lstlisting}
  10823. print( |$T_1$|[0][0] )
  10824. \end{lstlisting}
  10825. where $T_1$ is
  10826. \begin{lstlisting}
  10827. begin:
  10828. tmp.1 = |$T_2$|
  10829. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10830. 0
  10831. else:
  10832. collect(16)
  10833. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10834. tmp.2[0] = tmp.1
  10835. tmp.2
  10836. \end{lstlisting}
  10837. and $T_2$ is
  10838. \begin{lstlisting}
  10839. begin:
  10840. tmp.3 = 42
  10841. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10842. 0
  10843. else:
  10844. collect(16)
  10845. tmp.4 = allocate(1, TupleType([int]))
  10846. tmp.4[0] = tmp.3
  10847. tmp.4
  10848. \end{lstlisting}
  10849. \fi}
  10850. \caption{Output of the \code{expose\_allocation} pass.}
  10851. \label{fig:expose-alloc-output}
  10852. \end{figure}
  10853. \section{Remove Complex Operands}
  10854. \label{sec:remove-complex-opera-Lvec}
  10855. {\if\edition\racketEd
  10856. %
  10857. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10858. should be treated as complex operands.
  10859. %
  10860. \fi}
  10861. %
  10862. {\if\edition\pythonEd
  10863. %
  10864. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10865. and tuple access should be treated as complex operands. The
  10866. sub-expressions of tuple access must be atomic.
  10867. %
  10868. \fi}
  10869. %% A new case for
  10870. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10871. %% handled carefully to prevent the \code{Prim} node from being separated
  10872. %% from its enclosing \code{HasType}.
  10873. Figure~\ref{fig:Lvec-anf-syntax}
  10874. shows the grammar for the output language \LangAllocANF{} of this
  10875. pass, which is \LangAlloc{} in monadic normal form.
  10876. \newcommand{\LtupMonadASTPython}{
  10877. \begin{array}{rcl}
  10878. \Exp &::=& \GET{\Atm}{\Atm} \\
  10879. &\MID& \LEN{\Atm}\\
  10880. &\MID& \ALLOCATE{\Int}{\Type}
  10881. \MID \GLOBALVALUE{\Var} \\
  10882. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10883. &\MID& \COLLECT{\Int}
  10884. \end{array}
  10885. }
  10886. \begin{figure}[tp]
  10887. \centering
  10888. \fbox{
  10889. \begin{minipage}{0.96\textwidth}
  10890. \small
  10891. {\if\edition\racketEd
  10892. \[
  10893. \begin{array}{rcl}
  10894. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10895. \MID \VOID{} } \\
  10896. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10897. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10898. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10899. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10900. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10901. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10902. \MID \GLOBALVALUE{\Var}\\
  10903. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10904. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10905. \end{array}
  10906. \]
  10907. \fi}
  10908. {\if\edition\pythonEd
  10909. \[
  10910. \begin{array}{l}
  10911. \gray{\LvarMonadASTPython} \\ \hline
  10912. \gray{\LifMonadASTPython} \\ \hline
  10913. \gray{\LwhileMonadASTPython} \\ \hline
  10914. \LtupMonadASTPython \\
  10915. \begin{array}{rcl}
  10916. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10917. \end{array}
  10918. \end{array}
  10919. %% \begin{array}{lcl}
  10920. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10921. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10922. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10923. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10924. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  10925. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10926. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  10927. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10928. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  10929. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  10930. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  10931. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10932. %% &\MID& \GET{\Atm}{\Atm} \\
  10933. %% &\MID& \LEN{\Exp}\\
  10934. %% &\MID& \ALLOCATE{\Int}{\Type}
  10935. %% \MID \GLOBALVALUE{\Var}\RP\\
  10936. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  10937. %% % why have \LET?
  10938. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10939. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10940. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10941. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10942. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10943. %% \MID \COLLECT{\Int} \\
  10944. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10945. %% \end{array}
  10946. \]
  10947. \fi}
  10948. \end{minipage}
  10949. }
  10950. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  10951. \label{fig:Lvec-anf-syntax}
  10952. \end{figure}
  10953. \section{Explicate Control and the \LangCVec{} language}
  10954. \label{sec:explicate-control-r3}
  10955. \newcommand{\CtupASTRacket}{
  10956. \begin{array}{lcl}
  10957. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  10958. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  10959. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10960. &\MID& \VECLEN{\Atm} \\
  10961. &\MID& \GLOBALVALUE{\Var} \\
  10962. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  10963. &\MID& \LP\key{Collect} \,\itm{int}\RP
  10964. \end{array}
  10965. }
  10966. \newcommand{\CtupASTPython}{
  10967. \begin{array}{lcl}
  10968. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  10969. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  10970. \Stmt &::=& \COLLECT{\Int} \\
  10971. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  10972. \end{array}
  10973. }
  10974. \begin{figure}[tp]
  10975. \fbox{
  10976. \begin{minipage}{0.96\textwidth}
  10977. \small
  10978. {\if\edition\racketEd
  10979. \[
  10980. \begin{array}{l}
  10981. \gray{\CvarASTRacket} \\ \hline
  10982. \gray{\CifASTRacket} \\ \hline
  10983. \gray{\CloopASTRacket} \\ \hline
  10984. \CtupASTRacket \\
  10985. \begin{array}{lcl}
  10986. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10987. \end{array}
  10988. \end{array}
  10989. \]
  10990. \fi}
  10991. {\if\edition\pythonEd
  10992. \[
  10993. \begin{array}{l}
  10994. \gray{\CifASTPython} \\ \hline
  10995. \CtupASTPython \\
  10996. \begin{array}{lcl}
  10997. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  10998. \end{array}
  10999. \end{array}
  11000. \]
  11001. \fi}
  11002. \end{minipage}
  11003. }
  11004. \caption{The abstract syntax of \LangCVec{}, extending
  11005. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11006. (Figure~\ref{fig:c1-syntax})}.}
  11007. \label{fig:c2-syntax}
  11008. \end{figure}
  11009. The output of \code{explicate\_control} is a program in the
  11010. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11011. Figure~\ref{fig:c2-syntax}.
  11012. %
  11013. \racket{(The concrete syntax is defined in
  11014. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11015. %
  11016. The new expressions of \LangCVec{} include \key{allocate},
  11017. %
  11018. \racket{\key{vector-ref}, and \key{vector-set!},}
  11019. %
  11020. \python{accessing tuple elements,}
  11021. %
  11022. and \key{global\_value}.
  11023. %
  11024. \python{\LangCVec{} also includes the \code{collect} statement and
  11025. assignment to a tuple element.}
  11026. %
  11027. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11028. %
  11029. The \code{explicate\_control} pass can treat these new forms much like
  11030. the other forms that we've already encoutered.
  11031. \section{Select Instructions and the \LangXGlobal{} Language}
  11032. \label{sec:select-instructions-gc}
  11033. \index{subject}{instruction selection}
  11034. %% void (rep as zero)
  11035. %% allocate
  11036. %% collect (callq collect)
  11037. %% vector-ref
  11038. %% vector-set!
  11039. %% vector-length
  11040. %% global (postpone)
  11041. In this pass we generate x86 code for most of the new operations that
  11042. were needed to compile tuples, including \code{Allocate},
  11043. \code{Collect}, and accessing tuple elements.
  11044. %
  11045. We compile \code{GlobalValue} to \code{Global} because the later has a
  11046. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11047. \ref{fig:x86-2}). \index{subject}{x86}
  11048. The tuple read and write forms translate into \code{movq}
  11049. instructions. (The plus one in the offset is to get past the tag at
  11050. the beginning of the tuple representation.)
  11051. %
  11052. \begin{center}
  11053. \begin{minipage}{\textwidth}
  11054. {\if\edition\racketEd
  11055. \begin{lstlisting}
  11056. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11057. |$\Longrightarrow$|
  11058. movq |$\itm{tup}'$|, %r11
  11059. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11060. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11061. |$\Longrightarrow$|
  11062. movq |$\itm{tup}'$|, %r11
  11063. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11064. movq $0, |$\itm{lhs'}$|
  11065. \end{lstlisting}
  11066. \fi}
  11067. {\if\edition\pythonEd
  11068. \begin{lstlisting}
  11069. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11070. |$\Longrightarrow$|
  11071. movq |$\itm{tup}'$|, %r11
  11072. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11073. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11074. |$\Longrightarrow$|
  11075. movq |$\itm{tup}'$|, %r11
  11076. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11077. \end{lstlisting}
  11078. \fi}
  11079. \end{minipage}
  11080. \end{center}
  11081. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11082. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11083. are obtained by translating from \LangCVec{} to x86.
  11084. %
  11085. The move of $\itm{tup}'$ to
  11086. register \code{r11} ensures that offset expression
  11087. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11088. removing \code{r11} from consideration by the register allocating.
  11089. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11090. \code{rax}. Then the generated code for tuple assignment would be
  11091. \begin{lstlisting}
  11092. movq |$\itm{tup}'$|, %rax
  11093. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11094. \end{lstlisting}
  11095. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11096. \code{patch\_instructions} would insert a move through \code{rax}
  11097. as follows.
  11098. \begin{lstlisting}
  11099. movq |$\itm{tup}'$|, %rax
  11100. movq |$\itm{rhs}'$|, %rax
  11101. movq %rax, |$8(n+1)$|(%rax)
  11102. \end{lstlisting}
  11103. But the above sequence of instructions does not work because we're
  11104. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11105. $\itm{rhs}'$) at the same time!
  11106. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11107. be translated into a sequence of instructions that read the tag of the
  11108. tuple and extract the six bits that represent the tuple length, which
  11109. are the bits starting at index 1 and going up to and including bit 6.
  11110. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11111. (shift right) can be used to accomplish this.
  11112. We compile the \code{allocate} form to operations on the
  11113. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11114. allocation} as it implements allocation by bumping the allocation
  11115. pointer. It is much more efficient than calling a function for each
  11116. allocation. The address in the \code{free\_ptr}
  11117. is the next free address in the FromSpace, so we copy it into
  11118. \code{r11} and then move it forward by enough space for the tuple
  11119. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  11120. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11121. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11122. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11123. tag is organized.
  11124. %
  11125. \racket{We recommend using the Racket operations
  11126. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11127. during compilation.}
  11128. %
  11129. \python{We recommend using the bitwise-or operator \code{|} and the
  11130. shift-left operator \code{<<} to compute the tag during
  11131. compilation.}
  11132. %
  11133. The type annotation in the \code{allocate} form is used to determine
  11134. the pointer mask region of the tag.
  11135. %
  11136. Do not worry about the addressing mode \verb!free_ptr(%rip)!. It
  11137. essentially stands for the address \code{free\_ptr}, but uses a
  11138. special instruction-pointer relative addressing mode of the x86-64
  11139. processor.
  11140. %
  11141. {\if\edition\racketEd
  11142. \begin{lstlisting}
  11143. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11144. |$\Longrightarrow$|
  11145. movq free_ptr(%rip), %r11
  11146. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11147. movq $|$\itm{tag}$|, 0(%r11)
  11148. movq %r11, |$\itm{lhs}'$|
  11149. \end{lstlisting}
  11150. \fi}
  11151. {\if\edition\pythonEd
  11152. \begin{lstlisting}
  11153. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11154. |$\Longrightarrow$|
  11155. movq free_ptr(%rip), %r11
  11156. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11157. movq $|$\itm{tag}$|, 0(%r11)
  11158. movq %r11, |$\itm{lhs}'$|
  11159. \end{lstlisting}
  11160. \fi}
  11161. The \code{collect} form is compiled to a call to the \code{collect}
  11162. function in the runtime. The arguments to \code{collect} are 1) the
  11163. top of the root stack and 2) the number of bytes that need to be
  11164. allocated. We use another dedicated register, \code{r15}, to
  11165. store the pointer to the top of the root stack. So \code{r15} is not
  11166. available for use by the register allocator.
  11167. {\if\edition\racketEd
  11168. \begin{lstlisting}
  11169. (collect |$\itm{bytes}$|)
  11170. |$\Longrightarrow$|
  11171. movq %r15, %rdi
  11172. movq $|\itm{bytes}|, %rsi
  11173. callq collect
  11174. \end{lstlisting}
  11175. \fi}
  11176. {\if\edition\pythonEd
  11177. \begin{lstlisting}
  11178. collect(|$\itm{bytes}$|)
  11179. |$\Longrightarrow$|
  11180. movq %r15, %rdi
  11181. movq $|\itm{bytes}|, %rsi
  11182. callq collect
  11183. \end{lstlisting}
  11184. \fi}
  11185. \begin{figure}[tp]
  11186. \fbox{
  11187. \begin{minipage}{0.96\textwidth}
  11188. \[
  11189. \begin{array}{lcl}
  11190. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11191. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11192. & & \gray{ \key{main:} \; \Instr^{*} }
  11193. \end{array}
  11194. \]
  11195. \end{minipage}
  11196. }
  11197. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11198. \label{fig:x86-2-concrete}
  11199. \end{figure}
  11200. \begin{figure}[tp]
  11201. \fbox{
  11202. \begin{minipage}{0.96\textwidth}
  11203. \small
  11204. \[
  11205. \begin{array}{lcl}
  11206. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11207. \MID \BYTEREG{\Reg}} \\
  11208. &\MID& \GLOBAL{\Var} \\
  11209. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11210. \end{array}
  11211. \]
  11212. \end{minipage}
  11213. }
  11214. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11215. \label{fig:x86-2}
  11216. \end{figure}
  11217. The concrete and abstract syntax of the \LangXGlobal{} language is
  11218. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11219. differs from \LangXIf{} just in the addition of global variables.
  11220. %
  11221. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11222. \code{select\_instructions} pass on the running example.
  11223. \begin{figure}[tbp]
  11224. \centering
  11225. % tests/s2_17.rkt
  11226. \begin{minipage}[t]{0.5\textwidth}
  11227. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11228. block35:
  11229. movq free_ptr(%rip), alloc9024
  11230. addq $16, free_ptr(%rip)
  11231. movq alloc9024, %r11
  11232. movq $131, 0(%r11)
  11233. movq alloc9024, %r11
  11234. movq vecinit9025, 8(%r11)
  11235. movq $0, initret9026
  11236. movq alloc9024, %r11
  11237. movq 8(%r11), tmp9034
  11238. movq tmp9034, %r11
  11239. movq 8(%r11), %rax
  11240. jmp conclusion
  11241. block36:
  11242. movq $0, collectret9027
  11243. jmp block35
  11244. block38:
  11245. movq free_ptr(%rip), alloc9020
  11246. addq $16, free_ptr(%rip)
  11247. movq alloc9020, %r11
  11248. movq $3, 0(%r11)
  11249. movq alloc9020, %r11
  11250. movq vecinit9021, 8(%r11)
  11251. movq $0, initret9022
  11252. movq alloc9020, vecinit9025
  11253. movq free_ptr(%rip), tmp9031
  11254. movq tmp9031, tmp9032
  11255. addq $16, tmp9032
  11256. movq fromspace_end(%rip), tmp9033
  11257. cmpq tmp9033, tmp9032
  11258. jl block36
  11259. jmp block37
  11260. block37:
  11261. movq %r15, %rdi
  11262. movq $16, %rsi
  11263. callq 'collect
  11264. jmp block35
  11265. block39:
  11266. movq $0, collectret9023
  11267. jmp block38
  11268. \end{lstlisting}
  11269. \end{minipage}
  11270. \begin{minipage}[t]{0.45\textwidth}
  11271. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11272. start:
  11273. movq $42, vecinit9021
  11274. movq free_ptr(%rip), tmp9028
  11275. movq tmp9028, tmp9029
  11276. addq $16, tmp9029
  11277. movq fromspace_end(%rip), tmp9030
  11278. cmpq tmp9030, tmp9029
  11279. jl block39
  11280. jmp block40
  11281. block40:
  11282. movq %r15, %rdi
  11283. movq $16, %rsi
  11284. callq 'collect
  11285. jmp block38
  11286. \end{lstlisting}
  11287. \end{minipage}
  11288. \caption{Output of the \code{select\_instructions} pass.}
  11289. \label{fig:select-instr-output-gc}
  11290. \end{figure}
  11291. \clearpage
  11292. \section{Register Allocation}
  11293. \label{sec:reg-alloc-gc}
  11294. \index{subject}{register allocation}
  11295. As discussed earlier in this chapter, the garbage collector needs to
  11296. access all the pointers in the root set, that is, all variables that
  11297. are tuples. It will be the responsibility of the register allocator
  11298. to make sure that:
  11299. \begin{enumerate}
  11300. \item the root stack is used for spilling tuple-typed variables, and
  11301. \item if a tuple-typed variable is live during a call to the
  11302. collector, it must be spilled to ensure it is visible to the
  11303. collector.
  11304. \end{enumerate}
  11305. The later responsibility can be handled during construction of the
  11306. interference graph, by adding interference edges between the call-live
  11307. tuple-typed variables and all the callee-saved registers. (They
  11308. already interfere with the caller-saved registers.)
  11309. %
  11310. \racket{The type information for variables is in the \code{Program}
  11311. form, so we recommend adding another parameter to the
  11312. \code{build\_interference} function to communicate this alist.}
  11313. %
  11314. \python{The type information for variables is generated by the type
  11315. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11316. the \code{CProgram} AST mode. You'll need to propagate that
  11317. information so that it is available in this pass.}
  11318. The spilling of tuple-typed variables to the root stack can be handled
  11319. after graph coloring, when choosing how to assign the colors
  11320. (integers) to registers and stack locations. The
  11321. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11322. changes to also record the number of spills to the root stack.
  11323. % build-interference
  11324. %
  11325. % callq
  11326. % extra parameter for var->type assoc. list
  11327. % update 'program' and 'if'
  11328. % allocate-registers
  11329. % allocate spilled vectors to the rootstack
  11330. % don't change color-graph
  11331. % TODO:
  11332. %\section{Patch Instructions}
  11333. %[mention that global variables are memory references]
  11334. \section{Prelude and Conclusion}
  11335. \label{sec:print-x86-gc}
  11336. \label{sec:prelude-conclusion-x86-gc}
  11337. \index{subject}{prelude}\index{subject}{conclusion}
  11338. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11339. \code{prelude\_and\_conclusion} pass on the running example. In the
  11340. prelude and conclusion of the \code{main} function, we allocate space
  11341. on the root stack to make room for the spills of tuple-typed
  11342. variables. We do so by bumping the root stack
  11343. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11344. example, there was just one spill so we increment \code{r15} by 8
  11345. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11346. One issue that deserves special care is that there may be a call to
  11347. \code{collect} prior to the initializing assignments for all the
  11348. variables in the root stack. We do not want the garbage collector to
  11349. accidentally think that some uninitialized variable is a pointer that
  11350. needs to be followed. Thus, we zero-out all locations on the root
  11351. stack in the prelude of \code{main}. In
  11352. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11353. %
  11354. \lstinline{movq $0, 0(%r15)}
  11355. %
  11356. is sufficient to accomplish this task because there is only one spill.
  11357. In general, we have to clear as many words as there are spills of
  11358. tuple-typed variables. The garbage collector tests each root to see
  11359. if it is null prior to dereferencing it.
  11360. \begin{figure}[htbp]
  11361. % TODO: Python Version -Jeremy
  11362. \begin{minipage}[t]{0.5\textwidth}
  11363. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11364. block35:
  11365. movq free_ptr(%rip), %rcx
  11366. addq $16, free_ptr(%rip)
  11367. movq %rcx, %r11
  11368. movq $131, 0(%r11)
  11369. movq %rcx, %r11
  11370. movq -8(%r15), %rax
  11371. movq %rax, 8(%r11)
  11372. movq $0, %rdx
  11373. movq %rcx, %r11
  11374. movq 8(%r11), %rcx
  11375. movq %rcx, %r11
  11376. movq 8(%r11), %rax
  11377. jmp conclusion
  11378. block36:
  11379. movq $0, %rcx
  11380. jmp block35
  11381. block38:
  11382. movq free_ptr(%rip), %rcx
  11383. addq $16, free_ptr(%rip)
  11384. movq %rcx, %r11
  11385. movq $3, 0(%r11)
  11386. movq %rcx, %r11
  11387. movq %rbx, 8(%r11)
  11388. movq $0, %rdx
  11389. movq %rcx, -8(%r15)
  11390. movq free_ptr(%rip), %rcx
  11391. addq $16, %rcx
  11392. movq fromspace_end(%rip), %rdx
  11393. cmpq %rdx, %rcx
  11394. jl block36
  11395. movq %r15, %rdi
  11396. movq $16, %rsi
  11397. callq collect
  11398. jmp block35
  11399. block39:
  11400. movq $0, %rcx
  11401. jmp block38
  11402. \end{lstlisting}
  11403. \end{minipage}
  11404. \begin{minipage}[t]{0.45\textwidth}
  11405. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11406. start:
  11407. movq $42, %rbx
  11408. movq free_ptr(%rip), %rdx
  11409. addq $16, %rdx
  11410. movq fromspace_end(%rip), %rcx
  11411. cmpq %rcx, %rdx
  11412. jl block39
  11413. movq %r15, %rdi
  11414. movq $16, %rsi
  11415. callq collect
  11416. jmp block38
  11417. .globl main
  11418. main:
  11419. pushq %rbp
  11420. movq %rsp, %rbp
  11421. pushq %r13
  11422. pushq %r12
  11423. pushq %rbx
  11424. pushq %r14
  11425. subq $0, %rsp
  11426. movq $16384, %rdi
  11427. movq $16384, %rsi
  11428. callq initialize
  11429. movq rootstack_begin(%rip), %r15
  11430. movq $0, 0(%r15)
  11431. addq $8, %r15
  11432. jmp start
  11433. conclusion:
  11434. subq $8, %r15
  11435. addq $0, %rsp
  11436. popq %r14
  11437. popq %rbx
  11438. popq %r12
  11439. popq %r13
  11440. popq %rbp
  11441. retq
  11442. \end{lstlisting}
  11443. \end{minipage}
  11444. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11445. \label{fig:print-x86-output-gc}
  11446. \end{figure}
  11447. \begin{figure}[tbp]
  11448. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11449. \node (Lvec) at (0,2) {\large \LangVec{}};
  11450. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11451. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11452. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11453. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11454. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11455. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11456. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11457. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11458. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11459. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11460. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11461. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11462. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11463. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11464. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11465. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11466. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11467. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11468. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11469. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11470. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11471. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11472. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11473. \end{tikzpicture}
  11474. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11475. \label{fig:Lvec-passes}
  11476. \end{figure}
  11477. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11478. for the compilation of \LangVec{}.
  11479. \clearpage
  11480. {\if\edition\racketEd
  11481. \section{Challenge: Simple Structures}
  11482. \label{sec:simple-structures}
  11483. \index{subject}{struct}
  11484. \index{subject}{structure}
  11485. The language \LangStruct{} extends \LangVec{} with support for simple
  11486. structures. Its concrete syntax is defined in
  11487. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11488. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11489. Racket is a user-defined data type that contains named fields and that
  11490. is heap allocated, similar to a vector. The following is an example of
  11491. a structure definition, in this case the definition of a \code{point}
  11492. type.
  11493. \begin{lstlisting}
  11494. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11495. \end{lstlisting}
  11496. \newcommand{\LstructGrammarRacket}{
  11497. \begin{array}{lcl}
  11498. \Type &::=& \Var \\
  11499. \Exp &::=& (\Var\;\Exp \ldots)\\
  11500. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11501. \end{array}
  11502. }
  11503. \newcommand{\LstructASTRacket}{
  11504. \begin{array}{lcl}
  11505. \Type &::=& \VAR{\Var} \\
  11506. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11507. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11508. \end{array}
  11509. }
  11510. \begin{figure}[tbp]
  11511. \centering
  11512. \fbox{
  11513. \begin{minipage}{0.96\textwidth}
  11514. \[
  11515. \begin{array}{l}
  11516. \gray{\LintGrammarRacket{}} \\ \hline
  11517. \gray{\LvarGrammarRacket{}} \\ \hline
  11518. \gray{\LifGrammarRacket{}} \\ \hline
  11519. \gray{\LwhileGrammarRacket} \\ \hline
  11520. \gray{\LtupGrammarRacket} \\ \hline
  11521. \LstructGrammarRacket \\
  11522. \begin{array}{lcl}
  11523. \LangStruct{} &::=& \Def \ldots \; \Exp
  11524. \end{array}
  11525. \end{array}
  11526. \]
  11527. \end{minipage}
  11528. }
  11529. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11530. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11531. \label{fig:Lstruct-concrete-syntax}
  11532. \end{figure}
  11533. \begin{figure}[tbp]
  11534. \centering
  11535. \fbox{
  11536. \begin{minipage}{0.96\textwidth}
  11537. \[
  11538. \begin{array}{l}
  11539. \gray{\LintASTRacket{}} \\ \hline
  11540. \gray{\LvarASTRacket{}} \\ \hline
  11541. \gray{\LifASTRacket{}} \\ \hline
  11542. \gray{\LwhileASTRacket} \\ \hline
  11543. \gray{\LtupASTRacket} \\ \hline
  11544. \LstructASTRacket \\
  11545. \begin{array}{lcl}
  11546. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11547. \end{array}
  11548. \end{array}
  11549. \]
  11550. \end{minipage}
  11551. }
  11552. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11553. (Figure~\ref{fig:Lvec-syntax}).}
  11554. \label{fig:Lstruct-syntax}
  11555. \end{figure}
  11556. An instance of a structure is created using function call syntax, with
  11557. the name of the structure in the function position:
  11558. \begin{lstlisting}
  11559. (point 7 12)
  11560. \end{lstlisting}
  11561. Function-call syntax is also used to read the value in a field of a
  11562. structure. The function name is formed by the structure name, a dash,
  11563. and the field name. The following example uses \code{point-x} and
  11564. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11565. instances.
  11566. \begin{center}
  11567. \begin{lstlisting}
  11568. (let ([pt1 (point 7 12)])
  11569. (let ([pt2 (point 4 3)])
  11570. (+ (- (point-x pt1) (point-x pt2))
  11571. (- (point-y pt1) (point-y pt2)))))
  11572. \end{lstlisting}
  11573. \end{center}
  11574. Similarly, to write to a field of a structure, use its set function,
  11575. whose name starts with \code{set-}, followed by the structure name,
  11576. then a dash, then the field name, and concluded with an exclamation
  11577. mark. The following example uses \code{set-point-x!} to change the
  11578. \code{x} field from \code{7} to \code{42}.
  11579. \begin{center}
  11580. \begin{lstlisting}
  11581. (let ([pt (point 7 12)])
  11582. (let ([_ (set-point-x! pt 42)])
  11583. (point-x pt)))
  11584. \end{lstlisting}
  11585. \end{center}
  11586. \begin{exercise}\normalfont
  11587. Create a type checker for \LangStruct{} by extending the type
  11588. checker for \LangVec{}. Extend your compiler with support for simple
  11589. structures, compiling \LangStruct{} to x86 assembly code. Create
  11590. five new test cases that use structures and test your compiler.
  11591. \end{exercise}
  11592. % TODO: create an interpreter for L_struct
  11593. \clearpage
  11594. \section{Challenge: Arrays}
  11595. \label{sec:arrays}
  11596. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11597. elements whose length is determined at compile-time and where each
  11598. element of a tuple may have a different type (they are
  11599. heterogeous). This challenge is also about sequences, but this time
  11600. the length is determined at run-time and all the elements have the same
  11601. type (they are homogeneous). We use the term ``array'' for this later
  11602. kind of sequence.
  11603. The Racket language does not distinguish between tuples and arrays,
  11604. they are both represented by vectors. However, Typed Racket
  11605. distinguishes between tuples and arrays: the \code{Vector} type is for
  11606. tuples and the \code{Vectorof} type is for arrays.
  11607. %
  11608. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11609. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11610. and the \code{make-vector} primitive operator for creating an array,
  11611. whose arguments are the length of the array and an initial value for
  11612. all the elements in the array. The \code{vector-length},
  11613. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11614. for tuples become overloaded for use with arrays.
  11615. %
  11616. We also include integer multiplication in \LangArray{}, as it is
  11617. useful in many examples involving arrays such as computing the
  11618. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11619. \begin{figure}[tp]
  11620. \centering
  11621. \fbox{
  11622. \begin{minipage}{0.96\textwidth}
  11623. \small
  11624. {\if\edition\racketEd
  11625. \[
  11626. \begin{array}{lcl}
  11627. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11628. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11629. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11630. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11631. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11632. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11633. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11634. \MID \LP\key{not}\;\Exp\RP } \\
  11635. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11636. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11637. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11638. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11639. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11640. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11641. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11642. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11643. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11644. \MID \CWHILE{\Exp}{\Exp} } \\
  11645. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11646. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11647. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11648. \end{array}
  11649. \]
  11650. \fi}
  11651. {\if\edition\pythonEd
  11652. UNDER CONSTRUCTION
  11653. \fi}
  11654. \end{minipage}
  11655. }
  11656. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11657. \label{fig:Lvecof-concrete-syntax}
  11658. \end{figure}
  11659. \begin{figure}[tp]
  11660. \begin{lstlisting}
  11661. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11662. [n : Integer]) : Integer
  11663. (let ([i 0])
  11664. (let ([prod 0])
  11665. (begin
  11666. (while (< i n)
  11667. (begin
  11668. (set! prod (+ prod (* (vector-ref A i)
  11669. (vector-ref B i))))
  11670. (set! i (+ i 1))
  11671. ))
  11672. prod))))
  11673. (let ([A (make-vector 2 2)])
  11674. (let ([B (make-vector 2 3)])
  11675. (+ (inner-product A B 2)
  11676. 30)))
  11677. \end{lstlisting}
  11678. \caption{Example program that computes the inner-product.}
  11679. \label{fig:inner-product}
  11680. \end{figure}
  11681. The type checker for \LangArray{} is define in
  11682. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11683. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11684. of the intializing expression. The length expression is required to
  11685. have type \code{Integer}. The type checking of the operators
  11686. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11687. updated to handle the situation where the vector has type
  11688. \code{Vectorof}. In these cases we translate the operators to their
  11689. \code{vectorof} form so that later passes can easily distinguish
  11690. between operations on tuples versus arrays. We override the
  11691. \code{operator-types} method to provide the type signature for
  11692. multiplication: it takes two integers and returns an integer. To
  11693. support injection and projection of arrays to the \code{Any} type
  11694. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11695. predicate.
  11696. \begin{figure}[tbp]
  11697. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11698. (define type-check-Lvecof_class
  11699. (class type-check-Rwhile_class
  11700. (super-new)
  11701. (inherit check-type-equal?)
  11702. (define/override (flat-ty? ty)
  11703. (match ty
  11704. ['(Vectorof Any) #t]
  11705. [else (super flat-ty? ty)]))
  11706. (define/override (operator-types)
  11707. (append '((* . ((Integer Integer) . Integer)))
  11708. (super operator-types)))
  11709. (define/override (type-check-exp env)
  11710. (lambda (e)
  11711. (define recur (type-check-exp env))
  11712. (match e
  11713. [(Prim 'make-vector (list e1 e2))
  11714. (define-values (e1^ t1) (recur e1))
  11715. (define-values (e2^ elt-type) (recur e2))
  11716. (define vec-type `(Vectorof ,elt-type))
  11717. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11718. vec-type)]
  11719. [(Prim 'vector-ref (list e1 e2))
  11720. (define-values (e1^ t1) (recur e1))
  11721. (define-values (e2^ t2) (recur e2))
  11722. (match* (t1 t2)
  11723. [(`(Vectorof ,elt-type) 'Integer)
  11724. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11725. [(other wise) ((super type-check-exp env) e)])]
  11726. [(Prim 'vector-set! (list e1 e2 e3) )
  11727. (define-values (e-vec t-vec) (recur e1))
  11728. (define-values (e2^ t2) (recur e2))
  11729. (define-values (e-arg^ t-arg) (recur e3))
  11730. (match t-vec
  11731. [`(Vectorof ,elt-type)
  11732. (check-type-equal? elt-type t-arg e)
  11733. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11734. [else ((super type-check-exp env) e)])]
  11735. [(Prim 'vector-length (list e1))
  11736. (define-values (e1^ t1) (recur e1))
  11737. (match t1
  11738. [`(Vectorof ,t)
  11739. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11740. [else ((super type-check-exp env) e)])]
  11741. [else ((super type-check-exp env) e)])))
  11742. ))
  11743. (define (type-check-Lvecof p)
  11744. (send (new type-check-Lvecof_class) type-check-program p))
  11745. \end{lstlisting}
  11746. \caption{Type checker for the \LangArray{} language.}
  11747. \label{fig:type-check-Lvecof}
  11748. \end{figure}
  11749. The interpreter for \LangArray{} is defined in
  11750. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11751. implemented with Racket's \code{make-vector} function and
  11752. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11753. integers.
  11754. \begin{figure}[tbp]
  11755. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11756. (define interp-Lvecof_class
  11757. (class interp-Rwhile_class
  11758. (super-new)
  11759. (define/override (interp-op op)
  11760. (verbose "Lvecof/interp-op" op)
  11761. (match op
  11762. ['make-vector make-vector]
  11763. ['* fx*]
  11764. [else (super interp-op op)]))
  11765. ))
  11766. (define (interp-Lvecof p)
  11767. (send (new interp-Lvecof_class) interp-program p))
  11768. \end{lstlisting}
  11769. \caption{Interpreter for \LangArray{}.}
  11770. \label{fig:interp-Lvecof}
  11771. \end{figure}
  11772. \subsection{Data Representation}
  11773. \label{sec:array-rep}
  11774. Just like tuples, we store arrays on the heap which means that the
  11775. garbage collector will need to inspect arrays. An immediate thought is
  11776. to use the same representation for arrays that we use for tuples.
  11777. However, we limit tuples to a length of $50$ so that their length and
  11778. pointer mask can fit into the 64-bit tag at the beginning of each
  11779. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11780. millions of elements, so we need more bits to store the length.
  11781. However, because arrays are homogeneous, we only need $1$ bit for the
  11782. pointer mask instead of one bit per array elements. Finally, the
  11783. garbage collector will need to be able to distinguish between tuples
  11784. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11785. arrive at the following layout for the 64-bit tag at the beginning of
  11786. an array:
  11787. \begin{itemize}
  11788. \item The right-most bit is the forwarding bit, just like in a tuple.
  11789. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11790. it is not.
  11791. \item The next bit to the left is the pointer mask. A $0$ indicates
  11792. that none of the elements are pointers to the heap and a $1$
  11793. indicates that all of the elements are pointers.
  11794. \item The next $61$ bits store the length of the array.
  11795. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11796. array ($1$).
  11797. \end{itemize}
  11798. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11799. differentiate the kinds of values that have been injected into the
  11800. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11801. to indicate that the value is an array.
  11802. In the following subsections we provide hints regarding how to update
  11803. the passes to handle arrays.
  11804. \subsection{Reveal Casts}
  11805. The array-access operators \code{vectorof-ref} and
  11806. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11807. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11808. that the type checker cannot tell whether the index will be in bounds,
  11809. so the bounds check must be performed at run time. Recall that the
  11810. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11811. an \code{If} arround a vector reference for update to check whether
  11812. the index is less than the length. You should do the same for
  11813. \code{vectorof-ref} and \code{vectorof-set!} .
  11814. In addition, the handling of the \code{any-vector} operators in
  11815. \code{reveal-casts} needs to be updated to account for arrays that are
  11816. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11817. generated code should test whether the tag is for tuples (\code{010})
  11818. or arrays (\code{110}) and then dispatch to either
  11819. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11820. we add a case in \code{select\_instructions} to generate the
  11821. appropriate instructions for accessing the array length from the
  11822. header of an array.
  11823. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11824. the generated code needs to check that the index is less than the
  11825. vector length, so like the code for \code{any-vector-length}, check
  11826. the tag to determine whether to use \code{any-vector-length} or
  11827. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11828. is complete, the generated code can use \code{any-vector-ref} and
  11829. \code{any-vector-set!} for both tuples and arrays because the
  11830. instructions used for those operators do not look at the tag at the
  11831. front of the tuple or array.
  11832. \subsection{Expose Allocation}
  11833. This pass should translate the \code{make-vector} operator into
  11834. lower-level operations. In particular, the new AST node
  11835. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11836. length specified by the $\Exp$, but does not initialize the elements
  11837. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11838. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11839. element type for the array. Regarding the initialization of the array,
  11840. we recommend generated a \code{while} loop that uses
  11841. \code{vector-set!} to put the initializing value into every element of
  11842. the array.
  11843. \subsection{Remove Complex Operands}
  11844. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11845. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11846. complex and its subexpression must be atomic.
  11847. \subsection{Explicate Control}
  11848. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11849. \code{explicate\_assign}.
  11850. \subsection{Select Instructions}
  11851. Generate instructions for \code{AllocateArray} similar to those for
  11852. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11853. that the tag at the front of the array should instead use the
  11854. representation discussed in Section~\ref{sec:array-rep}.
  11855. Regarding \code{vectorof-length}, extract the length from the tag
  11856. according to the representation discussed in
  11857. Section~\ref{sec:array-rep}.
  11858. The instructions generated for \code{vectorof-ref} differ from those
  11859. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11860. that the index is not a constant so the offset must be computed at
  11861. runtime, similar to the instructions generated for
  11862. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11863. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11864. appear in an assignment and as a stand-alone statement, so make sure
  11865. to handle both situations in this pass.
  11866. Finally, the instructions for \code{any-vectorof-length} should be
  11867. similar to those for \code{vectorof-length}, except that one must
  11868. first project the array by writing zeroes into the $3$-bit tag
  11869. \begin{exercise}\normalfont
  11870. Implement a compiler for the \LangArray{} language by extending your
  11871. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11872. programs, including the one in Figure~\ref{fig:inner-product} and also
  11873. a program that multiplies two matrices. Note that matrices are
  11874. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11875. arrays by laying out each row in the array, one after the next.
  11876. \end{exercise}
  11877. \section{Challenge: Generational Collection}
  11878. The copying collector described in Section~\ref{sec:GC} can incur
  11879. significant runtime overhead because the call to \code{collect} takes
  11880. time proportional to all of the live data. One way to reduce this
  11881. overhead is to reduce how much data is inspected in each call to
  11882. \code{collect}. In particular, researchers have observed that recently
  11883. allocated data is more likely to become garbage then data that has
  11884. survived one or more previous calls to \code{collect}. This insight
  11885. motivated the creation of \emph{generational garbage collectors}
  11886. \index{subject}{generational garbage collector} that
  11887. 1) segregates data according to its age into two or more generations,
  11888. 2) allocates less space for younger generations, so collecting them is
  11889. faster, and more space for the older generations, and 3) performs
  11890. collection on the younger generations more frequently then for older
  11891. generations~\citep{Wilson:1992fk}.
  11892. For this challenge assignment, the goal is to adapt the copying
  11893. collector implemented in \code{runtime.c} to use two generations, one
  11894. for young data and one for old data. Each generation consists of a
  11895. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11896. \code{collect} function to use the two generations.
  11897. \begin{enumerate}
  11898. \item Copy the young generation's FromSpace to its ToSpace then switch
  11899. the role of the ToSpace and FromSpace
  11900. \item If there is enough space for the requested number of bytes in
  11901. the young FromSpace, then return from \code{collect}.
  11902. \item If there is not enough space in the young FromSpace for the
  11903. requested bytes, then move the data from the young generation to the
  11904. old one with the following steps:
  11905. \begin{enumerate}
  11906. \item If there is enough room in the old FromSpace, copy the young
  11907. FromSpace to the old FromSpace and then return.
  11908. \item If there is not enough room in the old FromSpace, then collect
  11909. the old generation by copying the old FromSpace to the old ToSpace
  11910. and swap the roles of the old FromSpace and ToSpace.
  11911. \item If there is enough room now, copy the young FromSpace to the
  11912. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11913. and ToSpace for the old generation. Copy the young FromSpace and
  11914. the old FromSpace into the larger FromSpace for the old
  11915. generation and then return.
  11916. \end{enumerate}
  11917. \end{enumerate}
  11918. We recommend that you generalize the \code{cheney} function so that it
  11919. can be used for all the copies mentioned above: between the young
  11920. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11921. between the young FromSpace and old FromSpace. This can be
  11922. accomplished by adding parameters to \code{cheney} that replace its
  11923. use of the global variables \code{fromspace\_begin},
  11924. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11925. Note that the collection of the young generation does not traverse the
  11926. old generation. This introduces a potential problem: there may be
  11927. young data that is only reachable through pointers in the old
  11928. generation. If these pointers are not taken into account, the
  11929. collector could throw away young data that is live! One solution,
  11930. called \emph{pointer recording}, is to maintain a set of all the
  11931. pointers from the old generation into the new generation and consider
  11932. this set as part of the root set. To maintain this set, the compiler
  11933. must insert extra instructions around every \code{vector-set!}. If the
  11934. vector being modified is in the old generation, and if the value being
  11935. written is a pointer into the new generation, than that pointer must
  11936. be added to the set. Also, if the value being overwritten was a
  11937. pointer into the new generation, then that pointer should be removed
  11938. from the set.
  11939. \begin{exercise}\normalfont
  11940. Adapt the \code{collect} function in \code{runtime.c} to implement
  11941. generational garbage collection, as outlined in this section.
  11942. Update the code generation for \code{vector-set!} to implement
  11943. pointer recording. Make sure that your new compiler and runtime
  11944. passes your test suite.
  11945. \end{exercise}
  11946. \fi}
  11947. \section{Further Reading}
  11948. There are many alternatives to copying collectors (and their bigger
  11949. siblings, the generational collectors) when its comes to garbage
  11950. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  11951. reference counting~\citep{Collins:1960aa}. The strengths of copying
  11952. collectors are that allocation is fast (just a comparison and pointer
  11953. increment), there is no fragmentation, cyclic garbage is collected,
  11954. and the time complexity of collection only depends on the amount of
  11955. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  11956. main disadvantages of a two-space copying collector is that it uses a
  11957. lot of extra space and takes a long time to perform the copy, though
  11958. these problems are ameliorated in generational collectors.
  11959. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  11960. small objects and generate a lot of garbage, so copying and
  11961. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  11962. Garbage collection is an active research topic, especially concurrent
  11963. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  11964. developing new techniques and revisiting old
  11965. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  11966. meet every year at the International Symposium on Memory Management to
  11967. present these findings.
  11968. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11969. \chapter{Functions}
  11970. \label{ch:Lfun}
  11971. \index{subject}{function}
  11972. This chapter studies the compilation of a subset of \racket{Typed
  11973. Racket}\python{Python} in which only top-level function definitions
  11974. are allowed..
  11975. This kind of function is a realistic example as the C language imposes
  11976. similar restrictions. It is also an important stepping stone to
  11977. implementing lexically-scoped functions in the form of \key{lambda}
  11978. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  11979. \section{The \LangFun{} Language}
  11980. The concrete and abstract syntax for function definitions and function
  11981. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  11982. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  11983. \LangFun{} begin with zero or more function definitions. The function
  11984. names from these definitions are in-scope for the entire program,
  11985. including all other function definitions (so the ordering of function
  11986. definitions does not matter).
  11987. %
  11988. \python{The abstract syntax for function parameters in
  11989. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  11990. consists of a parameter name and its type. This design differs from
  11991. Python's \code{ast} module, which has a more complex structure for
  11992. function parameters to handle keyword parameters,
  11993. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  11994. complex Python abstract syntax into the simpler syntax of
  11995. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  11996. \code{FunctionDef} constructor are for decorators and a type
  11997. comment, neither of which are used by our compiler. We recommend
  11998. replacing them with \code{None} in the \code{shrink} pass.
  11999. }
  12000. %
  12001. The concrete syntax for function application\index{subject}{function
  12002. application} is
  12003. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12004. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12005. where the first expression
  12006. must evaluate to a function and the remaining expressions are the arguments. The
  12007. abstract syntax for function application is
  12008. $\APPLY{\Exp}{\Exp^*}$.
  12009. %% The syntax for function application does not include an explicit
  12010. %% keyword, which is error prone when using \code{match}. To alleviate
  12011. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12012. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12013. Functions are first-class in the sense that a function pointer
  12014. \index{subject}{function pointer} is data and can be stored in memory or passed
  12015. as a parameter to another function. Thus, there is a function
  12016. type, written
  12017. {\if\edition\racketEd
  12018. \begin{lstlisting}
  12019. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12020. \end{lstlisting}
  12021. \fi}
  12022. {\if\edition\pythonEd
  12023. \begin{lstlisting}
  12024. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12025. \end{lstlisting}
  12026. \fi}
  12027. %
  12028. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12029. through $\Type_n$ and whose return type is $\Type_R$. The main
  12030. limitation of these functions (with respect to
  12031. \racket{Racket}\python{Python} functions) is that they are not
  12032. lexically scoped. That is, the only external entities that can be
  12033. referenced from inside a function body are other globally-defined
  12034. functions. The syntax of \LangFun{} prevents function definitions from being
  12035. nested inside each other.
  12036. \newcommand{\LfunGrammarRacket}{
  12037. \begin{array}{lcl}
  12038. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12039. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12040. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12041. \end{array}
  12042. }
  12043. \newcommand{\LfunASTRacket}{
  12044. \begin{array}{lcl}
  12045. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12046. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12047. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12048. \end{array}
  12049. }
  12050. \newcommand{\LfunGrammarPython}{
  12051. \begin{array}{lcl}
  12052. \Type &::=& \key{int}
  12053. \MID \key{bool}
  12054. \MID \key{tuple}\LS \Type^+ \RS
  12055. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12056. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12057. \Stmt &::=& \CRETURN{\Exp} \\
  12058. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12059. \end{array}
  12060. }
  12061. \newcommand{\LfunASTPython}{
  12062. \begin{array}{lcl}
  12063. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12064. \MID \key{TupleType}\LS\Type^+\RS\\
  12065. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12066. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12067. \Stmt &::=& \RETURN{\Exp} \\
  12068. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12069. \\
  12070. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12071. \end{array}
  12072. }
  12073. \begin{figure}[tp]
  12074. \centering
  12075. \fbox{
  12076. \begin{minipage}{0.96\textwidth}
  12077. \small
  12078. {\if\edition\racketEd
  12079. \[
  12080. \begin{array}{l}
  12081. \gray{\LintGrammarRacket{}} \\ \hline
  12082. \gray{\LvarGrammarRacket{}} \\ \hline
  12083. \gray{\LifGrammarRacket{}} \\ \hline
  12084. \gray{\LwhileGrammarRacket} \\ \hline
  12085. \gray{\LtupGrammarRacket} \\ \hline
  12086. \LfunGrammarRacket \\
  12087. \begin{array}{lcl}
  12088. \LangFunM{} &::=& \Def \ldots \; \Exp
  12089. \end{array}
  12090. \end{array}
  12091. \]
  12092. \fi}
  12093. {\if\edition\pythonEd
  12094. \[
  12095. \begin{array}{l}
  12096. \gray{\LintGrammarPython{}} \\ \hline
  12097. \gray{\LvarGrammarPython{}} \\ \hline
  12098. \gray{\LifGrammarPython{}} \\ \hline
  12099. \gray{\LwhileGrammarPython} \\ \hline
  12100. \gray{\LtupGrammarPython} \\ \hline
  12101. \LfunGrammarPython \\
  12102. \begin{array}{rcl}
  12103. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12104. \end{array}
  12105. \end{array}
  12106. \]
  12107. \fi}
  12108. \end{minipage}
  12109. }
  12110. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12111. \label{fig:Rfun-concrete-syntax}
  12112. \end{figure}
  12113. \begin{figure}[tp]
  12114. \centering
  12115. \fbox{
  12116. \begin{minipage}{0.96\textwidth}
  12117. \small
  12118. {\if\edition\racketEd
  12119. \[
  12120. \begin{array}{l}
  12121. \gray{\LintOpAST} \\ \hline
  12122. \gray{\LvarASTRacket{}} \\ \hline
  12123. \gray{\LifASTRacket{}} \\ \hline
  12124. \gray{\LwhileASTRacket{}} \\ \hline
  12125. \gray{\LtupASTRacket{}} \\ \hline
  12126. \LfunASTRacket \\
  12127. \begin{array}{lcl}
  12128. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12129. \end{array}
  12130. \end{array}
  12131. \]
  12132. \fi}
  12133. {\if\edition\pythonEd
  12134. \[
  12135. \begin{array}{l}
  12136. \gray{\LintASTPython{}} \\ \hline
  12137. \gray{\LvarASTPython{}} \\ \hline
  12138. \gray{\LifASTPython{}} \\ \hline
  12139. \gray{\LwhileASTPython} \\ \hline
  12140. \gray{\LtupASTPython} \\ \hline
  12141. \LfunASTPython \\
  12142. \begin{array}{rcl}
  12143. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12144. \end{array}
  12145. \end{array}
  12146. \]
  12147. \fi}
  12148. \end{minipage}
  12149. }
  12150. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12151. \label{fig:Rfun-syntax}
  12152. \end{figure}
  12153. The program in Figure~\ref{fig:Rfun-function-example} is a
  12154. representative example of defining and using functions in \LangFun{}.
  12155. We define a function \code{map} that applies some other function
  12156. \code{f} to both elements of a tuple and returns a new tuple
  12157. containing the results. We also define a function \code{inc}. The
  12158. program applies \code{map} to \code{inc} and
  12159. %
  12160. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12161. %
  12162. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12163. %
  12164. from which we return the \code{42}.
  12165. \begin{figure}[tbp]
  12166. {\if\edition\racketEd
  12167. \begin{lstlisting}
  12168. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12169. : (Vector Integer Integer)
  12170. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12171. (define (inc [x : Integer]) : Integer
  12172. (+ x 1))
  12173. (vector-ref (map inc (vector 0 41)) 1)
  12174. \end{lstlisting}
  12175. \fi}
  12176. {\if\edition\pythonEd
  12177. \begin{lstlisting}
  12178. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12179. return f(v[0]), f(v[1])
  12180. def inc(x : int) -> int:
  12181. return x + 1
  12182. print( map(inc, (0, 41))[1] )
  12183. \end{lstlisting}
  12184. \fi}
  12185. \caption{Example of using functions in \LangFun{}.}
  12186. \label{fig:Rfun-function-example}
  12187. \end{figure}
  12188. The definitional interpreter for \LangFun{} is in
  12189. Figure~\ref{fig:interp-Rfun}. The case for the
  12190. %
  12191. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12192. %
  12193. AST is responsible for setting up the mutual recursion between the
  12194. top-level function definitions.
  12195. %
  12196. \racket{We use the classic back-patching
  12197. \index{subject}{back-patching} approach that uses mutable variables
  12198. and makes two passes over the function
  12199. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12200. top-level environment using a mutable cons cell for each function
  12201. definition. Note that the \code{lambda} value for each function is
  12202. incomplete; it does not yet include the environment. Once the
  12203. top-level environment is constructed, we then iterate over it and
  12204. update the \code{lambda} values to use the top-level environment.}
  12205. %
  12206. \python{We create a dictionary named \code{env} and fill it in
  12207. by mapping each function name to a new \code{Function} value,
  12208. each of which stores a reference to the \code{env}.
  12209. (We define the class \code{Function} for this purpose.)}
  12210. %
  12211. To interpret a function \racket{application}\python{call}, we match
  12212. the result of the function expression to obtain a function value. We
  12213. then extend the function's environment with mapping of parameters to
  12214. argument values. Finally, we interpret the body of the function in
  12215. this extended environment.
  12216. \begin{figure}[tp]
  12217. {\if\edition\racketEd
  12218. \begin{lstlisting}
  12219. (define interp-Rfun_class
  12220. (class interp-Lvec_class
  12221. (super-new)
  12222. (define/override ((interp-exp env) e)
  12223. (define recur (interp-exp env))
  12224. (match e
  12225. [(Var x) (unbox (dict-ref env x))]
  12226. [(Let x e body)
  12227. (define new-env (dict-set env x (box (recur e))))
  12228. ((interp-exp new-env) body)]
  12229. [(Apply fun args)
  12230. (define fun-val (recur fun))
  12231. (define arg-vals (for/list ([e args]) (recur e)))
  12232. (match fun-val
  12233. [`(function (,xs ...) ,body ,fun-env)
  12234. (define params-args (for/list ([x xs] [arg arg-vals])
  12235. (cons x (box arg))))
  12236. (define new-env (append params-args fun-env))
  12237. ((interp-exp new-env) body)]
  12238. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12239. [else ((super interp-exp env) e)]
  12240. ))
  12241. (define/public (interp-def d)
  12242. (match d
  12243. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12244. (cons f (box `(function ,xs ,body ())))]))
  12245. (define/override (interp-program p)
  12246. (match p
  12247. [(ProgramDefsExp info ds body)
  12248. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12249. (for/list ([f (in-dict-values top-level)])
  12250. (set-box! f (match (unbox f)
  12251. [`(function ,xs ,body ())
  12252. `(function ,xs ,body ,top-level)])))
  12253. ((interp-exp top-level) body))]))
  12254. ))
  12255. (define (interp-Rfun p)
  12256. (send (new interp-Rfun_class) interp-program p))
  12257. \end{lstlisting}
  12258. \fi}
  12259. {\if\edition\pythonEd
  12260. \begin{lstlisting}
  12261. class InterpLfun(InterpLtup):
  12262. def apply_fun(self, fun, args, e):
  12263. match fun:
  12264. case Function(name, xs, body, env):
  12265. new_env = env.copy().update(zip(xs, args))
  12266. return self.interp_stmts(body, new_env)
  12267. case _:
  12268. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12269. def interp_exp(self, e, env):
  12270. match e:
  12271. case Call(Name('input_int'), []):
  12272. return super().interp_exp(e, env)
  12273. case Call(func, args):
  12274. f = self.interp_exp(func, env)
  12275. vs = [self.interp_exp(arg, env) for arg in args]
  12276. return self.apply_fun(f, vs, e)
  12277. case _:
  12278. return super().interp_exp(e, env)
  12279. def interp_stmts(self, ss, env):
  12280. if len(ss) == 0:
  12281. return
  12282. match ss[0]:
  12283. case Return(value):
  12284. return self.interp_exp(value, env)
  12285. case FunctionDef(name, params, bod, dl, returns, comment):
  12286. ps = [x for (x,t) in params]
  12287. env[name] = Function(name, ps, bod, env)
  12288. return self.interp_stmts(ss[1:], env)
  12289. case _:
  12290. return super().interp_stmts(ss, env)
  12291. def interp(self, p):
  12292. match p:
  12293. case Module(ss):
  12294. env = {}
  12295. self.interp_stmts(ss, env)
  12296. if 'main' in env.keys():
  12297. self.apply_fun(env['main'], [], None)
  12298. case _:
  12299. raise Exception('interp: unexpected ' + repr(p))
  12300. \end{lstlisting}
  12301. \fi}
  12302. \caption{Interpreter for the \LangFun{} language.}
  12303. \label{fig:interp-Rfun}
  12304. \end{figure}
  12305. %\margincomment{TODO: explain type checker}
  12306. The type checker for \LangFun{} is in
  12307. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12308. function parameters into the simpler abstract syntax.) Similar to the
  12309. interpreter, the case for the
  12310. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12311. %
  12312. AST is responsible for setting up the mutual recursion between the
  12313. top-level function definitions. We begin by create a mapping
  12314. \code{env} from every function name to its type. We then type check
  12315. the program using this mapping.
  12316. %
  12317. In the case for function \racket{application}\python{call}, we match
  12318. the type of the function expression to a function type and check that
  12319. the types of the argument expressions are equal to the function's
  12320. parameter types. The type of the \racket{application}\python{call} as
  12321. a whole is the return type from the function type.
  12322. \begin{figure}[tp]
  12323. {\if\edition\racketEd
  12324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12325. (define type-check-Rfun_class
  12326. (class type-check-Lvec_class
  12327. (super-new)
  12328. (inherit check-type-equal?)
  12329. (define/public (type-check-apply env e es)
  12330. (define-values (e^ ty) ((type-check-exp env) e))
  12331. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12332. ((type-check-exp env) e)))
  12333. (match ty
  12334. [`(,ty^* ... -> ,rt)
  12335. (for ([arg-ty ty*] [param-ty ty^*])
  12336. (check-type-equal? arg-ty param-ty (Apply e es)))
  12337. (values e^ e* rt)]))
  12338. (define/override (type-check-exp env)
  12339. (lambda (e)
  12340. (match e
  12341. [(FunRef f n)
  12342. (values (FunRef f n) (dict-ref env f))]
  12343. [(Apply e es)
  12344. (define-values (e^ es^ rt) (type-check-apply env e es))
  12345. (values (Apply e^ es^) rt)]
  12346. [(Call e es)
  12347. (define-values (e^ es^ rt) (type-check-apply env e es))
  12348. (values (Call e^ es^) rt)]
  12349. [else ((super type-check-exp env) e)])))
  12350. (define/public (type-check-def env)
  12351. (lambda (e)
  12352. (match e
  12353. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12354. (define new-env (append (map cons xs ps) env))
  12355. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12356. (check-type-equal? ty^ rt body)
  12357. (Def f p:t* rt info body^)])))
  12358. (define/public (fun-def-type d)
  12359. (match d
  12360. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12361. (define/override (type-check-program e)
  12362. (match e
  12363. [(ProgramDefsExp info ds body)
  12364. (define env (for/list ([d ds])
  12365. (cons (Def-name d) (fun-def-type d))))
  12366. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12367. (define-values (body^ ty) ((type-check-exp env) body))
  12368. (check-type-equal? ty 'Integer body)
  12369. (ProgramDefsExp info ds^ body^)]))))
  12370. (define (type-check-Rfun p)
  12371. (send (new type-check-Rfun_class) type-check-program p))
  12372. \end{lstlisting}
  12373. \fi}
  12374. {\if\edition\pythonEd
  12375. \begin{lstlisting}
  12376. class TypeCheckLfun(TypeCheckLtup):
  12377. def type_check_exp(self, e, env):
  12378. match e:
  12379. case Call(Name('input_int'), []):
  12380. return super().type_check_exp(e, env)
  12381. case Call(func, args):
  12382. func_t = self.type_check_exp(func, env)
  12383. args_t = [self.type_check_exp(arg, env) for arg in args]
  12384. match func_t:
  12385. case FunctionType(params_t, return_t):
  12386. for (arg_t, param_t) in zip(args_t, params_t):
  12387. check_type_equal(param_t, arg_t, e)
  12388. return return_t
  12389. case _:
  12390. raise Exception('type_check_exp: in call, unexpected ' +
  12391. repr(func_t))
  12392. case _:
  12393. return super().type_check_exp(e, env)
  12394. def type_check_stmts(self, ss, env):
  12395. if len(ss) == 0:
  12396. return
  12397. match ss[0]:
  12398. case FunctionDef(name, params, body, dl, returns, comment):
  12399. new_env = env.copy().update(params)
  12400. rt = self.type_check_stmts(body, new_env)
  12401. check_type_equal(returns, rt, ss[0])
  12402. return self.type_check_stmts(ss[1:], env)
  12403. case Return(value):
  12404. return self.type_check_exp(value, env)
  12405. case _:
  12406. return super().type_check_stmts(ss, env)
  12407. def type_check(self, p):
  12408. match p:
  12409. case Module(body):
  12410. env = {}
  12411. for s in body:
  12412. match s:
  12413. case FunctionDef(name, params, bod, dl, returns, comment):
  12414. if name in env:
  12415. raise Exception('type_check: function ' +
  12416. repr(name) + ' defined twice')
  12417. params_t = [t for (x,t) in params]
  12418. env[name] = FunctionType(params_t, returns)
  12419. self.type_check_stmts(body, env)
  12420. case _:
  12421. raise Exception('type_check: unexpected ' + repr(p))
  12422. \end{lstlisting}
  12423. \fi}
  12424. \caption{Type checker for the \LangFun{} language.}
  12425. \label{fig:type-check-Rfun}
  12426. \end{figure}
  12427. \clearpage
  12428. \section{Functions in x86}
  12429. \label{sec:fun-x86}
  12430. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12431. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12432. %% \margincomment{\tiny Talk about the return address on the
  12433. %% stack and what callq and retq does.\\ --Jeremy }
  12434. The x86 architecture provides a few features to support the
  12435. implementation of functions. We have already seen that there are
  12436. labels in x86 so that one can refer to the location of an instruction, as is
  12437. needed for jump instructions. Labels can also be used to mark the
  12438. beginning of the instructions for a function. Going further, we can
  12439. obtain the address of a label by using the \key{leaq} instruction and
  12440. PC-relative addressing. For example, the following puts the
  12441. address of the \code{inc} label into the \code{rbx} register.
  12442. \begin{lstlisting}
  12443. leaq inc(%rip), %rbx
  12444. \end{lstlisting}
  12445. The instruction pointer register \key{rip} (aka. the program counter
  12446. \index{subject}{program counter}) always points to the next
  12447. instruction to be executed. When combined with a label, as in
  12448. \code{inc(\%rip)}, the assembler computes the distance $d$ between the
  12449. address of \code{inc} and where the \code{rip} would be at that moment
  12450. and then changes the \code{inc(\%rip)} argument to \code{$d$(\%rip)},
  12451. which at runtime will compute the address of \code{inc}.
  12452. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12453. to functions whose locations were given by a label, such as
  12454. \code{read\_int}. To support function calls in this chapter we instead
  12455. will be jumping to functions whose location are given by an address in
  12456. a register, that is, we need to make an \emph{indirect function
  12457. call}. The x86 syntax for this is a \code{callq} instruction but with
  12458. an asterisk before the register name.\index{subject}{indirect function
  12459. call}
  12460. \begin{lstlisting}
  12461. callq *%rbx
  12462. \end{lstlisting}
  12463. \subsection{Calling Conventions}
  12464. \index{subject}{calling conventions}
  12465. The \code{callq} instruction provides partial support for implementing
  12466. functions: it pushes the return address on the stack and it jumps to
  12467. the target. However, \code{callq} does not handle
  12468. \begin{enumerate}
  12469. \item parameter passing,
  12470. \item pushing frames on the procedure call stack and popping them off,
  12471. or
  12472. \item determining how registers are shared by different functions.
  12473. \end{enumerate}
  12474. Regarding (1) parameter passing, recall that the x86-64 calling convention
  12475. for Unix-based system uses the following six
  12476. registers to pass arguments to a function, in this order.
  12477. \begin{lstlisting}
  12478. rdi rsi rdx rcx r8 r9
  12479. \end{lstlisting}
  12480. If there are
  12481. more than six arguments, then the calling convention mandates to use space on the
  12482. frame of the caller for the rest of the arguments. However, to ease
  12483. the implementation of efficient tail calls
  12484. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12485. arguments.
  12486. %
  12487. Also recall that the register \code{rax} is for the return value of
  12488. the function.
  12489. \index{subject}{prelude}\index{subject}{conclusion}
  12490. Regarding (2) frames \index{subject}{frame} and the procedure call
  12491. stack, \index{subject}{procedure call stack} recall from
  12492. Section~\ref{sec:x86} that the stack grows down and each function call
  12493. uses a chunk of space on the stack called a frame. The caller sets the
  12494. stack pointer, register \code{rsp}, to the last data item in its
  12495. frame. The callee must not change anything in the caller's frame, that
  12496. is, anything that is at or above the stack pointer. The callee is free
  12497. to use locations that are below the stack pointer.
  12498. Recall that we are storing variables of tuple type on the root stack.
  12499. So the prelude needs to move the root stack pointer \code{r15} up
  12500. according to the number of variables of tuple type and
  12501. the conclusion needs to move the root stack pointer back down. Also,
  12502. the prelude must initialize to \code{0} this frame's slots in the root
  12503. stack to signal to the garbage collector that those slots do not yet
  12504. contain a pointer to a vector. Otherwise the garbage collector will
  12505. interpret the garbage bits in those slots as memory addresses and try
  12506. to traverse them, causing serious mayhem!
  12507. Regarding (3) the sharing of registers between different functions,
  12508. recall from Section~\ref{sec:calling-conventions} that the registers
  12509. are divided into two groups, the caller-saved registers and the
  12510. callee-saved registers. The caller should assume that all the
  12511. caller-saved registers get overwritten with arbitrary values by the
  12512. callee. For that reason we recommend in
  12513. Section~\ref{sec:calling-conventions} that variables that are live
  12514. during a function call should not be assigned to caller-saved
  12515. registers.
  12516. On the flip side, if the callee wants to use a callee-saved register,
  12517. the callee must save the contents of those registers on their stack
  12518. frame and then put them back prior to returning to the caller. For
  12519. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12520. the register allocator assigns a variable to a callee-saved register,
  12521. then the prelude of the \code{main} function must save that register
  12522. to the stack and the conclusion of \code{main} must restore it. This
  12523. recommendation now generalizes to all functions.
  12524. Recall that the base pointer, register \code{rbp}, is used as a
  12525. point-of-reference within a frame, so that each local variable can be
  12526. accessed at a fixed offset from the base pointer
  12527. (Section~\ref{sec:x86}).
  12528. %
  12529. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12530. and callee frames.
  12531. \begin{figure}[tbp]
  12532. \centering
  12533. \begin{tabular}{r|r|l|l} \hline
  12534. Caller View & Callee View & Contents & Frame \\ \hline
  12535. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12536. 0(\key{\%rbp}) & & old \key{rbp} \\
  12537. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12538. \ldots & & \ldots \\
  12539. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12540. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12541. \ldots & & \ldots \\
  12542. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12543. %% & & \\
  12544. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12545. %% & \ldots & \ldots \\
  12546. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12547. \hline
  12548. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12549. & 0(\key{\%rbp}) & old \key{rbp} \\
  12550. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12551. & \ldots & \ldots \\
  12552. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12553. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12554. & \ldots & \ldots \\
  12555. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12556. \end{tabular}
  12557. \caption{Memory layout of caller and callee frames.}
  12558. \label{fig:call-frames}
  12559. \end{figure}
  12560. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12561. %% local variables and for storing the values of callee-saved registers
  12562. %% (we shall refer to all of these collectively as ``locals''), and that
  12563. %% at the beginning of a function we move the stack pointer \code{rsp}
  12564. %% down to make room for them.
  12565. %% We recommend storing the local variables
  12566. %% first and then the callee-saved registers, so that the local variables
  12567. %% can be accessed using \code{rbp} the same as before the addition of
  12568. %% functions.
  12569. %% To make additional room for passing arguments, we shall
  12570. %% move the stack pointer even further down. We count how many stack
  12571. %% arguments are needed for each function call that occurs inside the
  12572. %% body of the function and find their maximum. Adding this number to the
  12573. %% number of locals gives us how much the \code{rsp} should be moved at
  12574. %% the beginning of the function. In preparation for a function call, we
  12575. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12576. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12577. %% so on.
  12578. %% Upon calling the function, the stack arguments are retrieved by the
  12579. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12580. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12581. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12582. %% the layout of the caller and callee frames. Notice how important it is
  12583. %% that we correctly compute the maximum number of arguments needed for
  12584. %% function calls; if that number is too small then the arguments and
  12585. %% local variables will smash into each other!
  12586. \subsection{Efficient Tail Calls}
  12587. \label{sec:tail-call}
  12588. In general, the amount of stack space used by a program is determined
  12589. by the longest chain of nested function calls. That is, if function
  12590. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12591. of stack space is linear in $n$. The depth $n$ can grow quite large
  12592. if functions are (mutually) recursive. However, in
  12593. some cases we can arrange to use only a constant amount of space for a
  12594. long chain of nested function calls.
  12595. A \emph{tail call}\index{subject}{tail call} is a function call that
  12596. happens as the last action in a function body.
  12597. For example, in the following
  12598. program, the recursive call to \code{tail\_sum} is a tail call.
  12599. \begin{center}
  12600. {\if\edition\racketEd
  12601. \begin{lstlisting}
  12602. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12603. (if (eq? n 0)
  12604. r
  12605. (tail_sum (- n 1) (+ n r))))
  12606. (+ (tail_sum 3 0) 36)
  12607. \end{lstlisting}
  12608. \fi}
  12609. {\if\edition\pythonEd
  12610. \begin{lstlisting}
  12611. def tail_sum(n : int, r : int) -> int:
  12612. if n == 0:
  12613. return r
  12614. else:
  12615. return tail_sum(n - 1, n + r)
  12616. print( tail_sum(3, 0) + 36)
  12617. \end{lstlisting}
  12618. \fi}
  12619. \end{center}
  12620. At a tail call, the frame of the caller is no longer needed, so we can
  12621. pop the caller's frame before making the tail call. With this
  12622. approach, a recursive function that only makes tail calls ends up
  12623. using a constant amount of stack space. Functional languages like
  12624. Racket rely heavily on recursive functions, so the definition of
  12625. Racket \emph{requires} that all tail calls be optimized in this way.
  12626. \index{subject}{frame}
  12627. Some care is needed with regards to argument passing in tail calls.
  12628. As mentioned above, for arguments beyond the sixth, the convention is
  12629. to use space in the caller's frame for passing arguments. But for a
  12630. tail call we pop the caller's frame and can no longer use it. An
  12631. alternative is to use space in the callee's frame for passing
  12632. arguments. However, this option is also problematic because the caller
  12633. and callee's frames overlap in memory. As we begin to copy the
  12634. arguments from their sources in the caller's frame, the target
  12635. locations in the callee's frame might collide with the sources for
  12636. later arguments! We solve this problem by using the heap instead of
  12637. the stack for passing more than six arguments, which we describe in
  12638. the Section~\ref{sec:limit-functions-r4}.
  12639. As mentioned above, for a tail call we pop the caller's frame prior to
  12640. making the tail call. The instructions for popping a frame are the
  12641. instructions that we usually place in the conclusion of a
  12642. function. Thus, we also need to place such code immediately before
  12643. each tail call. These instructions include restoring the callee-saved
  12644. registers, so it is fortunate that the argument passing registers are
  12645. all caller-saved registers!
  12646. One last note regarding which instruction to use to make the tail
  12647. call. When the callee is finished, it should not return to the current
  12648. function, but it should return to the function that called the current
  12649. one. Thus, the return address that is already on the stack is the
  12650. right one, and we should not use \key{callq} to make the tail call, as
  12651. that would unnecessarily overwrite the return address. Instead we can
  12652. simply use the \key{jmp} instruction. Like the indirect function call,
  12653. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12654. register prefixed with an asterisk. We recommend using \code{rax} to
  12655. hold the jump target because the preceding conclusion can overwrite
  12656. just about everything else.
  12657. \begin{lstlisting}
  12658. jmp *%rax
  12659. \end{lstlisting}
  12660. \section{Shrink \LangFun{}}
  12661. \label{sec:shrink-r4}
  12662. The \code{shrink} pass performs a minor modification to ease the
  12663. later passes. This pass introduces an explicit \code{main} function
  12664. that gobbles up all the top-level statements of the module.
  12665. %
  12666. \racket{It also changes the top \code{ProgramDefsExp} form to
  12667. \code{ProgramDefs}.}
  12668. {\if\edition\racketEd
  12669. \begin{lstlisting}
  12670. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12671. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12672. \end{lstlisting}
  12673. where $\itm{mainDef}$ is
  12674. \begin{lstlisting}
  12675. (Def 'main '() 'Integer '() |$\Exp'$|)
  12676. \end{lstlisting}
  12677. \fi}
  12678. {\if\edition\pythonEd
  12679. \begin{lstlisting}
  12680. Module(|$\Def\ldots\Stmt\ldots$|)
  12681. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12682. \end{lstlisting}
  12683. where $\itm{mainDef}$ is
  12684. \begin{lstlisting}
  12685. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12686. \end{lstlisting}
  12687. \fi}
  12688. \section{Reveal Functions and the \LangFunRef{} language}
  12689. \label{sec:reveal-functions-r4}
  12690. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12691. in that it conflates the use of function names and local
  12692. variables. This is a problem because we need to compile the use of a
  12693. function name differently than the use of a local variable; we need to
  12694. use \code{leaq} to convert the function name (a label in x86) to an
  12695. address in a register. Thus, we create a new pass that changes
  12696. function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where $n$ is the
  12697. arity of the function.\python{\footnote{The arity is not needed in this
  12698. chapter but is used in Chapter~\ref{ch:Ldyn}.}} This pass is
  12699. named \code{reveal\_functions} and the output language, \LangFunRef{},
  12700. is defined in Figure~\ref{fig:f1-syntax}.
  12701. %% The concrete syntax for a
  12702. %% function reference is $\CFUNREF{f}$.
  12703. \begin{figure}[tp]
  12704. \centering
  12705. \fbox{
  12706. \begin{minipage}{0.96\textwidth}
  12707. {\if\edition\racketEd
  12708. \[
  12709. \begin{array}{lcl}
  12710. \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12711. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12712. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12713. \end{array}
  12714. \]
  12715. \fi}
  12716. {\if\edition\pythonEd
  12717. \[
  12718. \begin{array}{lcl}
  12719. \Exp &::=& \FUNREF{\Var}{\Int}\\
  12720. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12721. \end{array}
  12722. \]
  12723. \fi}
  12724. \end{minipage}
  12725. }
  12726. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12727. (Figure~\ref{fig:Rfun-syntax}).}
  12728. \label{fig:f1-syntax}
  12729. \end{figure}
  12730. %% Distinguishing between calls in tail position and non-tail position
  12731. %% requires the pass to have some notion of context. We recommend using
  12732. %% two mutually recursive functions, one for processing expressions in
  12733. %% tail position and another for the rest.
  12734. \racket{Placing this pass after \code{uniquify} will make sure that
  12735. there are no local variables and functions that share the same
  12736. name.}
  12737. %
  12738. The \code{reveal\_functions} pass should come before the
  12739. \code{remove\_complex\_operands} pass because function references
  12740. should be categorized as complex expressions.
  12741. \section{Limit Functions}
  12742. \label{sec:limit-functions-r4}
  12743. Recall that we wish to limit the number of function parameters to six
  12744. so that we do not need to use the stack for argument passing, which
  12745. makes it easier to implement efficient tail calls. However, because
  12746. the input language \LangFun{} supports arbitrary numbers of function
  12747. arguments, we have some work to do!
  12748. This pass transforms functions and function calls that involve more
  12749. than six arguments to pass the first five arguments as usual, but it
  12750. packs the rest of the arguments into a vector and passes it as the
  12751. sixth argument.
  12752. Each function definition with seven or more parameters is transformed as
  12753. follows.
  12754. {\if\edition\racketEd
  12755. \begin{lstlisting}
  12756. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12757. |$\Rightarrow$|
  12758. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12759. \end{lstlisting}
  12760. \fi}
  12761. {\if\edition\pythonEd
  12762. \begin{lstlisting}
  12763. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12764. |$\Rightarrow$|
  12765. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12766. |$T_r$|, None, |$\itm{body}'$|, None)
  12767. \end{lstlisting}
  12768. \fi}
  12769. %
  12770. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12771. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12772. the $k$th element of the tuple, where $k = i - 6$.
  12773. %
  12774. {\if\edition\racketEd
  12775. \begin{lstlisting}
  12776. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12777. \end{lstlisting}
  12778. \fi}
  12779. {\if\edition\pythonEd
  12780. \begin{lstlisting}
  12781. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12782. \end{lstlisting}
  12783. \fi}
  12784. For function calls with too many arguments, the \code{limit\_functions}
  12785. pass transforms them in the following way.
  12786. \begin{tabular}{lll}
  12787. \begin{minipage}{0.3\textwidth}
  12788. {\if\edition\racketEd
  12789. \begin{lstlisting}
  12790. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12791. \end{lstlisting}
  12792. \fi}
  12793. {\if\edition\pythonEd
  12794. \begin{lstlisting}
  12795. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12796. \end{lstlisting}
  12797. \fi}
  12798. \end{minipage}
  12799. &
  12800. $\Rightarrow$
  12801. &
  12802. \begin{minipage}{0.5\textwidth}
  12803. {\if\edition\racketEd
  12804. \begin{lstlisting}
  12805. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12806. \end{lstlisting}
  12807. \fi}
  12808. {\if\edition\pythonEd
  12809. \begin{lstlisting}
  12810. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12811. \end{lstlisting}
  12812. \fi}
  12813. \end{minipage}
  12814. \end{tabular}
  12815. \section{Remove Complex Operands}
  12816. \label{sec:rco-r4}
  12817. The primary decisions to make for this pass is whether to classify
  12818. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12819. atomic or complex expressions. Recall that a simple expression will
  12820. eventually end up as just an immediate argument of an x86
  12821. instruction. Function application will be translated to a sequence of
  12822. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12823. classified as complex expression. On the other hand, the arguments of
  12824. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12825. %
  12826. Regarding \code{FunRef}, as discussed above, the function label needs
  12827. to be converted to an address using the \code{leaq} instruction. Thus,
  12828. even though \code{FunRef} seems rather simple, it needs to be
  12829. classified as a complex expression so that we generate an assignment
  12830. statement with a left-hand side that can serve as the target of the
  12831. \code{leaq}.
  12832. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12833. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12834. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12835. %
  12836. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12837. % TODO: Return?
  12838. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12839. %% \LangFunANF{} of this pass.
  12840. %% \begin{figure}[tp]
  12841. %% \centering
  12842. %% \fbox{
  12843. %% \begin{minipage}{0.96\textwidth}
  12844. %% \small
  12845. %% \[
  12846. %% \begin{array}{rcl}
  12847. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12848. %% \MID \VOID{} } \\
  12849. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12850. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12851. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12852. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12853. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12854. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12855. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12856. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12857. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12858. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12859. %% \end{array}
  12860. %% \]
  12861. %% \end{minipage}
  12862. %% }
  12863. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12864. %% \label{fig:Rfun-anf-syntax}
  12865. %% \end{figure}
  12866. \section{Explicate Control and the \LangCFun{} language}
  12867. \label{sec:explicate-control-r4}
  12868. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12869. output of \code{explicate\_control}.
  12870. %
  12871. \racket{(The concrete syntax is given in
  12872. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12873. %
  12874. The auxiliary functions for assignment\racket{and tail contexts} should
  12875. be updated with cases for
  12876. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12877. function for predicate context should be updated for
  12878. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12879. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  12880. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12881. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12882. auxiliary function for processing function definitions. This code is
  12883. similar to the case for \code{Program} in \LangVec{}. The top-level
  12884. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12885. form of \LangFun{} can then apply this new function to all the
  12886. function definitions.
  12887. {\if\edition\pythonEd
  12888. The translation of \code{Return} statements requires a new auxiliary
  12889. function to handle expressions in tail context, called
  12890. \code{explicate\_tail}. The function should take an expression and the
  12891. dictionary of basic blocks and produce a list of statements in the
  12892. \LangCFun{} language. The \code{explicate\_tail} function should
  12893. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12894. and a default case for other kinds of expressions. The default case
  12895. should produce a \code{Return} statement. The case for \code{Call}
  12896. should change it into \code{TailCall}. The other cases should
  12897. recursively process their subexpressions and statements, choosing the
  12898. appropriate explicate functions for the various contexts.
  12899. \fi}
  12900. \newcommand{\CfunASTRacket}{
  12901. \begin{array}{lcl}
  12902. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12903. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12904. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12905. \end{array}
  12906. }
  12907. \newcommand{\CfunASTPython}{
  12908. \begin{array}{lcl}
  12909. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  12910. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12911. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12912. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  12913. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  12914. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12915. \end{array}
  12916. }
  12917. \begin{figure}[tp]
  12918. \fbox{
  12919. \begin{minipage}{0.96\textwidth}
  12920. \small
  12921. {\if\edition\racketEd
  12922. \[
  12923. \begin{array}{l}
  12924. \gray{\CvarASTRacket} \\ \hline
  12925. \gray{\CifASTRacket} \\ \hline
  12926. \gray{\CloopASTRacket} \\ \hline
  12927. \gray{\CtupASTRacket} \\ \hline
  12928. \CfunASTRacket \\
  12929. \begin{array}{lcl}
  12930. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12931. \end{array}
  12932. \end{array}
  12933. \]
  12934. \fi}
  12935. {\if\edition\pythonEd
  12936. \[
  12937. \begin{array}{l}
  12938. \gray{\CifASTPython} \\ \hline
  12939. \gray{\CtupASTPython} \\ \hline
  12940. \CfunASTPython \\
  12941. \begin{array}{lcl}
  12942. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12943. \end{array}
  12944. \end{array}
  12945. \]
  12946. \fi}
  12947. \end{minipage}
  12948. }
  12949. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  12950. \label{fig:c3-syntax}
  12951. \end{figure}
  12952. \section{Select Instructions and the \LangXIndCall{} Language}
  12953. \label{sec:select-r4}
  12954. \index{subject}{instruction selection}
  12955. The output of select instructions is a program in the \LangXIndCall{}
  12956. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  12957. \index{subject}{x86}
  12958. \begin{figure}[tp]
  12959. \fbox{
  12960. \begin{minipage}{0.96\textwidth}
  12961. \small
  12962. \[
  12963. \begin{array}{lcl}
  12964. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  12965. \itm{cc} & ::= & \gray{ \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  12966. \Instr &::=& \ldots
  12967. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  12968. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  12969. \Block &::= & \itm{label}\key{:}\, \Instr^{*} \\
  12970. \Def &::= & \key{.globl}\,\itm{label}\; \Block^{*} \\
  12971. \LangXIndCallM{} &::= & \Def\ldots
  12972. \end{array}
  12973. \]
  12974. \end{minipage}
  12975. }
  12976. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  12977. \label{fig:x86-3-concrete}
  12978. \end{figure}
  12979. \begin{figure}[tp]
  12980. \fbox{
  12981. \begin{minipage}{0.96\textwidth}
  12982. \small
  12983. {\if\edition\racketEd
  12984. \[
  12985. \begin{array}{lcl}
  12986. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  12987. \MID \BYTEREG{\Reg} } \\
  12988. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  12989. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  12990. \MID \TAILJMP{\Arg}{\itm{int}}\\
  12991. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  12992. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  12993. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  12994. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12995. \end{array}
  12996. \]
  12997. \fi}
  12998. {\if\edition\pythonEd
  12999. \[
  13000. \begin{array}{lcl}
  13001. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13002. \MID \BYTEREG{\Reg} } \\
  13003. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13004. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13005. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13006. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13007. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13008. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13009. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13010. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13011. \end{array}
  13012. \]
  13013. \fi}
  13014. \end{minipage}
  13015. }
  13016. \caption{The abstract syntax of \LangXIndCall{} (extends
  13017. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13018. \label{fig:x86-3}
  13019. \end{figure}
  13020. An assignment of a function reference to a variable becomes a
  13021. load-effective-address instruction as follows, where $\itm{lhs}'$
  13022. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  13023. to \Arg{} in \LangXIndCallVar{}. \\
  13024. \begin{tabular}{lcl}
  13025. \begin{minipage}{0.35\textwidth}
  13026. {\if\edition\racketEd
  13027. \begin{lstlisting}
  13028. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13029. \end{lstlisting}
  13030. \fi}
  13031. {\if\edition\pythonEd
  13032. \begin{lstlisting}
  13033. |$\itm{lhs}$| = FunRef(|$f$|, |$n$|);
  13034. \end{lstlisting}
  13035. \fi}
  13036. \end{minipage}
  13037. &
  13038. $\Rightarrow$\qquad\qquad
  13039. &
  13040. \begin{minipage}{0.3\textwidth}
  13041. {\if\edition\racketEd
  13042. \begin{lstlisting}
  13043. leaq (fun-ref |$f$| |$n$|), |$\itm{lhs}'$|
  13044. \end{lstlisting}
  13045. \fi}
  13046. {\if\edition\pythonEd
  13047. \begin{lstlisting}
  13048. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13049. \end{lstlisting}
  13050. \fi}
  13051. \end{minipage}
  13052. \end{tabular} \\
  13053. Regarding function definitions, we need to remove the parameters and
  13054. instead perform parameter passing using the conventions discussed in
  13055. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13056. registers. We recommend turning the parameters into local variables
  13057. and generating instructions at the beginning of the function to move
  13058. from the argument passing registers to these local variables.
  13059. {\if\edition\racketEd
  13060. \begin{lstlisting}
  13061. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13062. |$\Rightarrow$|
  13063. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13064. \end{lstlisting}
  13065. \fi}
  13066. {\if\edition\pythonEd
  13067. \begin{lstlisting}
  13068. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13069. |$\Rightarrow$|
  13070. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13071. \end{lstlisting}
  13072. \fi}
  13073. The basic blocks $B'$ are the same as $B$ except that the
  13074. \code{start} block is modified to add the instructions for moving from
  13075. the argument registers to the parameter variables. So the \code{start}
  13076. block of $B$ shown on the left is changed to the code on the right.
  13077. \begin{center}
  13078. \begin{minipage}{0.3\textwidth}
  13079. \begin{lstlisting}
  13080. start:
  13081. |$\itm{instr}_1$|
  13082. |$\cdots$|
  13083. |$\itm{instr}_n$|
  13084. \end{lstlisting}
  13085. \end{minipage}
  13086. $\Rightarrow$
  13087. \begin{minipage}{0.3\textwidth}
  13088. \begin{lstlisting}
  13089. start:
  13090. movq %rdi, |$x_1$|
  13091. |$\cdots$|
  13092. |$\itm{instr}_1$|
  13093. |$\cdots$|
  13094. |$\itm{instr}_n$|
  13095. \end{lstlisting}
  13096. \end{minipage}
  13097. \end{center}
  13098. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13099. parameters the function expects, but the parameters are no longer in
  13100. the syntax of function definitions. Instead, add an entry to
  13101. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13102. to construct $\itm{info}'$.}
  13103. By changing the parameters to local variables, we are giving the
  13104. register allocator control over which registers or stack locations to
  13105. use for them. If you implemented the move-biasing challenge
  13106. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13107. assign the parameter variables to the corresponding argument register,
  13108. in which case the \code{patch\_instructions} pass will remove the
  13109. \code{movq} instruction. This happens in the example translation in
  13110. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13111. the \code{add} function.
  13112. %
  13113. Also, note that the register allocator will perform liveness analysis
  13114. on this sequence of move instructions and build the interference
  13115. graph. So, for example, $x_1$ will be marked as interfering with
  13116. \code{rsi} and that will prevent the assignment of $x_1$ to
  13117. \code{rsi}, which is good, because that would overwrite the argument
  13118. that needs to move into $x_2$.
  13119. Next, consider the compilation of function calls. In the mirror image
  13120. of handling the parameters of function definitions, the arguments need
  13121. to be moved to the argument passing registers. The function call
  13122. itself is performed with an indirect function call. The return value
  13123. from the function is stored in \code{rax}, so it needs to be moved
  13124. into the \itm{lhs}.
  13125. \begin{lstlisting}
  13126. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13127. |$\Rightarrow$|
  13128. movq |$\itm{arg}_1$|, %rdi
  13129. movq |$\itm{arg}_2$|, %rsi
  13130. |$\vdots$|
  13131. callq *|\itm{fun}|
  13132. movq %rax, |\itm{lhs}|
  13133. \end{lstlisting}
  13134. The \code{IndirectCallq} AST node includes an integer for the arity of
  13135. the function, i.e., the number of parameters. That information is
  13136. useful in the \code{uncover\_live} pass for determining which
  13137. argument-passing registers are potentially read during the call.
  13138. For tail calls, the parameter passing is the same as non-tail calls:
  13139. generate instructions to move the arguments into the argument
  13140. passing registers. After that we need to pop the frame from the
  13141. procedure call stack. However, we do not yet know how big the frame
  13142. is; that gets determined during register allocation. So instead of
  13143. generating those instructions here, we invent a new instruction that
  13144. means ``pop the frame and then do an indirect jump'', which we name
  13145. \code{TailJmp}. The abstract syntax for this instruction includes an
  13146. argument that specifies where to jump and an integer that represents
  13147. the arity of the function being called.
  13148. Recall that we use the label \code{start} for the initial block of a
  13149. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13150. the conclusion of the program with \code{conclusion}, so that
  13151. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13152. by a jump to \code{conclusion}. With the addition of function
  13153. definitions, there is a start block and conclusion for each function,
  13154. but their labels need to be unique. We recommend prepending the
  13155. function's name to \code{start} and \code{conclusion}, respectively,
  13156. to obtain unique labels.
  13157. \section{Register Allocation}
  13158. \label{sec:register-allocation-r4}
  13159. \subsection{Liveness Analysis}
  13160. \label{sec:liveness-analysis-r4}
  13161. \index{subject}{liveness analysis}
  13162. %% The rest of the passes need only minor modifications to handle the new
  13163. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13164. %% \code{leaq}.
  13165. The \code{IndirectCallq} instruction should be treated like
  13166. \code{Callq} regarding its written locations $W$, in that they should
  13167. include all the caller-saved registers. Recall that the reason for
  13168. that is to force variables that are live across a function call to be assigned to callee-saved
  13169. registers or to be spilled to the stack.
  13170. Regarding the set of read locations $R$, the arity field of
  13171. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13172. argument-passing registers should be considered as read by those
  13173. instructions. Also, the target field of \code{TailJmp} and
  13174. \code{IndirectCallq} should be included in the set of read locations
  13175. $R$.
  13176. \subsection{Build Interference Graph}
  13177. \label{sec:build-interference-r4}
  13178. With the addition of function definitions, we compute a separate interference
  13179. graph for each function (not just one for the whole program).
  13180. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13181. spill vector-typed variables that are live during a call to
  13182. \code{collect}, the garbage collector. With the addition of functions to our language, we
  13183. need to revisit this issue. Functions that perform allocation contain
  13184. calls to the collector. Thus, we should
  13185. not only spill a vector-typed variable when it is live during a call
  13186. to \code{collect}, but we should spill the variable if it is live
  13187. during call to a user-defined function. Thus, in the \code{build\_interference} pass,
  13188. we recommend adding interference edges between call-live vector-typed
  13189. variables and the callee-saved registers (in addition to the usual
  13190. addition of edges between call-live variables and the caller-saved
  13191. registers).
  13192. \subsection{Allocate Registers}
  13193. The primary change to the \code{allocate\_registers} pass is adding an
  13194. auxiliary function for handling definitions (the \Def{} non-terminal
  13195. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13196. logic is the same as described in
  13197. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13198. allocation is performed many times, once for each function definition,
  13199. instead of just once for the whole program.
  13200. \section{Patch Instructions}
  13201. In \code{patch\_instructions}, you should deal with the x86
  13202. idiosyncrasy that the destination argument of \code{leaq} must be a
  13203. register. Additionally, you should ensure that the argument of
  13204. \code{TailJmp} is \itm{rax}, our reserved register---mostly to make
  13205. code generation more convenient, because we trample many registers
  13206. before the tail call (as explained in the next section).
  13207. \section{Prelude and Conclusion}
  13208. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13209. %% \code{IndirectCallq} are straightforward: output their concrete
  13210. %% syntax.
  13211. %% \begin{lstlisting}
  13212. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13213. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13214. %% \end{lstlisting}
  13215. Now that register allocation is complete, we can translate the
  13216. \code{TailJmp} into a sequence of instructions. A straightforward
  13217. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13218. However, before the jump we need to pop the current frame. This
  13219. sequence of instructions is the same as the code for the conclusion of
  13220. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13221. Regarding function definitions, you need to generate a prelude
  13222. and conclusion for each one. This code is similar to the prelude and
  13223. conclusion generated for the \code{main} function in
  13224. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13225. should carry out the following steps.
  13226. % TODO: .align the functions!
  13227. \begin{enumerate}
  13228. %% \item Start with \code{.global} and \code{.align} directives followed
  13229. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13230. %% example.)
  13231. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13232. pointer.
  13233. \item Push to the stack all of the callee-saved registers that were
  13234. used for register allocation.
  13235. \item Move the stack pointer \code{rsp} down by the size of the stack
  13236. frame for this function, which depends on the number of regular
  13237. spills. (Aligned to 16 bytes.)
  13238. \item Move the root stack pointer \code{r15} up by the size of the
  13239. root-stack frame for this function, which depends on the number of
  13240. spilled vectors. \label{root-stack-init}
  13241. \item Initialize to zero all new entries in the root-stack frame.
  13242. \item Jump to the start block.
  13243. \end{enumerate}
  13244. The prelude of the \code{main} function has one additional task: call
  13245. the \code{initialize} function to set up the garbage collector and
  13246. move the value of the global \code{rootstack\_begin} in
  13247. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13248. above, which depends on \code{r15}.
  13249. The conclusion of every function should do the following.
  13250. \begin{enumerate}
  13251. \item Move the stack pointer back up by the size of the stack frame
  13252. for this function.
  13253. \item Restore the callee-saved registers by popping them from the
  13254. stack.
  13255. \item Move the root stack pointer back down by the size of the
  13256. root-stack frame for this function.
  13257. \item Restore \code{rbp} by popping it from the stack.
  13258. \item Return to the caller with the \code{retq} instruction.
  13259. \end{enumerate}
  13260. \begin{exercise}\normalfont
  13261. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13262. Create 5 new programs that use functions, including examples that pass
  13263. functions and return functions from other functions, recursive
  13264. functions, functions that create vectors, and functions that make tail
  13265. calls. Test your compiler on these new programs and all of your
  13266. previously created test programs.
  13267. \end{exercise}
  13268. \begin{figure}[tbp]
  13269. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13270. \node (Rfun) at (0,2) {\large \LangFun{}};
  13271. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13272. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13273. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13274. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13275. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13276. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13277. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13278. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13279. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13280. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13281. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13282. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13283. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13284. \path[->,bend left=15] (Rfun) edge [above] node
  13285. {\ttfamily\footnotesize shrink} (Rfun-1);
  13286. \path[->,bend left=15] (Rfun-1) edge [above] node
  13287. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13288. \path[->,bend left=15] (Rfun-2) edge [above] node
  13289. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13290. \path[->,bend left=15] (F1-1) edge [right] node
  13291. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13292. \path[->,bend right=15] (F1-2) edge [above] node
  13293. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13294. \path[->,bend right=15] (F1-3) edge [above] node
  13295. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13296. \path[->,bend left=15] (F1-4) edge [right] node
  13297. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13298. \path[->,bend right=15] (C3-2) edge [left] node
  13299. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13300. \path[->,bend left=15] (x86-2) edge [left] node
  13301. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13302. \path[->,bend right=15] (x86-2-1) edge [below] node
  13303. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13304. \path[->,bend right=15] (x86-2-2) edge [left] node
  13305. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13306. \path[->,bend left=15] (x86-3) edge [above] node
  13307. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13308. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13309. \end{tikzpicture}
  13310. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13311. \label{fig:Rfun-passes}
  13312. \end{figure}
  13313. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13314. compiling \LangFun{} to x86.
  13315. \section{An Example Translation}
  13316. \label{sec:functions-example}
  13317. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13318. function in \LangFun{} to x86. The figure also includes the results of the
  13319. \code{explicate\_control} and \code{select\_instructions} passes.
  13320. \begin{figure}[htbp]
  13321. \begin{tabular}{ll}
  13322. \begin{minipage}{0.4\textwidth}
  13323. % s3_2.rkt
  13324. {\if\edition\racketEd
  13325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13326. (define (add [x : Integer] [y : Integer])
  13327. : Integer
  13328. (+ x y))
  13329. (add 40 2)
  13330. \end{lstlisting}
  13331. \fi}
  13332. {\if\edition\pythonEd
  13333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13334. def add(x:int, y:int) -> int:
  13335. return x + y
  13336. print(add(40, 2))
  13337. \end{lstlisting}
  13338. \fi}
  13339. $\Downarrow$
  13340. {\if\edition\racketEd
  13341. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13342. (define (add86 [x87 : Integer]
  13343. [y88 : Integer]) : Integer
  13344. add86start:
  13345. return (+ x87 y88);
  13346. )
  13347. (define (main) : Integer ()
  13348. mainstart:
  13349. tmp89 = (fun-ref add86 2);
  13350. (tail-call tmp89 40 2)
  13351. )
  13352. \end{lstlisting}
  13353. \fi}
  13354. {\if\edition\pythonEd
  13355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13356. def add(x:int, y:int) -> int:
  13357. addstart:
  13358. return x + y
  13359. def main() -> int:
  13360. mainstart:
  13361. fun.0 = add
  13362. tmp.1 = fun.0(40, 2)
  13363. print(tmp.1)
  13364. return 0
  13365. \end{lstlisting}
  13366. \fi}
  13367. \end{minipage}
  13368. &
  13369. $\Rightarrow$
  13370. \begin{minipage}{0.5\textwidth}
  13371. {\if\edition\racketEd
  13372. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13373. (define (add86) : Integer
  13374. add86start:
  13375. movq %rdi, x87
  13376. movq %rsi, y88
  13377. movq x87, %rax
  13378. addq y88, %rax
  13379. jmp inc1389conclusion
  13380. )
  13381. (define (main) : Integer
  13382. mainstart:
  13383. leaq (fun-ref add86 2), tmp89
  13384. movq $40, %rdi
  13385. movq $2, %rsi
  13386. tail-jmp tmp89
  13387. )
  13388. \end{lstlisting}
  13389. \fi}
  13390. {\if\edition\pythonEd
  13391. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13392. def add() -> int:
  13393. addstart:
  13394. movq %rdi, x
  13395. movq %rsi, y
  13396. movq x, %rax
  13397. addq y, %rax
  13398. jmp addconclusion
  13399. def main() -> int:
  13400. mainstart:
  13401. leaq add, fun.0
  13402. movq $40, %rdi
  13403. movq $2, %rsi
  13404. callq *fun.0
  13405. movq %rax, tmp.1
  13406. movq tmp.1, %rdi
  13407. callq print_int
  13408. movq $0, %rax
  13409. jmp mainconclusion
  13410. \end{lstlisting}
  13411. \fi}
  13412. $\Downarrow$
  13413. \end{minipage}
  13414. \end{tabular}
  13415. \begin{tabular}{ll}
  13416. \begin{minipage}{0.3\textwidth}
  13417. {\if\edition\racketEd
  13418. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13419. .globl add86
  13420. .align 16
  13421. add86:
  13422. pushq %rbp
  13423. movq %rsp, %rbp
  13424. jmp add86start
  13425. add86start:
  13426. movq %rdi, %rax
  13427. addq %rsi, %rax
  13428. jmp add86conclusion
  13429. add86conclusion:
  13430. popq %rbp
  13431. retq
  13432. \end{lstlisting}
  13433. \fi}
  13434. {\if\edition\pythonEd
  13435. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13436. .align 16
  13437. add:
  13438. pushq %rbp
  13439. movq %rsp, %rbp
  13440. subq $0, %rsp
  13441. jmp addstart
  13442. addstart:
  13443. movq %rdi, %rdx
  13444. movq %rsi, %rcx
  13445. movq %rdx, %rax
  13446. addq %rcx, %rax
  13447. jmp addconclusion
  13448. addconclusion:
  13449. subq $0, %r15
  13450. addq $0, %rsp
  13451. popq %rbp
  13452. retq
  13453. \end{lstlisting}
  13454. \fi}
  13455. \end{minipage}
  13456. &
  13457. \begin{minipage}{0.5\textwidth}
  13458. {\if\edition\racketEd
  13459. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13460. .globl main
  13461. .align 16
  13462. main:
  13463. pushq %rbp
  13464. movq %rsp, %rbp
  13465. movq $16384, %rdi
  13466. movq $16384, %rsi
  13467. callq initialize
  13468. movq rootstack_begin(%rip), %r15
  13469. jmp mainstart
  13470. mainstart:
  13471. leaq add86(%rip), %rcx
  13472. movq $40, %rdi
  13473. movq $2, %rsi
  13474. movq %rcx, %rax
  13475. popq %rbp
  13476. jmp *%rax
  13477. mainconclusion:
  13478. popq %rbp
  13479. retq
  13480. \end{lstlisting}
  13481. \fi}
  13482. {\if\edition\pythonEd
  13483. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13484. .globl main
  13485. .align 16
  13486. main:
  13487. pushq %rbp
  13488. movq %rsp, %rbp
  13489. subq $0, %rsp
  13490. movq $65536, %rdi
  13491. movq $65536, %rsi
  13492. callq initialize
  13493. movq rootstack_begin(%rip), %r15
  13494. jmp mainstart
  13495. mainstart:
  13496. leaq add(%rip), %rcx
  13497. movq $40, %rdi
  13498. movq $2, %rsi
  13499. callq *%rcx
  13500. movq %rax, %rcx
  13501. movq %rcx, %rdi
  13502. callq print_int
  13503. movq $0, %rax
  13504. jmp mainconclusion
  13505. mainconclusion:
  13506. subq $0, %r15
  13507. addq $0, %rsp
  13508. popq %rbp
  13509. retq
  13510. \end{lstlisting}
  13511. \fi}
  13512. \end{minipage}
  13513. \end{tabular}
  13514. \caption{Example compilation of a simple function to x86.}
  13515. \label{fig:add-fun}
  13516. \end{figure}
  13517. % Challenge idea: inlining! (simple version)
  13518. % Further Reading
  13519. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13520. \chapter{Lexically Scoped Functions}
  13521. \label{ch:Llambda}
  13522. \index{subject}{lambda}
  13523. \index{subject}{lexical scoping}
  13524. This chapter studies lexically scoped functions. Lexical scoping means
  13525. that a function's body may refer to variables whose binding site is
  13526. outside of the function, in an enclosing scope.
  13527. %
  13528. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13529. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13530. using the \key{lambda} form. The body of the \key{lambda} refers to
  13531. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13532. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13533. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13534. variable of function \code{f}} and \code{x} is a parameter of
  13535. function \code{f}. The \key{lambda} is returned from the function
  13536. \code{f}. The main expression of the program includes two calls to
  13537. \code{f} with different arguments for \code{x}, first \code{5} then
  13538. \code{3}. The functions returned from \code{f} are bound to variables
  13539. \code{g} and \code{h}. Even though these two functions were created by
  13540. the same \code{lambda}, they are really different functions because
  13541. they use different values for \code{x}. Applying \code{g} to \code{11}
  13542. produces \code{20} whereas applying \code{h} to \code{15} produces
  13543. \code{22}. The result of this program is \code{42}.
  13544. \begin{figure}[btp]
  13545. {\if\edition\racketEd
  13546. % lambda_test_21.rkt
  13547. \begin{lstlisting}
  13548. (define (f [x : Integer]) : (Integer -> Integer)
  13549. (let ([y 4])
  13550. (lambda: ([z : Integer]) : Integer
  13551. (+ x (+ y z)))))
  13552. (let ([g (f 5)])
  13553. (let ([h (f 3)])
  13554. (+ (g 11) (h 15))))
  13555. \end{lstlisting}
  13556. \fi}
  13557. {\if\edition\pythonEd
  13558. \begin{lstlisting}
  13559. def f(x : int) -> Callable[[int], int]:
  13560. y = 4
  13561. return lambda z: x + y + z
  13562. g = f(5)
  13563. h = f(3)
  13564. print( g(11) + h(15) )
  13565. \end{lstlisting}
  13566. \fi}
  13567. \caption{Example of a lexically scoped function.}
  13568. \label{fig:lexical-scoping}
  13569. \end{figure}
  13570. The approach that we take for implementing lexically scoped functions
  13571. is to compile them into top-level function definitions, translating
  13572. from \LangLam{} into \LangFun{}. However, the compiler must give
  13573. special treatment to variable occurrences such as \code{x} and
  13574. \code{y} in the body of the \code{lambda} of
  13575. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13576. may not refer to variables defined outside of it. To identify such
  13577. variable occurrences, we review the standard notion of free variable.
  13578. \begin{definition}
  13579. A variable is \textbf{free in expression} $e$ if the variable occurs
  13580. inside $e$ but does not have an enclosing definition that is also in
  13581. $e$.\index{subject}{free variable}
  13582. \end{definition}
  13583. For example, in the expression
  13584. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13585. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13586. only \code{x} and \code{y} are free in the following expression
  13587. because \code{z} is defined by the \code{lambda}.
  13588. {\if\edition\racketEd
  13589. \begin{lstlisting}
  13590. (lambda: ([z : Integer]) : Integer
  13591. (+ x (+ y z)))
  13592. \end{lstlisting}
  13593. \fi}
  13594. {\if\edition\pythonEd
  13595. \begin{lstlisting}
  13596. lambda z: x + y + z
  13597. \end{lstlisting}
  13598. \fi}
  13599. %
  13600. So the free variables of a \code{lambda} are the ones that need
  13601. special treatment. We need to transport, at runtime, the values of
  13602. those variables from the point where the \code{lambda} was created to
  13603. the point where the \code{lambda} is applied. An efficient solution to
  13604. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13605. of the free variables together with a function pointer into a tuple,
  13606. an arrangement called a \emph{flat closure} (which we shorten to just
  13607. ``closure''). \index{subject}{closure}\index{subject}{flat closure}
  13608. Fortunately, we have all the ingredients to make closures:
  13609. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13610. function pointers. The function pointer resides at index $0$ and the
  13611. values for the free variables fill in the rest of the tuple.
  13612. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13613. how closures work. It's a three-step dance. The program calls function
  13614. \code{f}, which creates a closure for the \code{lambda}. The closure
  13615. is a tuple whose first element is a pointer to the top-level function
  13616. that we will generate for the \code{lambda}, the second element is the
  13617. value of \code{x}, which is \code{5}, and the third element is
  13618. \code{4}, the value of \code{y}. The closure does not contain an
  13619. element for \code{z} because \code{z} is not a free variable of the
  13620. \code{lambda}. Creating the closure is step 1 of the dance. The
  13621. closure is returned from \code{f} and bound to \code{g}, as shown in
  13622. Figure~\ref{fig:closures}.
  13623. %
  13624. The second call to \code{f} creates another closure, this time with
  13625. \code{3} in the second slot (for \code{x}). This closure is also
  13626. returned from \code{f} but bound to \code{h}, which is also shown in
  13627. Figure~\ref{fig:closures}.
  13628. \begin{figure}[tbp]
  13629. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13630. \caption{Flat closure representations for the two functions
  13631. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13632. \label{fig:closures}
  13633. \end{figure}
  13634. Continuing with the example, consider the application of \code{g} to
  13635. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13636. obtain the function pointer in the first element of the closure and
  13637. call it, passing in the closure itself and then the regular arguments,
  13638. in this case \code{11}. This technique for applying a closure is step
  13639. 2 of the dance.
  13640. %
  13641. But doesn't this \code{lambda} only take 1 argument, for parameter
  13642. \code{z}? The third and final step of the dance is generating a
  13643. top-level function for a \code{lambda}. We add an additional
  13644. parameter for the closure and we insert an initialization at the beginning
  13645. of the function for each free variable, to bind those variables to the
  13646. appropriate elements from the closure parameter.
  13647. %
  13648. This three-step dance is known as \emph{closure conversion}. We
  13649. discuss the details of closure conversion in
  13650. Section~\ref{sec:closure-conversion} and the code generated from the
  13651. example in Section~\ref{sec:example-lambda}. But first we define the
  13652. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13653. \section{The \LangLam{} Language}
  13654. \label{sec:r5}
  13655. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13656. functions and lexical scoping, is defined in
  13657. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13658. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13659. syntax for function application.
  13660. %
  13661. \python{The syntax also includes an assignment statement that includes
  13662. a type annotation for the variable on the left-hand side, which
  13663. facilitates the type checking of \code{lambda} expressions that we
  13664. discuss later in this section.}
  13665. %
  13666. \python{The \code{arity} operation returns the number of parameters of
  13667. a given function, an operation that we need for the translation
  13668. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13669. The \code{arity} operation is not in Python, but the same functionality
  13670. is available in a more complex form. We include \code{arity} in the
  13671. \LangLam{} source language to enable testing.}
  13672. \newcommand{\LlambdaGrammarRacket}{
  13673. \begin{array}{lcl}
  13674. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13675. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13676. \end{array}
  13677. }
  13678. \newcommand{\LlambdaASTRacket}{
  13679. \begin{array}{lcl}
  13680. \itm{op} &::=& \code{procedure-arity} \\
  13681. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13682. \end{array}
  13683. }
  13684. \newcommand{\LlambdaGrammarPython}{
  13685. \begin{array}{lcl}
  13686. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13687. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13688. \end{array}
  13689. }
  13690. \newcommand{\LlambdaASTPython}{
  13691. \begin{array}{lcl}
  13692. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13693. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13694. \end{array}
  13695. }
  13696. % include AnnAssign in ASTPython
  13697. \begin{figure}[tp]
  13698. \centering
  13699. \fbox{
  13700. \begin{minipage}{0.96\textwidth}
  13701. \small
  13702. {\if\edition\racketEd
  13703. \[
  13704. \begin{array}{l}
  13705. \gray{\LintGrammarRacket{}} \\ \hline
  13706. \gray{\LvarGrammarRacket{}} \\ \hline
  13707. \gray{\LifGrammarRacket{}} \\ \hline
  13708. \gray{\LwhileGrammarRacket} \\ \hline
  13709. \gray{\LtupGrammarRacket} \\ \hline
  13710. \gray{\LfunGrammarRacket} \\ \hline
  13711. \LlambdaGrammarRacket \\
  13712. \begin{array}{lcl}
  13713. \LangLamM{} &::=& \Def\ldots \; \Exp
  13714. \end{array}
  13715. \end{array}
  13716. \]
  13717. \fi}
  13718. {\if\edition\pythonEd
  13719. \[
  13720. \begin{array}{l}
  13721. \gray{\LintGrammarPython{}} \\ \hline
  13722. \gray{\LvarGrammarPython{}} \\ \hline
  13723. \gray{\LifGrammarPython{}} \\ \hline
  13724. \gray{\LwhileGrammarPython} \\ \hline
  13725. \gray{\LtupGrammarPython} \\ \hline
  13726. \gray{\LfunGrammarPython} \\ \hline
  13727. \LlambdaGrammarPython \\
  13728. \begin{array}{lcl}
  13729. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13730. \end{array}
  13731. \end{array}
  13732. \]
  13733. \fi}
  13734. \end{minipage}
  13735. }
  13736. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13737. with \key{lambda}.}
  13738. \label{fig:Rlam-concrete-syntax}
  13739. \end{figure}
  13740. \begin{figure}[tp]
  13741. \centering
  13742. \fbox{
  13743. \begin{minipage}{0.96\textwidth}
  13744. \small
  13745. {\if\edition\racketEd
  13746. \[
  13747. \begin{array}{l}
  13748. \gray{\LintOpAST} \\ \hline
  13749. \gray{\LvarASTRacket{}} \\ \hline
  13750. \gray{\LifASTRacket{}} \\ \hline
  13751. \gray{\LwhileASTRacket{}} \\ \hline
  13752. \gray{\LtupASTRacket{}} \\ \hline
  13753. \gray{\LfunASTRacket} \\ \hline
  13754. \LlambdaASTRacket \\
  13755. \begin{array}{lcl}
  13756. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13757. \end{array}
  13758. \end{array}
  13759. \]
  13760. \fi}
  13761. {\if\edition\pythonEd
  13762. \[
  13763. \begin{array}{l}
  13764. \gray{\LintASTPython} \\ \hline
  13765. \gray{\LvarASTPython{}} \\ \hline
  13766. \gray{\LifASTPython{}} \\ \hline
  13767. \gray{\LwhileASTPython{}} \\ \hline
  13768. \gray{\LtupASTPython{}} \\ \hline
  13769. \gray{\LfunASTPython} \\ \hline
  13770. \LlambdaASTPython \\
  13771. \begin{array}{lcl}
  13772. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13773. \end{array}
  13774. \end{array}
  13775. \]
  13776. \fi}
  13777. \end{minipage}
  13778. }
  13779. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13780. \label{fig:Rlam-syntax}
  13781. \end{figure}
  13782. \index{subject}{interpreter}
  13783. \label{sec:interp-Rlambda}
  13784. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13785. \LangLam{}. The case for \key{Lambda} saves the current environment
  13786. inside the returned function value. Recall that during function
  13787. application, the environment stored in the function value, extended
  13788. with the mapping of parameters to argument values, is used to
  13789. interpret the body of the function.
  13790. \begin{figure}[tbp]
  13791. {\if\edition\racketEd
  13792. \begin{lstlisting}
  13793. (define interp-Rlambda_class
  13794. (class interp-Rfun_class
  13795. (super-new)
  13796. (define/override (interp-op op)
  13797. (match op
  13798. ['procedure-arity
  13799. (lambda (v)
  13800. (match v
  13801. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13802. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13803. [else (super interp-op op)]))
  13804. (define/override ((interp-exp env) e)
  13805. (define recur (interp-exp env))
  13806. (match e
  13807. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13808. `(function ,xs ,body ,env)]
  13809. [else ((super interp-exp env) e)]))
  13810. ))
  13811. (define (interp-Rlambda p)
  13812. (send (new interp-Rlambda_class) interp-program p))
  13813. \end{lstlisting}
  13814. \fi}
  13815. {\if\edition\pythonEd
  13816. \begin{lstlisting}
  13817. class InterpLlambda(InterpLfun):
  13818. def arity(self, v):
  13819. match v:
  13820. case Function(name, params, body, env):
  13821. return len(params)
  13822. case _:
  13823. raise Exception('Llambda arity unexpected ' + repr(v))
  13824. def interp_exp(self, e, env):
  13825. match e:
  13826. case Call(Name('arity'), [fun]):
  13827. f = self.interp_exp(fun, env)
  13828. return self.arity(f)
  13829. case Lambda(params, body):
  13830. return Function('lambda', params, [Return(body)], env)
  13831. case _:
  13832. return super().interp_exp(e, env)
  13833. def interp_stmts(self, ss, env):
  13834. if len(ss) == 0:
  13835. return
  13836. match ss[0]:
  13837. case AnnAssign(lhs, typ, value, simple):
  13838. env[lhs.id] = self.interp_exp(value, env)
  13839. return self.interp_stmts(ss[1:], env)
  13840. case _:
  13841. return super().interp_stmts(ss, env)
  13842. \end{lstlisting}
  13843. \fi}
  13844. \caption{Interpreter for \LangLam{}.}
  13845. \label{fig:interp-Rlambda}
  13846. \end{figure}
  13847. \label{sec:type-check-r5}
  13848. \index{subject}{type checking}
  13849. {\if\edition\racketEd
  13850. %
  13851. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13852. \key{lambda} form. The body of the \key{lambda} is checked in an
  13853. environment that includes the current environment (because it is
  13854. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13855. require the body's type to match the declared return type.
  13856. %
  13857. \fi}
  13858. {\if\edition\pythonEd
  13859. %
  13860. Figures~\ref{fig:type-check-Llambda} and
  13861. \ref{fig:type-check-Llambda-part2} define the type checker for
  13862. \LangLam{}, which is more complex than one might expect. The reason
  13863. for the added complexity is that the syntax of \key{lambda} does not
  13864. include type annotations for the parameters or return type. Instead
  13865. they must be inferred. There are many approaches of type inference to
  13866. choose from of varying degrees of complexity. We choose one of the
  13867. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13868. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13869. this book is compilation, not type inference.
  13870. The main idea of bidirectional type inference is to add an auxilliary
  13871. function, here named \code{check\_exp}, that takes an expected type
  13872. and checks whether the given expression is of that type. Thus, in
  13873. \code{check\_exp}, type information flows in a top-down manner with
  13874. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13875. function, where type information flows in a primarily bottom-up
  13876. manner.
  13877. %
  13878. The idea then is to use \code{check\_exp} in all the places where we
  13879. already know what the type of an expression should be, such as in the
  13880. \code{return} statement of a top-level function definition, or on the
  13881. right-hand side of an annotated assignment statement.
  13882. Getting back to \code{lambda}, it is straightforward to check a
  13883. \code{lambda} inside \code{check\_exp} because the expected type
  13884. provides the parameter types and the return type. On the other hand,
  13885. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13886. that we do not allow \code{lambda} in contexts where we don't already
  13887. know its type. This restriction does not incur a loss of
  13888. expressiveness for \LangLam{} because it is straightforward to modify
  13889. a program to sidestep the restriction, for example, by using an
  13890. annotated assignment statement to assign the \code{lambda} to a
  13891. temporary variable.
  13892. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13893. checker records their type in a \code{has\_type} field. This type
  13894. information is used later in this chapter.
  13895. %
  13896. \fi}
  13897. \begin{figure}[tbp]
  13898. {\if\edition\racketEd
  13899. \begin{lstlisting}
  13900. (define (type-check-Rlambda env)
  13901. (lambda (e)
  13902. (match e
  13903. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13904. (define-values (new-body bodyT)
  13905. ((type-check-exp (append (map cons xs Ts) env)) body))
  13906. (define ty `(,@Ts -> ,rT))
  13907. (cond
  13908. [(equal? rT bodyT)
  13909. (values (HasType (Lambda params rT new-body) ty) ty)]
  13910. [else
  13911. (error "mismatch in return type" bodyT rT)])]
  13912. ...
  13913. )))
  13914. \end{lstlisting}
  13915. \fi}
  13916. {\if\edition\pythonEd
  13917. \begin{lstlisting}
  13918. class TypeCheckLlambda(TypeCheckLfun):
  13919. def type_check_exp(self, e, env):
  13920. match e:
  13921. case Name(id):
  13922. e.has_type = env[id]
  13923. return env[id]
  13924. case Lambda(params, body):
  13925. raise Exception('cannot synthesize a type for a lambda')
  13926. case Call(Name('arity'), [func]):
  13927. func_t = self.type_check_exp(func, env)
  13928. match func_t:
  13929. case FunctionType(params_t, return_t):
  13930. return IntType()
  13931. case _:
  13932. raise Exception('in arity, unexpected ' + repr(func_t))
  13933. case _:
  13934. return super().type_check_exp(e, env)
  13935. def check_exp(self, e, ty, env):
  13936. match e:
  13937. case Lambda(params, body):
  13938. e.has_type = ty
  13939. match ty:
  13940. case FunctionType(params_t, return_t):
  13941. new_env = env.copy().update(zip(params, params_t))
  13942. self.check_exp(body, return_t, new_env)
  13943. case _:
  13944. raise Exception('lambda does not have type ' + str(ty))
  13945. case Call(func, args):
  13946. func_t = self.type_check_exp(func, env)
  13947. match func_t:
  13948. case FunctionType(params_t, return_t):
  13949. for (arg, param_t) in zip(args, params_t):
  13950. self.check_exp(arg, param_t, env)
  13951. self.check_type_equal(return_t, ty, e)
  13952. case _:
  13953. raise Exception('type_check_exp: in call, unexpected ' + \
  13954. repr(func_t))
  13955. case _:
  13956. t = self.type_check_exp(e, env)
  13957. self.check_type_equal(t, ty, e)
  13958. \end{lstlisting}
  13959. \fi}
  13960. \caption{Type checking \LangLam{}\python{, part 1}.}
  13961. \label{fig:type-check-Llambda}
  13962. \end{figure}
  13963. {\if\edition\pythonEd
  13964. \begin{figure}[tbp]
  13965. \begin{lstlisting}
  13966. def check_stmts(self, ss, return_ty, env):
  13967. if len(ss) == 0:
  13968. return
  13969. match ss[0]:
  13970. case FunctionDef(name, params, body, dl, returns, comment):
  13971. new_env = env.copy().update(params)
  13972. rt = self.check_stmts(body, returns, new_env)
  13973. self.check_stmts(ss[1:], return_ty, env)
  13974. case Return(value):
  13975. self.check_exp(value, return_ty, env)
  13976. case Assign([Name(id)], value):
  13977. if id in env:
  13978. self.check_exp(value, env[id], env)
  13979. else:
  13980. env[id] = self.type_check_exp(value, env)
  13981. self.check_stmts(ss[1:], return_ty, env)
  13982. case Assign([Subscript(tup, Constant(index), Store())], value):
  13983. tup_t = self.type_check_exp(tup, env)
  13984. match tup_t:
  13985. case TupleType(ts):
  13986. self.check_exp(value, ts[index], env)
  13987. case _:
  13988. raise Exception('expected a tuple, not ' + repr(tup_t))
  13989. self.check_stmts(ss[1:], return_ty, env)
  13990. case AnnAssign(Name(id), ty, value, simple):
  13991. ss[0].annotation = ty_annot
  13992. if id in env:
  13993. self.check_type_equal(env[id], ty)
  13994. else:
  13995. env[id] = ty_annot
  13996. self.check_exp(value, ty_annot, env)
  13997. case _:
  13998. self.type_check_stmts(ss, env)
  13999. def type_check(self, p):
  14000. match p:
  14001. case Module(body):
  14002. env = {}
  14003. for s in body:
  14004. match s:
  14005. case FunctionDef(name, params, bod, dl, returns, comment):
  14006. params_t = [t for (x,t) in params]
  14007. env[name] = FunctionType(params_t, returns)
  14008. self.check_stmts(body, int, env)
  14009. \end{lstlisting}
  14010. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14011. \label{fig:type-check-Llambda-part2}
  14012. \end{figure}
  14013. \fi}
  14014. \clearpage
  14015. \section{Assignment and Lexically Scoped Functions}
  14016. \label{sec:assignment-scoping}
  14017. The combination of lexically-scoped functions and assignment to
  14018. variables raises a challenge with our approach to implementing
  14019. lexically-scoped functions. Consider the following example in which
  14020. function \code{f} has a free variable \code{x} that is changed after
  14021. \code{f} is created but before the call to \code{f}.
  14022. % loop_test_11.rkt
  14023. {\if\edition\racketEd
  14024. \begin{lstlisting}
  14025. (let ([x 0])
  14026. (let ([y 0])
  14027. (let ([z 20])
  14028. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14029. (begin
  14030. (set! x 10)
  14031. (set! y 12)
  14032. (f y))))))
  14033. \end{lstlisting}
  14034. \fi}
  14035. {\if\edition\pythonEd
  14036. % box_free_assign.py
  14037. \begin{lstlisting}
  14038. def g(z : int) -> int:
  14039. x = 0
  14040. y = 0
  14041. f : Callable[[int],int] = lambda a: a + x + z
  14042. x = 10
  14043. y = 12
  14044. return f(y)
  14045. print( g(20) )
  14046. \end{lstlisting}
  14047. \fi}
  14048. The correct output for this example is \code{42} because the call to
  14049. \code{f} is required to use the current value of \code{x} (which is
  14050. \code{10}). Unfortunately, the closure conversion pass
  14051. (Section~\ref{sec:closure-conversion}) generates code for the
  14052. \code{lambda} that copies the old value of \code{x} into a
  14053. closure. Thus, if we naively add support for assignment to our current
  14054. compiler, the output of this program would be \code{32}.
  14055. A first attempt at solving this problem would be to save a pointer to
  14056. \code{x} in the closure and change the occurrences of \code{x} inside
  14057. the lambda to dereference the pointer. Of course, this would require
  14058. assigning \code{x} to the stack and not to a register. However, the
  14059. problem goes a bit deeper.
  14060. %% Consider the following example in which we
  14061. %% create a counter abstraction by creating a pair of functions that
  14062. %% share the free variable \code{x}.
  14063. Consider the following example that returns a function that refers to
  14064. a local variable of the enclosing function.
  14065. \begin{center}
  14066. \begin{minipage}{\textwidth}
  14067. {\if\edition\racketEd
  14068. % similar to loop_test_10.rkt
  14069. %% \begin{lstlisting}
  14070. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  14071. %% (vector
  14072. %% (lambda: () : Integer x)
  14073. %% (lambda: () : Void (set! x (+ 1 x)))))
  14074. %% (let ([counter (f 0)])
  14075. %% (let ([get (vector-ref counter 0)])
  14076. %% (let ([inc (vector-ref counter 1)])
  14077. %% (begin
  14078. %% (inc)
  14079. %% (get)))))
  14080. %% \end{lstlisting}
  14081. \begin{lstlisting}
  14082. (define (f []) : Integer
  14083. (let ([x 0])
  14084. (let ([g (lambda: () : Integer x)])
  14085. (begin
  14086. (set! x 42)
  14087. g))))
  14088. ((f))
  14089. \end{lstlisting}
  14090. \fi}
  14091. {\if\edition\pythonEd
  14092. % counter.py
  14093. \begin{lstlisting}
  14094. def f():
  14095. x = 0
  14096. g = lambda: x
  14097. x = 42
  14098. return g
  14099. print( f()() )
  14100. \end{lstlisting}
  14101. \fi}
  14102. \end{minipage}
  14103. \end{center}
  14104. In this example, the lifetime of \code{x} extends beyond the lifetime
  14105. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14106. stack frame for the call to \code{f}, it would be gone by the time we
  14107. call \code{g}, leaving us with dangling pointers for
  14108. \code{x}. This example demonstrates that when a variable occurs free
  14109. inside a function, its lifetime becomes indefinite. Thus, the value of
  14110. the variable needs to live on the heap. The verb
  14111. \emph{box}\index{subject}{box} is often used for allocating a single
  14112. value on the heap, producing a pointer, and
  14113. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14114. %% {\if\edition\racketEd
  14115. %% We recommend solving these problems by boxing the local variables that
  14116. %% are in the intersection of 1) variables that appear on the
  14117. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14118. %% inside a \code{lambda}.
  14119. %% \fi}
  14120. %% {\if\edition\pythonEd
  14121. %% We recommend solving these problems by boxing the local variables that
  14122. %% are in the intersection of 1) variables whose values may change and 2)
  14123. %% variables that occur free inside a \code{lambda}.
  14124. %% \fi}
  14125. We shall introduce a new pass named
  14126. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14127. to address this challenge.
  14128. %
  14129. \racket{But before diving into the compiler passes, we have one more
  14130. problem to discuss.}
  14131. \if\edition\pythonEd
  14132. \section{Uniquify Variables}
  14133. \label{sec:uniquify-lambda}
  14134. With the addition of \code{lambda} we have a complication to deal
  14135. with: name shadowing. Consider the following program with a function
  14136. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14137. \code{lambda} expressions. The first \code{lambda} has a parameter
  14138. that is also named \code{x}.
  14139. \begin{lstlisting}
  14140. def f(x:int, y:int) -> Callable[[int], int]:
  14141. g : Callable[[int],int] = (lambda x: x + y)
  14142. h : Callable[[int],int] = (lambda y: x + y)
  14143. x = input_int()
  14144. return g
  14145. print(f(0, 10)(32))
  14146. \end{lstlisting}
  14147. Many of our compiler passes rely on being able to connect variable
  14148. uses with their definitions using just the name of the variable,
  14149. including new passes in this chapter. However, in the above example
  14150. the name of the variable does not uniquely determine its
  14151. definition. To solve this problem we recommend implementing a pass
  14152. named \code{uniquify} that renames every variable in the program to
  14153. make sure they are all unique.
  14154. The following shows the result of \code{uniquify} for the above
  14155. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14156. and the \code{x} parameter of the \code{lambda} is renamed to
  14157. \code{x\_4}.
  14158. \begin{lstlisting}
  14159. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14160. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14161. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14162. x_0 = input_int()
  14163. return g_2
  14164. def main() -> int :
  14165. print(f(0, 10)(32))
  14166. return 0
  14167. \end{lstlisting}
  14168. \fi
  14169. %% \section{Reveal Functions}
  14170. %% \label{sec:reveal-functions-r5}
  14171. %% \racket{To support the \code{procedure-arity} operator we need to
  14172. %% communicate the arity of a function to the point of closure
  14173. %% creation.}
  14174. %% %
  14175. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14176. %% function at runtime. Thus, we need to communicate the arity of a
  14177. %% function to the point of closure creation.}
  14178. %% %
  14179. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14180. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14181. %% \[
  14182. %% \begin{array}{lcl}
  14183. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14184. %% \end{array}
  14185. %% \]
  14186. \section{Assignment Conversion}
  14187. \label{sec:convert-assignments}
  14188. The purpose of the \code{convert\_assignments} pass is to address the
  14189. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14190. interaction between variable assignments and closure conversion.
  14191. First we identify which variables need to be boxed, then we transform
  14192. the program to box those variables. In general, boxing introduces
  14193. runtime overhead that we would like to avoid, so we should box as few
  14194. variables as possible. We recommend boxing the variables in the
  14195. intersection of the following two sets of variables:
  14196. \begin{enumerate}
  14197. \item The variables that are free in a \code{lambda}.
  14198. \item The variables that appear on the left-hand side of an
  14199. assignment.
  14200. \end{enumerate}
  14201. The first condition is a must, but the second condition is quite conservative and it is possible to
  14202. develop a more liberal condition.
  14203. Consider again the first example from
  14204. Section~\ref{sec:assignment-scoping}:
  14205. %
  14206. {\if\edition\racketEd
  14207. \begin{lstlisting}
  14208. (let ([x 0])
  14209. (let ([y 0])
  14210. (let ([z 20])
  14211. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14212. (begin
  14213. (set! x 10)
  14214. (set! y 12)
  14215. (f y))))))
  14216. \end{lstlisting}
  14217. \fi}
  14218. {\if\edition\pythonEd
  14219. \begin{lstlisting}
  14220. def g(z : int) -> int:
  14221. x = 0
  14222. y = 0
  14223. f : Callable[[int],int] = lambda a: a + x + z
  14224. x = 10
  14225. y = 12
  14226. return f(y)
  14227. print( g(20) )
  14228. \end{lstlisting}
  14229. \fi}
  14230. %
  14231. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14232. variables \code{x} and \code{z} occur free inside the
  14233. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14234. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14235. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14236. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14237. with a tuple write. The output of \code{convert\_assignments} for
  14238. this example is as follows.
  14239. %
  14240. {\if\edition\racketEd
  14241. \begin{lstlisting}
  14242. (define (main) : Integer
  14243. (let ([x0 (vector 0)])
  14244. (let ([y1 0])
  14245. (let ([z2 20])
  14246. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14247. (+ a3 (+ (vector-ref x0 0) z2)))])
  14248. (begin
  14249. (vector-set! x0 0 10)
  14250. (set! y1 12)
  14251. (f4 y1)))))))
  14252. \end{lstlisting}
  14253. \fi}
  14254. %
  14255. {\if\edition\pythonEd
  14256. \begin{lstlisting}
  14257. def g(z : int)-> int:
  14258. x = (uninitialized(int),)
  14259. x[0] = 0
  14260. y = 0
  14261. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14262. x[0] = 10
  14263. y = 12
  14264. return f(y)
  14265. def main() -> int:
  14266. print(g(20))
  14267. return 0
  14268. \end{lstlisting}
  14269. \fi}
  14270. To compute the free variables of all the \code{lambda} expressions, we
  14271. recommend defining two auxiliary functions:
  14272. \begin{enumerate}
  14273. \item \code{free\_variables} computes the free variables of an expression, and
  14274. \item \code{free\_in\_lambda} collects all of the variables that are
  14275. free in any of the \code{lambda} expressions, using
  14276. \code{free\_variables} in the case for each \code{lambda}.
  14277. \end{enumerate}
  14278. {\if\edition\racketEd
  14279. %
  14280. To compute the variables that are assigned-to, we recommend using the
  14281. \code{collect-set!} function that we introduced in
  14282. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14283. forms such as \code{Lambda}.
  14284. %
  14285. \fi}
  14286. {\if\edition\pythonEd
  14287. %
  14288. To compute the variables that are assigned-to, we recommend defining
  14289. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14290. the set of variables that occur in the left-hand side of an assignment
  14291. statement, and otherwise returns the empty set.
  14292. %
  14293. \fi}
  14294. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14295. free in a \code{lambda} and that are assigned-to in the enclosing
  14296. function definition.
  14297. Next we discuss the \code{convert\_assignments} pass. In the case for
  14298. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14299. $\VAR{x}$ to a tuple read.
  14300. %
  14301. {\if\edition\racketEd
  14302. \begin{lstlisting}
  14303. (Var |$x$|)
  14304. |$\Rightarrow$|
  14305. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14306. \end{lstlisting}
  14307. \fi}
  14308. %
  14309. {\if\edition\pythonEd
  14310. \begin{lstlisting}
  14311. Name(|$x$|)
  14312. |$\Rightarrow$|
  14313. Subscript(Name(|$x$|), Constant(0), Load())
  14314. \end{lstlisting}
  14315. \fi}
  14316. %
  14317. %
  14318. In the case for assignment, recursively process the right-hand side
  14319. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14320. the assignment into a tuple-write as follows.
  14321. %
  14322. {\if\edition\racketEd
  14323. \begin{lstlisting}
  14324. (SetBang |$x$| |$\itm{rhs}$|)
  14325. |$\Rightarrow$|
  14326. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14327. \end{lstlisting}
  14328. \fi}
  14329. {\if\edition\pythonEd
  14330. \begin{lstlisting}
  14331. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14332. |$\Rightarrow$|
  14333. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14334. \end{lstlisting}
  14335. \fi}
  14336. %
  14337. {\if\edition\racketEd
  14338. The case for \code{Lambda} is non-trivial, but it is similar to the
  14339. case for function definitions, which we discuss next.
  14340. \fi}
  14341. To translate a function definition, we first compute $\mathit{AF}$,
  14342. the intersection of the variables that are free in a \code{lambda} and
  14343. that are assigned-to. We then apply assignment conversion to the body
  14344. of the function definition. Finally, we box the parameters of this
  14345. function definition that are in $\mathit{AF}$. For example,
  14346. the parameter \code{x} of the following function \code{g}
  14347. needs to be boxed.
  14348. {\if\edition\racketEd
  14349. \begin{lstlisting}
  14350. (define (g [x : Integer]) : Integer
  14351. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14352. (begin
  14353. (set! x 10)
  14354. (f 32))))
  14355. \end{lstlisting}
  14356. \fi}
  14357. %
  14358. {\if\edition\pythonEd
  14359. \begin{lstlisting}
  14360. def g(x : int) -> int:
  14361. f : Callable[[int],int] = lambda a: a + x
  14362. x = 10
  14363. return f(32)
  14364. \end{lstlisting}
  14365. \fi}
  14366. %
  14367. \noindent We box parameter \code{x} by creating a local variable named
  14368. \code{x} that is initialized to a tuple whose contents is the value of
  14369. the parameter, which we has been renamed.
  14370. %
  14371. {\if\edition\racketEd
  14372. \begin{lstlisting}
  14373. (define (g [x_0 : Integer]) : Integer
  14374. (let ([x (vector x_0)])
  14375. (let ([f (lambda: ([a : Integer]) : Integer
  14376. (+ a (vector-ref x 0)))])
  14377. (begin
  14378. (vector-set! x 0 10)
  14379. (f 32)))))
  14380. \end{lstlisting}
  14381. \fi}
  14382. %
  14383. {\if\edition\pythonEd
  14384. \begin{lstlisting}
  14385. def g(x_0 : int)-> int:
  14386. x = (x_0,)
  14387. f : Callable[[int], int] = (lambda a: a + x[0])
  14388. x[0] = 10
  14389. return f(32)
  14390. \end{lstlisting}
  14391. \fi}
  14392. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14393. %% involving a counter abstraction. The following is the output of
  14394. %% assignment version for function \code{f}.
  14395. %% \begin{lstlisting}
  14396. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14397. %% (vector
  14398. %% (lambda: () : Integer x1)
  14399. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14400. %% |$\Rightarrow$|
  14401. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14402. %% (let ([x1 (vector param_x1)])
  14403. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14404. %% (lambda: () : Void
  14405. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14406. %% \end{lstlisting}
  14407. \section{Closure Conversion}
  14408. \label{sec:closure-conversion}
  14409. \index{subject}{closure conversion}
  14410. The compiling of lexically-scoped functions into top-level function
  14411. definitions is accomplished in the pass \code{convert\_to\_closures}
  14412. that comes after \code{reveal\_functions} and before
  14413. \code{limit\_functions}.
  14414. As usual, we implement the pass as a recursive function over the
  14415. AST. The interesting cases are the ones for \key{lambda} and function
  14416. application. We transform a \key{lambda} expression into an expression
  14417. that creates a closure, that is, a tuple whose first element is a
  14418. function pointer and the rest of the elements are the values of the
  14419. free variables of the \key{lambda}.
  14420. %
  14421. However, we use the \code{Closure} AST node instead of using a tuple
  14422. so that we can record the arity.
  14423. %
  14424. In the generated code below, \itm{fvs} is the free variables of the
  14425. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14426. %
  14427. \racket{The \itm{arity} is the number of parameters (the length of
  14428. \itm{ps}).}
  14429. %
  14430. {\if\edition\racketEd
  14431. \begin{lstlisting}
  14432. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14433. |$\Rightarrow$|
  14434. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14435. \end{lstlisting}
  14436. \fi}
  14437. %
  14438. {\if\edition\pythonEd
  14439. \begin{lstlisting}
  14440. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14441. |$\Rightarrow$|
  14442. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14443. \end{lstlisting}
  14444. \fi}
  14445. %
  14446. In addition to transforming each \key{Lambda} AST node into a
  14447. tuple, we create a top-level function definition for each
  14448. \key{Lambda}, as shown below.\\
  14449. \begin{minipage}{0.8\textwidth}
  14450. {\if\edition\racketEd
  14451. \begin{lstlisting}
  14452. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14453. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14454. ...
  14455. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14456. |\itm{body'}|)...))
  14457. \end{lstlisting}
  14458. \fi}
  14459. {\if\edition\pythonEd
  14460. \begin{lstlisting}
  14461. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14462. |$\itm{fvs}_1$| = clos[1]
  14463. |$\ldots$|
  14464. |$\itm{fvs}_n$| = clos[|$n$|]
  14465. |\itm{body'}|
  14466. \end{lstlisting}
  14467. \fi}
  14468. \end{minipage}\\
  14469. The \code{clos} parameter refers to the closure. Translate the type
  14470. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14471. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14472. \itm{closTy} is a tuple type whose first element type is
  14473. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14474. the element types are the types of the free variables in the
  14475. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14476. is non-trivial to give a type to the function in the closure's type.%
  14477. %
  14478. \footnote{To give an accurate type to a closure, we would need to add
  14479. existential types to the type checker~\citep{Minamide:1996ys}.}
  14480. %
  14481. %% The dummy type is considered to be equal to any other type during type
  14482. %% checking.
  14483. The free variables become local variables that are initialized with
  14484. their values in the closure.
  14485. Closure conversion turns every function into a tuple, so the type
  14486. annotations in the program must also be translated. We recommend
  14487. defining an auxiliary recursive function for this purpose. Function
  14488. types should be translated as follows.
  14489. %
  14490. {\if\edition\racketEd
  14491. \begin{lstlisting}
  14492. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14493. |$\Rightarrow$|
  14494. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14495. \end{lstlisting}
  14496. \fi}
  14497. {\if\edition\pythonEd
  14498. \begin{lstlisting}
  14499. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14500. |$\Rightarrow$|
  14501. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14502. \end{lstlisting}
  14503. \fi}
  14504. %
  14505. The above type says that the first thing in the tuple is a
  14506. function. The first parameter of the function is a tuple (a closure)
  14507. and the rest of the parameters are the ones from the original
  14508. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14509. omits the types of the free variables because 1) those types are not
  14510. available in this context and 2) we do not need them in the code that
  14511. is generated for function application. So this type only describes the
  14512. first component of the closure tuple. At runtime the tuple may have
  14513. more components, but we ignore them at this point.
  14514. We transform function application into code that retrieves the
  14515. function from the closure and then calls the function, passing the
  14516. closure as the first argument. We place $e'$ in a temporary variable
  14517. to avoid code duplication.
  14518. \begin{center}
  14519. \begin{minipage}{\textwidth}
  14520. {\if\edition\racketEd
  14521. \begin{lstlisting}
  14522. (Apply |$e$| |$\itm{es}$|)
  14523. |$\Rightarrow$|
  14524. (Let |$\itm{tmp}$| |$e'$|
  14525. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14526. \end{lstlisting}
  14527. \fi}
  14528. %
  14529. {\if\edition\pythonEd
  14530. \begin{lstlisting}
  14531. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14532. |$\Rightarrow$|
  14533. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14534. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14535. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14536. \end{lstlisting}
  14537. \fi}
  14538. \end{minipage}
  14539. \end{center}
  14540. There is also the question of what to do with references to top-level
  14541. function definitions. To maintain a uniform translation of function
  14542. application, we turn function references into closures.
  14543. \begin{tabular}{lll}
  14544. \begin{minipage}{0.3\textwidth}
  14545. {\if\edition\racketEd
  14546. \begin{lstlisting}
  14547. (FunRefArity |$f$| |$n$|)
  14548. \end{lstlisting}
  14549. \fi}
  14550. {\if\edition\pythonEd
  14551. \begin{lstlisting}
  14552. FunRefArity(|$f$|, |$n$|)
  14553. \end{lstlisting}
  14554. \fi}
  14555. \end{minipage}
  14556. &
  14557. $\Rightarrow$
  14558. &
  14559. \begin{minipage}{0.5\textwidth}
  14560. {\if\edition\racketEd
  14561. \begin{lstlisting}
  14562. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14563. \end{lstlisting}
  14564. \fi}
  14565. {\if\edition\pythonEd
  14566. \begin{lstlisting}
  14567. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14568. \end{lstlisting}
  14569. \fi}
  14570. \end{minipage}
  14571. \end{tabular} \\
  14572. We no longer need the annotated assignment statement \code{AnnAssign}
  14573. to support the type checking of \code{lambda} expressions, so we
  14574. translate it to a regular \code{Assign} statement.
  14575. The top-level function definitions need to be updated to take an extra
  14576. closure parameter.
  14577. \section{An Example Translation}
  14578. \label{sec:example-lambda}
  14579. Figure~\ref{fig:lexical-functions-example} shows the result of
  14580. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14581. program demonstrating lexical scoping that we discussed at the
  14582. beginning of this chapter.
  14583. \begin{figure}[tbp]
  14584. \begin{minipage}{0.8\textwidth}
  14585. {\if\edition\racketEd
  14586. % tests/lambda_test_6.rkt
  14587. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14588. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14589. (let ([y8 4])
  14590. (lambda: ([z9 : Integer]) : Integer
  14591. (+ x7 (+ y8 z9)))))
  14592. (define (main) : Integer
  14593. (let ([g0 ((fun-ref f6 1) 5)])
  14594. (let ([h1 ((fun-ref f6 1) 3)])
  14595. (+ (g0 11) (h1 15)))))
  14596. \end{lstlisting}
  14597. $\Rightarrow$
  14598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14599. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14600. (let ([y8 4])
  14601. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14602. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14603. (let ([x7 (vector-ref fvs3 1)])
  14604. (let ([y8 (vector-ref fvs3 2)])
  14605. (+ x7 (+ y8 z9)))))
  14606. (define (main) : Integer
  14607. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14608. ((vector-ref clos5 0) clos5 5))])
  14609. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14610. ((vector-ref clos6 0) clos6 3))])
  14611. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14612. \end{lstlisting}
  14613. \fi}
  14614. %
  14615. {\if\edition\pythonEd
  14616. % free_var.py
  14617. \begin{lstlisting}
  14618. def f(x : int) -> Callable[[int], int]:
  14619. y = 4
  14620. return lambda z: x + y + z
  14621. g = f(5)
  14622. h = f(3)
  14623. print( g(11) + h(15) )
  14624. \end{lstlisting}
  14625. $\Rightarrow$
  14626. \begin{lstlisting}
  14627. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14628. x = fvs_1[1]
  14629. y = fvs_1[2]
  14630. return x + y[0] + z
  14631. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14632. y = (777,)
  14633. y[0] = 4
  14634. return (lambda_0, x, y)
  14635. def main() -> int:
  14636. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14637. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14638. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14639. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14640. return 0
  14641. \end{lstlisting}
  14642. \fi}
  14643. \end{minipage}
  14644. \caption{Example of closure conversion.}
  14645. \label{fig:lexical-functions-example}
  14646. \end{figure}
  14647. \begin{exercise}\normalfont
  14648. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14649. Create 5 new programs that use \key{lambda} functions and make use of
  14650. lexical scoping. Test your compiler on these new programs and all of
  14651. your previously created test programs.
  14652. \end{exercise}
  14653. \section{Expose Allocation}
  14654. \label{sec:expose-allocation-r5}
  14655. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14656. that allocates and initializes a tuple, similar to the translation of
  14657. the tuple creation in Section~\ref{sec:expose-allocation}.
  14658. The only difference is replacing the use of
  14659. \ALLOC{\itm{len}}{\itm{type}} with
  14660. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14661. \section{Explicate Control and \LangCLam{}}
  14662. \label{sec:explicate-r5}
  14663. The output language of \code{explicate\_control} is \LangCLam{} whose
  14664. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14665. %
  14666. \racket{The only difference with respect to \LangCFun{} is the
  14667. addition of the \code{AllocateClosure} form to the grammar for
  14668. $\Exp$. The handling of \code{AllocateClosure} in the
  14669. \code{explicate\_control} pass is similar to the handling of other
  14670. expressions such as primitive operators.}
  14671. %
  14672. \python{The differences with respect to \LangCFun{} are the
  14673. additions of \code{Uninitialized}, \code{AllocateClosure},
  14674. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14675. \code{explicate\_control} pass is similar to the handling of other
  14676. expressions such as primitive operators.}
  14677. \newcommand{\ClambdaASTPython}{
  14678. \begin{array}{lcl}
  14679. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14680. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14681. &\MID& \ARITY{\Atm}
  14682. \end{array}
  14683. }
  14684. \begin{figure}[tp]
  14685. \fbox{
  14686. \begin{minipage}{0.96\textwidth}
  14687. \small
  14688. {\if\edition\racketEd
  14689. \[
  14690. \begin{array}{lcl}
  14691. \Exp &::= & \ldots
  14692. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14693. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14694. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14695. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14696. \MID \GOTO{\itm{label}} } \\
  14697. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14698. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14699. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14700. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14701. \end{array}
  14702. \]
  14703. \fi}
  14704. {\if\edition\pythonEd
  14705. \[
  14706. \begin{array}{l}
  14707. \gray{\CifASTPython} \\ \hline
  14708. \gray{\CtupASTPython} \\ \hline
  14709. \gray{\CfunASTPython} \\ \hline
  14710. \ClambdaASTPython \\
  14711. \begin{array}{lcl}
  14712. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14713. \end{array}
  14714. \end{array}
  14715. \]
  14716. \fi}
  14717. \end{minipage}
  14718. }
  14719. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14720. \label{fig:Clam-syntax}
  14721. \end{figure}
  14722. \section{Select Instructions}
  14723. \label{sec:select-instructions-Rlambda}
  14724. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14725. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14726. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14727. that you should place the \itm{arity} in the tag that is stored at
  14728. position $0$ of the vector. Recall that in
  14729. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14730. was not used. We store the arity in the $5$ bits starting at position
  14731. $58$.
  14732. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14733. instructions that access the tag from position $0$ of the vector and
  14734. extract the $5$-bits starting at position $58$ from the tag.}
  14735. %
  14736. \python{Compile a call to the \code{arity} operator to a sequence of
  14737. instructions that access the tag from position $0$ of the tuple
  14738. (representing a closure) and extract the $5$-bits starting at position
  14739. $58$ from the tag.}
  14740. \begin{figure}[p]
  14741. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14742. \node (Rfun) at (0,2) {\large \LangLam{}};
  14743. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14744. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14745. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14746. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14747. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14748. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14749. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14750. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14751. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14752. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14753. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14754. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14755. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14756. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14757. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14758. \path[->,bend left=15] (Rfun) edge [above] node
  14759. {\ttfamily\footnotesize shrink} (Rfun-2);
  14760. \path[->,bend left=15] (Rfun-2) edge [above] node
  14761. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14762. \path[->,bend left=15] (Rfun-3) edge [above] node
  14763. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14764. \path[->,bend left=15] (F1-0) edge [right] node
  14765. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14766. \path[->,bend left=15] (F1-1) edge [below] node
  14767. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14768. \path[->,bend right=15] (F1-2) edge [above] node
  14769. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14770. \path[->,bend right=15] (F1-3) edge [above] node
  14771. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14772. \path[->,bend right=15] (F1-4) edge [above] node
  14773. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14774. \path[->,bend right=15] (F1-5) edge [right] node
  14775. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14776. \path[->,bend left=15] (C3-2) edge [left] node
  14777. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14778. \path[->,bend right=15] (x86-2) edge [left] node
  14779. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14780. \path[->,bend right=15] (x86-2-1) edge [below] node
  14781. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14782. \path[->,bend right=15] (x86-2-2) edge [left] node
  14783. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14784. \path[->,bend left=15] (x86-3) edge [above] node
  14785. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14786. \path[->,bend left=15] (x86-4) edge [right] node
  14787. {\ttfamily\footnotesize print\_x86} (x86-5);
  14788. \end{tikzpicture}
  14789. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14790. functions.}
  14791. \label{fig:Rlambda-passes}
  14792. \end{figure}
  14793. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14794. for the compilation of \LangLam{}.
  14795. \clearpage
  14796. \section{Challenge: Optimize Closures}
  14797. \label{sec:optimize-closures}
  14798. In this chapter we compiled lexically-scoped functions into a
  14799. relatively efficient representation: flat closures. However, even this
  14800. representation comes with some overhead. For example, consider the
  14801. following program with a function \code{tail\_sum} that does not have
  14802. any free variables and where all the uses of \code{tail\_sum} are in
  14803. applications where we know that only \code{tail\_sum} is being applied
  14804. (and not any other functions).
  14805. \begin{center}
  14806. \begin{minipage}{0.95\textwidth}
  14807. {\if\edition\racketEd
  14808. \begin{lstlisting}
  14809. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14810. (if (eq? n 0)
  14811. s
  14812. (tail_sum (- n 1) (+ n s))))
  14813. (+ (tail_sum 3 0) 36)
  14814. \end{lstlisting}
  14815. \fi}
  14816. {\if\edition\pythonEd
  14817. \begin{lstlisting}
  14818. def tail_sum(n : int, s : int) -> int:
  14819. if n == 0:
  14820. return s
  14821. else:
  14822. return tail_sum(n - 1, n + s)
  14823. print( tail_sum(3, 0) + 36)
  14824. \end{lstlisting}
  14825. \fi}
  14826. \end{minipage}
  14827. \end{center}
  14828. As described in this chapter, we uniformly apply closure conversion to
  14829. all functions, obtaining the following output for this program.
  14830. \begin{center}
  14831. \begin{minipage}{0.95\textwidth}
  14832. {\if\edition\racketEd
  14833. \begin{lstlisting}
  14834. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14835. (if (eq? n2 0)
  14836. s3
  14837. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  14838. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14839. (define (main) : Integer
  14840. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  14841. ((vector-ref clos6 0) clos6 3 0)) 27))
  14842. \end{lstlisting}
  14843. \fi}
  14844. {\if\edition\pythonEd
  14845. \begin{lstlisting}
  14846. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14847. if n_0 == 0:
  14848. return s_1
  14849. else:
  14850. return (let clos_2 = (tail_sum,)
  14851. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14852. def main() -> int :
  14853. print((let clos_4 = (tail_sum,)
  14854. in clos_4[0](clos_4, 3, 0)) + 36)
  14855. return 0
  14856. \end{lstlisting}
  14857. \fi}
  14858. \end{minipage}
  14859. \end{center}
  14860. In the previous chapter, there would be no allocation in the program
  14861. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14862. the above program allocates memory for each closure and the calls to
  14863. \code{tail\_sum} are indirect. These two differences incur
  14864. considerable overhead in a program such as this one, where the
  14865. allocations and indirect calls occur inside a tight loop.
  14866. One might think that this problem is trivial to solve: can't we just
  14867. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  14868. and compile them to direct calls instead of treating it like a call to
  14869. a closure? We would also drop the new \code{fvs} parameter of
  14870. \code{tail\_sum}.
  14871. %
  14872. However, this problem is not so trivial because a global function may
  14873. ``escape'' and become involved in applications that also involve
  14874. closures. Consider the following example in which the application
  14875. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14876. application, because the \code{lambda} may flow into \code{f}, but the
  14877. \code{inc} function might also flow into \code{f}.
  14878. \begin{center}
  14879. \begin{minipage}{\textwidth}
  14880. % lambda_test_30.rkt
  14881. {\if\edition\racketEd
  14882. \begin{lstlisting}
  14883. (define (inc [x : Integer]) : Integer
  14884. (+ x 1))
  14885. (let ([y (read)])
  14886. (let ([f (if (eq? (read) 0)
  14887. inc
  14888. (lambda: ([x : Integer]) : Integer (- x y)))])
  14889. (f 41)))
  14890. \end{lstlisting}
  14891. \fi}
  14892. {\if\edition\pythonEd
  14893. \begin{lstlisting}
  14894. def add1(x : int) -> int:
  14895. return x + 1
  14896. y = input_int()
  14897. g : Callable[[int], int] = lambda x: x - y
  14898. f = add1 if input_int() == 0 else g
  14899. print( f(41) )
  14900. \end{lstlisting}
  14901. \fi}
  14902. \end{minipage}
  14903. \end{center}
  14904. If a global function name is used in any way other than as the
  14905. operator in a direct call, then we say that the function
  14906. \emph{escapes}. If a global function does not escape, then we do not
  14907. need to perform closure conversion on the function.
  14908. \begin{exercise}\normalfont
  14909. Implement an auxiliary function for detecting which global
  14910. functions escape. Using that function, implement an improved version
  14911. of closure conversion that does not apply closure conversion to
  14912. global functions that do not escape but instead compiles them as
  14913. regular functions. Create several new test cases that check whether
  14914. you properly detect whether global functions escape or not.
  14915. \end{exercise}
  14916. So far we have reduced the overhead of calling global functions, but
  14917. it would also be nice to reduce the overhead of calling a
  14918. \code{lambda} when we can determine at compile time which
  14919. \code{lambda} will be called. We refer to such calls as \emph{known
  14920. calls}. Consider the following example in which a \code{lambda} is
  14921. bound to \code{f} and then applied.
  14922. {\if\edition\racketEd
  14923. % lambda_test_9.rkt
  14924. \begin{lstlisting}
  14925. (let ([y (read)])
  14926. (let ([f (lambda: ([x : Integer]) : Integer
  14927. (+ x y))])
  14928. (f 21)))
  14929. \end{lstlisting}
  14930. \fi}
  14931. {\if\edition\pythonEd
  14932. \begin{lstlisting}
  14933. y = input_int()
  14934. f : Callable[[int],int] = lambda x: x + y
  14935. print( f(21) )
  14936. \end{lstlisting}
  14937. \fi}
  14938. %
  14939. \noindent Closure conversion compiles the application
  14940. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14941. %
  14942. {\if\edition\racketEd
  14943. \begin{lstlisting}
  14944. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  14945. (let ([y2 (vector-ref fvs6 1)])
  14946. (+ x3 y2)))
  14947. (define (main) : Integer
  14948. (let ([y2 (read)])
  14949. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  14950. ((vector-ref f4 0) f4 21))))
  14951. \end{lstlisting}
  14952. \fi}
  14953. {\if\edition\pythonEd
  14954. \begin{lstlisting}
  14955. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  14956. y_1 = fvs_4[1]
  14957. return x_2 + y_1[0]
  14958. def main() -> int:
  14959. y_1 = (777,)
  14960. y_1[0] = input_int()
  14961. f_0 = (lambda_3, y_1)
  14962. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  14963. return 0
  14964. \end{lstlisting}
  14965. \fi}
  14966. %
  14967. \noindent but we can instead compile the application
  14968. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  14969. %
  14970. {\if\edition\racketEd
  14971. \begin{lstlisting}
  14972. (define (main) : Integer
  14973. (let ([y2 (read)])
  14974. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  14975. ((fun-ref lambda5 1) f4 21))))
  14976. \end{lstlisting}
  14977. \fi}
  14978. {\if\edition\pythonEd
  14979. \begin{lstlisting}
  14980. def main() -> int:
  14981. y_1 = (777,)
  14982. y_1[0] = input_int()
  14983. f_0 = (lambda_3, y_1)
  14984. print(lambda_3(f_0, 21))
  14985. return 0
  14986. \end{lstlisting}
  14987. \fi}
  14988. The problem of determining which \code{lambda} will be called from a
  14989. particular application is quite challenging in general and the topic
  14990. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  14991. following exercise we recommend that you compile an application to a
  14992. direct call when the operator is a variable and \racket{the variable
  14993. is \code{let}-bound to a closure} \python{the previous assignment to
  14994. the variable is a closure}. This can be accomplished by maintaining
  14995. an environment mapping variables to function names. Extend the
  14996. environment whenever you encounter a closure on the right-hand side of
  14997. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  14998. name of the global function for the closure. This pass should come
  14999. after closure conversion.
  15000. \begin{exercise}\normalfont
  15001. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15002. compiles known calls into direct calls. Verify that your compiler is
  15003. successful in this regard on several example programs.
  15004. \end{exercise}
  15005. These exercises only scratches the surface of optimizing of
  15006. closures. A good next step for the interested reader is to look at the
  15007. work of \citet{Keep:2012ab}.
  15008. \section{Further Reading}
  15009. The notion of lexically scoped functions predates modern computers by
  15010. about a decade. They were invented by \citet{Church:1932aa}, who
  15011. proposed the lambda calculus as a foundation for logic. Anonymous
  15012. functions were included in the LISP~\citep{McCarthy:1960dz}
  15013. programming language but were initially dynamically scoped. The Scheme
  15014. dialect of LISP adopted lexical scoping and
  15015. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15016. Scheme programs. However, environments were represented as linked
  15017. lists, so variable lookup was linear in the size of the
  15018. environment. In this chapter we represent environments using flat
  15019. closures, which were invented by
  15020. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15021. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15022. closures, variable lookup is constant time but the time to create a
  15023. closure is proportional to the number of its free variables. Flat
  15024. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15025. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15026. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15027. \chapter{Dynamic Typing}
  15028. \label{ch:Ldyn}
  15029. \index{subject}{dynamic typing}
  15030. In this chapter we discuss the compilation of \LangDyn{}, a
  15031. dynamically typed language that is a subset of
  15032. \racket{Racket}\python{Python}. The dynamic typing is in contrast to
  15033. the previous chapters, which have studied the compilation of
  15034. statically typed languages. In dynamically typed languages such as
  15035. \LangDyn{}, a particular expression may produce a value of a different
  15036. type each time it is executed. Consider the following example with a
  15037. conditional \code{if} expression that may return a Boolean or an
  15038. integer depending on the input to the program.
  15039. % part of dynamic_test_25.rkt
  15040. {\if\edition\racketEd
  15041. \begin{lstlisting}
  15042. (not (if (eq? (read) 1) #f 0))
  15043. \end{lstlisting}
  15044. \fi}
  15045. {\if\edition\pythonEd
  15046. \begin{lstlisting}
  15047. not (False if input_int() == 1 else 0)
  15048. \end{lstlisting}
  15049. \fi}
  15050. Languages that allow expressions to produce different kinds of values
  15051. are called \emph{polymorphic}, a word composed of the Greek roots
  15052. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  15053. are several kinds of polymorphism in programming languages, such as
  15054. subtype polymorphism and parametric
  15055. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15056. study in this chapter does not have a special name but it is the kind
  15057. that arises in dynamically typed languages.
  15058. Another characteristic of dynamically typed languages is that
  15059. primitive operations, such as \code{not}, are often defined to operate
  15060. on many different types of values. In fact, in
  15061. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15062. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15063. given anything else it returns \FALSE{}.
  15064. Furthermore, even when primitive operations restrict their inputs to
  15065. values of a certain type, this restriction is enforced at runtime
  15066. instead of during compilation. For example, the tuple read
  15067. operation
  15068. \racket{\code{(vector-ref \#t 0)}}
  15069. \python{\code{True[0]}}
  15070. results in a run-time error because the first argument must
  15071. be a tuple, not a Boolean.
  15072. \begin{figure}[tp]
  15073. \centering
  15074. \fbox{
  15075. \begin{minipage}{0.97\textwidth}
  15076. {\if\edition\racketEd
  15077. \[
  15078. \begin{array}{rcl}
  15079. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  15080. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15081. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  15082. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  15083. &\MID& \key{\#t} \MID \key{\#f}
  15084. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  15085. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  15086. \MID \CUNIOP{\key{not}}{\Exp} \\
  15087. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15088. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  15089. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  15090. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  15091. &\MID& \LP\Exp \; \Exp\ldots\RP
  15092. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15093. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15094. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15095. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  15096. \LangDynM{} &::=& \Def\ldots\; \Exp
  15097. \end{array}
  15098. \]
  15099. \fi}
  15100. {\if\edition\pythonEd
  15101. \[
  15102. \begin{array}{rcl}
  15103. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15104. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15105. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15106. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15107. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15108. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15109. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15110. \MID \CLEN{\Exp} \\
  15111. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15112. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15113. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15114. \MID \Var\mathop{\key{=}}\Exp \\
  15115. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15116. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15117. &\MID& \CRETURN{\Exp} \\
  15118. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15119. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15120. \end{array}
  15121. \]
  15122. \fi}
  15123. \end{minipage}
  15124. }
  15125. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15126. \label{fig:r7-concrete-syntax}
  15127. \end{figure}
  15128. \begin{figure}[tp]
  15129. \centering
  15130. \fbox{
  15131. \begin{minipage}{0.96\textwidth}
  15132. \small
  15133. {\if\edition\racketEd
  15134. \[
  15135. \begin{array}{lcl}
  15136. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15137. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15138. &\MID& \BOOL{\itm{bool}}
  15139. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15140. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15141. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15142. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15143. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15144. \end{array}
  15145. \]
  15146. \fi}
  15147. {\if\edition\pythonEd
  15148. \[
  15149. \begin{array}{rcl}
  15150. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15151. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15152. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15153. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15154. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15155. &\MID & \code{Is()} \\
  15156. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15157. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15158. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15159. \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp}
  15160. \MID \VAR{\Var{}} \\
  15161. &\MID& \BOOL{\itm{bool}}
  15162. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15163. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15164. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15165. &\MID& \LEN{\Exp} \\
  15166. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15167. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15168. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15169. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15170. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15171. &\MID& \RETURN{\Exp} \\
  15172. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15173. \Def &::=& \FUNDEF{\Var}{\Params}{\_}{}{\Stmt^{+}} \\
  15174. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15175. \end{array}
  15176. \]
  15177. \fi}
  15178. \end{minipage}
  15179. }
  15180. \caption{The abstract syntax of \LangDyn{}.}
  15181. \label{fig:r7-syntax}
  15182. \end{figure}
  15183. The concrete and abstract syntax of \LangDyn{} is defined in
  15184. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15185. %
  15186. There is no type checker for \LangDyn{} because it is not a statically
  15187. typed language.
  15188. The definitional interpreter for \LangDyn{} is presented in
  15189. \racket{Figure~\ref{fig:interp-Ldyn}}
  15190. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15191. and its auxiliary functions are defined in
  15192. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15193. \INT{n}. Instead of simply returning the integer \code{n} (as
  15194. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15195. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15196. value} that combines an underlying value with a tag that identifies
  15197. what kind of value it is. We define the following \racket{struct}\python{class}
  15198. to represented tagged values.
  15199. %
  15200. {\if\edition\racketEd
  15201. \begin{lstlisting}
  15202. (struct Tagged (value tag) #:transparent)
  15203. \end{lstlisting}
  15204. \fi}
  15205. {\if\edition\pythonEd
  15206. \begin{minipage}{\textwidth}
  15207. \begin{lstlisting}
  15208. @dataclass(eq=True)
  15209. class Tagged(Value):
  15210. value : Value
  15211. tag : str
  15212. __match_args__ = ("value", "tag")
  15213. def __str__(self):
  15214. return str(self.value)
  15215. \end{lstlisting}
  15216. \end{minipage}
  15217. \fi}
  15218. %
  15219. \racket{The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15220. \code{Vector}, and \code{Procedure}.}
  15221. %
  15222. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15223. \code{'tuple'}, and \code{'function'}.}
  15224. %
  15225. Tags are closely related to types but don't always capture all the
  15226. information that a type does.
  15227. %
  15228. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15229. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15230. Any)} is tagged with \code{Procedure}.}
  15231. %
  15232. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15233. is tagged with \code{'tuple'} and a function of type
  15234. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15235. is tagged with \code{'function'}.}
  15236. Next consider the match case for accessing the element of a tuple.
  15237. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15238. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15239. argument is a tuple and the second is an integer.
  15240. \racket{
  15241. If they are not, a \code{trapped-error} is raised. Recall from
  15242. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15243. raises a \code{trapped-error} error, the compiled code must also
  15244. signal an error by exiting with return code \code{255}. A
  15245. \code{trapped-error} is also raised if the index is not less than
  15246. length of the vector.
  15247. }
  15248. %
  15249. \python{If they are not, an exception is raised. The compiled code
  15250. must also signal an error by exiting with return code \code{255}. A
  15251. exception is also raised if the index is not less than length of the
  15252. tuple.}
  15253. \begin{figure}[tbp]
  15254. {\if\edition\racketEd
  15255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15256. (define ((interp-Rdyn-exp env) ast)
  15257. (define recur (interp-Rdyn-exp env))
  15258. (match ast
  15259. [(Var x) (lookup x env)]
  15260. [(Int n) (Tagged n 'Integer)]
  15261. [(Bool b) (Tagged b 'Boolean)]
  15262. [(Lambda xs rt body)
  15263. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15264. [(Prim 'vector es)
  15265. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15266. [(Prim 'vector-ref (list e1 e2))
  15267. (define vec (recur e1)) (define i (recur e2))
  15268. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15269. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15270. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15271. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15272. [(Prim 'vector-set! (list e1 e2 e3))
  15273. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15274. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15275. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15276. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15277. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15278. (Tagged (void) 'Void)]
  15279. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15280. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15281. [(Prim 'or (list e1 e2))
  15282. (define v1 (recur e1))
  15283. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15284. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15285. [(Prim op (list e1))
  15286. #:when (set-member? type-predicates op)
  15287. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15288. [(Prim op es)
  15289. (define args (map recur es))
  15290. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15291. (unless (for/or ([expected-tags (op-tags op)])
  15292. (equal? expected-tags tags))
  15293. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15294. (tag-value
  15295. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15296. [(If q t f)
  15297. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15298. [(Apply f es)
  15299. (define new-f (recur f)) (define args (map recur es))
  15300. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15301. (match f-val
  15302. [`(function ,xs ,body ,lam-env)
  15303. (unless (eq? (length xs) (length args))
  15304. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15305. (define new-env (append (map cons xs args) lam-env))
  15306. ((interp-Rdyn-exp new-env) body)]
  15307. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15308. \end{lstlisting}
  15309. \fi}
  15310. {\if\edition\pythonEd
  15311. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15312. class InterpLdyn(InterpLlambda):
  15313. def interp_exp(self, e, env):
  15314. match e:
  15315. case Constant(n):
  15316. return self.tag(super().interp_exp(e, env))
  15317. case Tuple(es, Load()):
  15318. return self.tag(super().interp_exp(e, env))
  15319. case Lambda(params, body):
  15320. return self.tag(super().interp_exp(e, env))
  15321. case Call(Name('input_int'), []):
  15322. return self.tag(super().interp_exp(e, env))
  15323. case BinOp(left, Add(), right):
  15324. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15325. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15326. case BinOp(left, Sub(), right):
  15327. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15328. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15329. case UnaryOp(USub(), e1):
  15330. v = self.interp_exp(e1, env)
  15331. return self.tag(- self.untag(v, 'int', e))
  15332. case IfExp(test, body, orelse):
  15333. v = self.interp_exp(test, env)
  15334. match self.untag(v, 'bool', e):
  15335. case True:
  15336. return self.interp_exp(body, env)
  15337. case False:
  15338. return self.interp_exp(orelse, env)
  15339. case UnaryOp(Not(), e1):
  15340. v = self.interp_exp(e1, env)
  15341. return self.tag(not self.untag(v, 'bool', e))
  15342. case BoolOp(And(), values):
  15343. left = values[0]; right = values[1]
  15344. l = self.interp_exp(left, env)
  15345. match self.untag(l, 'bool', e):
  15346. case True:
  15347. return self.interp_exp(right, env)
  15348. case False:
  15349. return self.tag(False)
  15350. case BoolOp(Or(), values):
  15351. left = values[0]; right = values[1]
  15352. l = self.interp_exp(left, env)
  15353. match self.untag(l, 'bool', e):
  15354. case True:
  15355. return True
  15356. case False:
  15357. return self.interp_exp(right, env)
  15358. case Compare(left, [cmp], [right]):
  15359. l = self.interp_exp(left, env)
  15360. r = self.interp_exp(right, env)
  15361. if l.tag == r.tag:
  15362. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15363. else:
  15364. raise Exception('interp Compare unexpected ' \
  15365. + repr(l) + ' ' + repr(r))
  15366. case Subscript(tup, index, Load()):
  15367. t = self.interp_exp(tup, env)
  15368. n = self.interp_exp(index, env)
  15369. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15370. case Call(Name('len'), [tup]):
  15371. t = self.interp_exp(tup, env)
  15372. return self.tag(len(self.untag(t, 'tuple', e)))
  15373. case _:
  15374. return super().interp_exp(e, env)
  15375. \end{lstlisting}
  15376. \fi}
  15377. \caption{Interpreter for the \LangDyn{} language \python{, part 1}.}
  15378. \label{fig:interp-Ldyn}
  15379. \end{figure}
  15380. \begin{figure}[tbp]
  15381. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15382. class InterpLdyn(InterpLlambda):
  15383. def interp_stmts(self, ss, env):
  15384. if len(ss) == 0:
  15385. return
  15386. match ss[0]:
  15387. case If(test, body, orelse):
  15388. v = self.interp_exp(test, env)
  15389. match self.untag(v, 'bool', ss[0]):
  15390. case True:
  15391. return self.interp_stmts(body + ss[1:], env)
  15392. case False:
  15393. return self.interp_stmts(orelse + ss[1:], env)
  15394. case While(test, body, []):
  15395. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15396. self.interp_stmts(body, env)
  15397. return self.interp_stmts(ss[1:], env)
  15398. case Assign([Subscript(tup, index)], value):
  15399. tup = self.interp_exp(tup, env)
  15400. index = self.interp_exp(index, env)
  15401. tup_v = self.untag(tup, 'tuple', ss[0])
  15402. index_v = self.untag(index, 'int', ss[0])
  15403. tup_v[index_v] = self.interp_exp(value, env)
  15404. return self.interp_stmts(ss[1:], env)
  15405. case FunctionDef(name, params, bod, dl, returns, comment):
  15406. ps = [x for (x,t) in params]
  15407. env[name] = self.tag(Function(name, ps, bod, env))
  15408. return self.interp_stmts(ss[1:], env)
  15409. case _:
  15410. return super().interp_stmts(ss, env)
  15411. \end{lstlisting}
  15412. \caption{Interpreter for the \LangDyn{} language \python{, part 2}.}
  15413. \label{fig:interp-Ldyn-2}
  15414. \end{figure}
  15415. \begin{figure}[tbp]
  15416. {\if\edition\racketEd
  15417. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15418. (define (interp-op op)
  15419. (match op
  15420. ['+ fx+]
  15421. ['- fx-]
  15422. ['read read-fixnum]
  15423. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15424. ['< (lambda (v1 v2)
  15425. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15426. ['<= (lambda (v1 v2)
  15427. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15428. ['> (lambda (v1 v2)
  15429. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15430. ['>= (lambda (v1 v2)
  15431. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15432. ['boolean? boolean?]
  15433. ['integer? fixnum?]
  15434. ['void? void?]
  15435. ['vector? vector?]
  15436. ['vector-length vector-length]
  15437. ['procedure? (match-lambda
  15438. [`(functions ,xs ,body ,env) #t] [else #f])]
  15439. [else (error 'interp-op "unknown operator" op)]))
  15440. (define (op-tags op)
  15441. (match op
  15442. ['+ '((Integer Integer))]
  15443. ['- '((Integer Integer) (Integer))]
  15444. ['read '(())]
  15445. ['not '((Boolean))]
  15446. ['< '((Integer Integer))]
  15447. ['<= '((Integer Integer))]
  15448. ['> '((Integer Integer))]
  15449. ['>= '((Integer Integer))]
  15450. ['vector-length '((Vector))]))
  15451. (define type-predicates
  15452. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15453. (define (tag-value v)
  15454. (cond [(boolean? v) (Tagged v 'Boolean)]
  15455. [(fixnum? v) (Tagged v 'Integer)]
  15456. [(procedure? v) (Tagged v 'Procedure)]
  15457. [(vector? v) (Tagged v 'Vector)]
  15458. [(void? v) (Tagged v 'Void)]
  15459. [else (error 'tag-value "unidentified value ~a" v)]))
  15460. (define (check-tag val expected ast)
  15461. (define tag (Tagged-tag val))
  15462. (unless (eq? tag expected)
  15463. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15464. \end{lstlisting}
  15465. \fi}
  15466. {\if\edition\pythonEd
  15467. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15468. class InterpLdyn(InterpLlambda):
  15469. def tag(self, v):
  15470. if v is True or v is False:
  15471. return Tagged(v, 'bool')
  15472. elif isinstance(v, int):
  15473. return Tagged(v, 'int')
  15474. elif isinstance(v, Function):
  15475. return Tagged(v, 'function')
  15476. elif isinstance(v, list):
  15477. return Tagged(v, 'tuple')
  15478. elif isinstance(v, type(None)):
  15479. return Tagged(v, 'none')
  15480. else:
  15481. raise Exception('tag: unexpected ' + repr(v))
  15482. def untag(self, v, expected_tag, ast):
  15483. match v:
  15484. case Tagged(val, tag):
  15485. if tag != expected_tag:
  15486. raise Exception('expected tag ' + expected_tag + ', not ' + ' ' + repr(v))
  15487. return val
  15488. case _:
  15489. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15490. def apply_fun(self, fun, args, e):
  15491. f = self.untag(fun, 'function', e)
  15492. return super().apply_fun(f, args, e)
  15493. \end{lstlisting}
  15494. \fi}
  15495. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15496. \label{fig:interp-Ldyn-aux}
  15497. \end{figure}
  15498. \clearpage
  15499. \section{Representation of Tagged Values}
  15500. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15501. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15502. values at the bit level. Because almost every operation in \LangDyn{}
  15503. involves manipulating tagged values, the representation must be
  15504. efficient. Recall that all of our values are 64 bits. We shall steal
  15505. the 3 right-most bits to encode the tag. We use $001$ to identify
  15506. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15507. and $101$ for the void value. We define the following auxiliary
  15508. function for mapping types to tag codes.
  15509. {\if\edition\racketEd
  15510. \begin{align*}
  15511. \itm{tagof}(\key{Integer}) &= 001 \\
  15512. \itm{tagof}(\key{Boolean}) &= 100 \\
  15513. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15514. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15515. \itm{tagof}(\key{Void}) &= 101
  15516. \end{align*}
  15517. \fi}
  15518. {\if\edition\pythonEd
  15519. \begin{align*}
  15520. \itm{tagof}(\key{IntType()}) &= 001 \\
  15521. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15522. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15523. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15524. \itm{tagof}(\key{type(None)}) &= 101
  15525. \end{align*}
  15526. \fi}
  15527. This stealing of 3 bits comes at some price: our integers are reduced
  15528. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15529. affect vectors and procedures because those values are addresses, and
  15530. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15531. they are always $000$. Thus, we do not lose information by overwriting
  15532. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15533. to recover the original address.
  15534. To make tagged values into first-class entities, we can give them a
  15535. type, called \racket{\code{Any}}\python{AnyType}, and define operations
  15536. such as \code{Inject} and \code{Project} for creating and using them,
  15537. yielding the \LangAny{} intermediate language. We describe how to
  15538. compile \LangDyn{} to \LangAny{} in Section~\ref{sec:compile-r7}
  15539. but first we describe the \LangAny{} language in greater detail.
  15540. \section{The \LangAny{} Language}
  15541. \label{sec:Rany-lang}
  15542. \newcommand{\LanyASTRacket}{
  15543. \begin{array}{lcl}
  15544. \Type &::= & \key{Any} \\
  15545. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15546. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15547. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15548. \itm{op} &::= & \code{any-vector-length}
  15549. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15550. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15551. \MID \code{procedure?} \MID \code{void?} \\
  15552. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15553. \end{array}
  15554. }
  15555. \newcommand{\LanyASTPython}{
  15556. \begin{array}{lcl}
  15557. \Type &::= & \key{AnyType} \\
  15558. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15559. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15560. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15561. \Exp & ::= & \INJECT{\Exp}{\Type} \MID \PROJECT{\Exp}{\Type} \\
  15562. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\Exp\key{, }\INT{n}}\\
  15563. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\Exp}
  15564. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15565. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15566. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15567. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15568. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15569. \end{array}
  15570. }
  15571. \begin{figure}[tp]
  15572. \centering
  15573. \fbox{
  15574. \begin{minipage}{0.96\textwidth}
  15575. \small
  15576. {\if\edition\racketEd
  15577. \[
  15578. \begin{array}{l}
  15579. \gray{\LintOpAST} \\ \hline
  15580. \gray{\LvarASTRacket{}} \\ \hline
  15581. \gray{\LifASTRacket{}} \\ \hline
  15582. \gray{\LwhileASTRacket{}} \\ \hline
  15583. \gray{\LtupASTRacket{}} \\ \hline
  15584. \gray{\LfunASTRacket} \\ \hline
  15585. \gray{\LlambdaASTRacket} \\ \hline
  15586. \LanyASTRacket \\
  15587. \begin{array}{lcl}
  15588. %% \Type &::= & \ldots \MID \key{Any} \\
  15589. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15590. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15591. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15592. %% \MID \code{procedure?} \MID \code{void?} \\
  15593. %% \Exp &::=& \ldots
  15594. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15595. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15596. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15597. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15598. \end{array}
  15599. \end{array}
  15600. \]
  15601. \fi}
  15602. {\if\edition\pythonEd
  15603. \[
  15604. \begin{array}{l}
  15605. \gray{\LintASTPython} \\ \hline
  15606. \gray{\LvarASTPython{}} \\ \hline
  15607. \gray{\LifASTPython{}} \\ \hline
  15608. \gray{\LwhileASTPython{}} \\ \hline
  15609. \gray{\LtupASTPython{}} \\ \hline
  15610. \gray{\LfunASTPython} \\ \hline
  15611. \gray{\LlambdaASTPython} \\ \hline
  15612. \LanyASTPython \\
  15613. \begin{array}{lcl}
  15614. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15615. \end{array}
  15616. \end{array}
  15617. \]
  15618. \fi}
  15619. \end{minipage}
  15620. }
  15621. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15622. \label{fig:Rany-syntax}
  15623. \end{figure}
  15624. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15625. \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15626. Figure~\ref{fig:Rany-concrete-syntax}.)} The $\INJECT{e}{T}$ form
  15627. converts the value produced by expression $e$ of type $T$ into a
  15628. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15629. produced by expression $e$ into a value of type $T$ or else halts the
  15630. program if the type tag is not equivalent to $T$.
  15631. %
  15632. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15633. restricted to a flat type $\FType$, which simplifies the
  15634. implementation and corresponds with what is needed for compiling \LangDyn{}.
  15635. The \racket{\code{any-vector}}\python{\code{any\_tuple}} operators
  15636. adapt the tuple operations so that they can be applied to a value of
  15637. type \racket{\code{Any}}{\code{AnyType}}. They also generalize the
  15638. tuple operations in that the index is not restricted to be a literal
  15639. integer in the grammar but is allowed to be any expression.
  15640. \racket{The type predicates such as
  15641. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15642. to produce a tagged value; they return true if the tag corresponds to
  15643. the predicate and they return false otherwise.}
  15644. The type checker for \LangAny{} is shown in
  15645. Figure~\ref{fig:type-check-Rany}
  15646. %
  15647. \racket{ and uses the auxiliary functions in
  15648. Figure~\ref{fig:type-check-Rany-aux}}.
  15649. %
  15650. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and
  15651. its auxiliary functions are in Figure~\ref{fig:interp-Rany-aux}.
  15652. \begin{figure}[btp]
  15653. {\if\edition\racketEd
  15654. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15655. (define type-check-Rany_class
  15656. (class type-check-Rlambda_class
  15657. (super-new)
  15658. (inherit check-type-equal?)
  15659. (define/override (type-check-exp env)
  15660. (lambda (e)
  15661. (define recur (type-check-exp env))
  15662. (match e
  15663. [(Inject e1 ty)
  15664. (unless (flat-ty? ty)
  15665. (error 'type-check "may only inject from flat type, not ~a" ty))
  15666. (define-values (new-e1 e-ty) (recur e1))
  15667. (check-type-equal? e-ty ty e)
  15668. (values (Inject new-e1 ty) 'Any)]
  15669. [(Project e1 ty)
  15670. (unless (flat-ty? ty)
  15671. (error 'type-check "may only project to flat type, not ~a" ty))
  15672. (define-values (new-e1 e-ty) (recur e1))
  15673. (check-type-equal? e-ty 'Any e)
  15674. (values (Project new-e1 ty) ty)]
  15675. [(Prim 'any-vector-length (list e1))
  15676. (define-values (e1^ t1) (recur e1))
  15677. (check-type-equal? t1 'Any e)
  15678. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15679. [(Prim 'any-vector-ref (list e1 e2))
  15680. (define-values (e1^ t1) (recur e1))
  15681. (define-values (e2^ t2) (recur e2))
  15682. (check-type-equal? t1 'Any e)
  15683. (check-type-equal? t2 'Integer e)
  15684. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15685. [(Prim 'any-vector-set! (list e1 e2 e3))
  15686. (define-values (e1^ t1) (recur e1))
  15687. (define-values (e2^ t2) (recur e2))
  15688. (define-values (e3^ t3) (recur e3))
  15689. (check-type-equal? t1 'Any e)
  15690. (check-type-equal? t2 'Integer e)
  15691. (check-type-equal? t3 'Any e)
  15692. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15693. [(ValueOf e ty)
  15694. (define-values (new-e e-ty) (recur e))
  15695. (values (ValueOf new-e ty) ty)]
  15696. [(Prim pred (list e1))
  15697. #:when (set-member? (type-predicates) pred)
  15698. (define-values (new-e1 e-ty) (recur e1))
  15699. (check-type-equal? e-ty 'Any e)
  15700. (values (Prim pred (list new-e1)) 'Boolean)]
  15701. [(If cnd thn els)
  15702. (define-values (cnd^ Tc) (recur cnd))
  15703. (define-values (thn^ Tt) (recur thn))
  15704. (define-values (els^ Te) (recur els))
  15705. (check-type-equal? Tc 'Boolean cnd)
  15706. (check-type-equal? Tt Te e)
  15707. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15708. [(Exit) (values (Exit) '_)]
  15709. [(Prim 'eq? (list arg1 arg2))
  15710. (define-values (e1 t1) (recur arg1))
  15711. (define-values (e2 t2) (recur arg2))
  15712. (match* (t1 t2)
  15713. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15714. [(other wise) (check-type-equal? t1 t2 e)])
  15715. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15716. [else ((super type-check-exp env) e)])))
  15717. ))
  15718. \end{lstlisting}
  15719. \fi}
  15720. {\if\edition\pythonEd
  15721. \begin{lstlisting}
  15722. class TypeCheckLany(TypeCheckLlambda):
  15723. def type_check_exp(self, e, env):
  15724. match e:
  15725. case Inject(value, typ):
  15726. self.check_exp(value, typ, env)
  15727. return AnyType()
  15728. case Project(value, typ):
  15729. self.check_exp(value, AnyType(), env)
  15730. return typ
  15731. case Call(Name('any_tuple_load'), [tup, index]):
  15732. self.check_exp(tup, AnyType(), env)
  15733. return AnyType()
  15734. case Call(Name('any_len'), [tup]):
  15735. self.check_exp(tup, AnyType(), env)
  15736. return IntType()
  15737. case Call(Name('arity'), [fun]):
  15738. ty = self.type_check_exp(fun, env)
  15739. match ty:
  15740. case FunctionType(ps, rt):
  15741. return IntType()
  15742. case TupleType([FunctionType(ps,rs)]):
  15743. return IntType()
  15744. case _:
  15745. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15746. case Call(Name('make_any'), [value, tag]):
  15747. self.type_check_exp(value, env)
  15748. self.check_exp(tag, IntType(), env)
  15749. return AnyType()
  15750. case ValueOf(value, typ):
  15751. self.check_exp(value, AnyType(), env)
  15752. return typ
  15753. case TagOf(value):
  15754. self.check_exp(value, AnyType(), env)
  15755. return IntType()
  15756. case Call(Name('exit'), []):
  15757. return Bottom()
  15758. case AnnLambda(params, returns, body):
  15759. new_env = {x:t for (x,t) in env.items()}
  15760. for (x,t) in params:
  15761. new_env[x] = t
  15762. return_t = self.type_check_exp(body, new_env)
  15763. self.check_type_equal(returns, return_t, e)
  15764. return FunctionType([t for (x,t) in params], return_t)
  15765. case _:
  15766. return super().type_check_exp(e, env)
  15767. \end{lstlisting}
  15768. \fi}
  15769. \caption{Type checker for the \LangAny{} language.}
  15770. \label{fig:type-check-Rany}
  15771. \end{figure}
  15772. {\if\edition\racketEd
  15773. \begin{figure}[tbp]
  15774. {\if\edition\racketEd
  15775. \begin{lstlisting}
  15776. (define/override (operator-types)
  15777. (append
  15778. '((integer? . ((Any) . Boolean))
  15779. (vector? . ((Any) . Boolean))
  15780. (procedure? . ((Any) . Boolean))
  15781. (void? . ((Any) . Boolean))
  15782. (tag-of-any . ((Any) . Integer))
  15783. (make-any . ((_ Integer) . Any)))
  15784. (super operator-types)))
  15785. (define/public (type-predicates)
  15786. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15787. (define/public (combine-types t1 t2)
  15788. (match (list t1 t2)
  15789. [(list '_ t2) t2]
  15790. [(list t1 '_) t1]
  15791. [(list `(Vector ,ts1 ...)
  15792. `(Vector ,ts2 ...))
  15793. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15794. (combine-types t1 t2)))]
  15795. [(list `(,ts1 ... -> ,rt1)
  15796. `(,ts2 ... -> ,rt2))
  15797. `(,@(for/list ([t1 ts1] [t2 ts2])
  15798. (combine-types t1 t2))
  15799. -> ,(combine-types rt1 rt2))]
  15800. [else t1]))
  15801. (define/public (flat-ty? ty)
  15802. (match ty
  15803. [(or `Integer `Boolean '_ `Void) #t]
  15804. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15805. [`(,ts ... -> ,rt)
  15806. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15807. [else #f]))
  15808. \end{lstlisting}
  15809. \fi}
  15810. \caption{Auxiliary methods for type checking \LangAny{}.}
  15811. \label{fig:type-check-Rany-aux}
  15812. \end{figure}
  15813. \fi}
  15814. \begin{figure}[btp]
  15815. {\if\edition\racketEd
  15816. \begin{lstlisting}
  15817. (define interp-Rany_class
  15818. (class interp-Rlambda_class
  15819. (super-new)
  15820. (define/override (interp-op op)
  15821. (match op
  15822. ['boolean? (match-lambda
  15823. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15824. [else #f])]
  15825. ['integer? (match-lambda
  15826. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15827. [else #f])]
  15828. ['vector? (match-lambda
  15829. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15830. [else #f])]
  15831. ['procedure? (match-lambda
  15832. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15833. [else #f])]
  15834. ['eq? (match-lambda*
  15835. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15836. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15837. [ls (apply (super interp-op op) ls)])]
  15838. ['any-vector-ref (lambda (v i)
  15839. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15840. ['any-vector-set! (lambda (v i a)
  15841. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15842. ['any-vector-length (lambda (v)
  15843. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15844. [else (super interp-op op)]))
  15845. (define/override ((interp-exp env) e)
  15846. (define recur (interp-exp env))
  15847. (match e
  15848. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15849. [(Project e ty2) (apply-project (recur e) ty2)]
  15850. [else ((super interp-exp env) e)]))
  15851. ))
  15852. (define (interp-Rany p)
  15853. (send (new interp-Rany_class) interp-program p))
  15854. \end{lstlisting}
  15855. \fi}
  15856. {\if\edition\pythonEd
  15857. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15858. class InterpLany(InterpLlambda):
  15859. def interp_exp(self, e, env):
  15860. match e:
  15861. case Inject(value, typ):
  15862. v = self.interp_exp(value, env)
  15863. return Tagged(v, self.type_to_tag(typ))
  15864. case Project(value, typ):
  15865. v = self.interp_exp(value, env)
  15866. match v:
  15867. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  15868. return val
  15869. case _:
  15870. raise Exception('interp project to ' + repr(typ) \
  15871. + ' unexpected ' + repr(v))
  15872. case Call(Name('any_tuple_load'), [tup, index]):
  15873. tv = self.interp_exp(tup, env)
  15874. n = self.interp_exp(index, env)
  15875. match tv:
  15876. case Tagged(v, tag):
  15877. return v[n]
  15878. case _:
  15879. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15880. case Call(Name('any_tuple_store'), [tup, index, value]):
  15881. tv = self.interp_exp(tup, env)
  15882. n = self.interp_exp(index, env)
  15883. val = self.interp_exp(value, env)
  15884. match tv:
  15885. case Tagged(v, tag):
  15886. v[n] = val
  15887. return None
  15888. case _:
  15889. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15890. case Call(Name('any_len'), [value]):
  15891. v = self.interp_exp(value, env)
  15892. match v:
  15893. case Tagged(value, tag):
  15894. return len(value)
  15895. case _:
  15896. raise Exception('interp any_len unexpected ' + repr(v))
  15897. case Call(Name('make_any'), [value, tag]):
  15898. v = self.interp_exp(value, env)
  15899. t = self.interp_exp(tag, env)
  15900. return Tagged(v, t)
  15901. case Call(Name('arity'), [fun]):
  15902. f = self.interp_exp(fun, env)
  15903. return self.arity(f)
  15904. case Call(Name('exit'), []):
  15905. trace('exiting!')
  15906. exit(0)
  15907. case TagOf(value):
  15908. v = self.interp_exp(value, env)
  15909. match v:
  15910. case Tagged(val, tag):
  15911. return tag
  15912. case _:
  15913. raise Exception('interp TagOf unexpected ' + repr(v))
  15914. case ValueOf(value, typ):
  15915. v = self.interp_exp(value, env)
  15916. match v:
  15917. case Tagged(val, tag):
  15918. return val
  15919. case _:
  15920. raise Exception('interp ValueOf unexpected ' + repr(v))
  15921. case AnnLambda(params, returns, body):
  15922. return Function('lambda', [x for (x,t) in params], [Return(body)], env)
  15923. case _:
  15924. return super().interp_exp(e, env)
  15925. \end{lstlisting}
  15926. \fi}
  15927. \caption{Interpreter for \LangAny{}.}
  15928. \label{fig:interp-Rany}
  15929. \end{figure}
  15930. \begin{figure}[tbp]
  15931. {\if\edition\racketEd
  15932. \begin{lstlisting}
  15933. (define/public (apply-inject v tg) (Tagged v tg))
  15934. (define/public (apply-project v ty2)
  15935. (define tag2 (any-tag ty2))
  15936. (match v
  15937. [(Tagged v1 tag1)
  15938. (cond
  15939. [(eq? tag1 tag2)
  15940. (match ty2
  15941. [`(Vector ,ts ...)
  15942. (define l1 ((interp-op 'vector-length) v1))
  15943. (cond
  15944. [(eq? l1 (length ts)) v1]
  15945. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15946. l1 (length ts))])]
  15947. [`(,ts ... -> ,rt)
  15948. (match v1
  15949. [`(function ,xs ,body ,env)
  15950. (cond [(eq? (length xs) (length ts)) v1]
  15951. [else
  15952. (error 'apply-project "arity mismatch ~a != ~a"
  15953. (length xs) (length ts))])]
  15954. [else (error 'apply-project "expected function not ~a" v1)])]
  15955. [else v1])]
  15956. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  15957. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  15958. \end{lstlisting}
  15959. \fi}
  15960. {\if\edition\pythonEd
  15961. \begin{lstlisting}
  15962. class InterpLany(InterpLlambda):
  15963. def type_to_tag(self, typ):
  15964. match typ:
  15965. case FunctionType(params, rt):
  15966. return 'function'
  15967. case TupleType(fields):
  15968. return 'tuple'
  15969. case t if t == int:
  15970. return 'int'
  15971. case t if t == bool:
  15972. return 'bool'
  15973. case IntType():
  15974. return 'int'
  15975. case BoolType():
  15976. return 'int'
  15977. case _:
  15978. raise Exception('type_to_tag unexpected ' + repr(typ))
  15979. def arity(self, v):
  15980. match v:
  15981. case Function(name, params, body, env):
  15982. return len(params)
  15983. case ClosureTuple(args, arity):
  15984. return arity
  15985. case _:
  15986. raise Exception('Lany arity unexpected ' + repr(v))
  15987. \end{lstlisting}
  15988. \fi}
  15989. \caption{Auxiliary functions for interpreting \LangAny{}.}
  15990. \label{fig:interp-Rany-aux}
  15991. \end{figure}
  15992. \clearpage
  15993. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  15994. \label{sec:compile-r7}
  15995. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  15996. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  15997. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  15998. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  15999. an expression $e'$ in \LangAny{} that has type \ANYTY{}. For example, the
  16000. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  16001. the Boolean \TRUE{}, which must be injected to produce an
  16002. expression of type \ANYTY{}.
  16003. %
  16004. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  16005. addition, is representative of compilation for many primitive
  16006. operations: the arguments have type \ANYTY{} and must be projected to
  16007. \INTTYPE{} before the addition can be performed.
  16008. The compilation of \key{lambda} (third row of
  16009. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  16010. produce type annotations: we simply use \ANYTY{}.
  16011. %
  16012. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16013. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16014. this pass has to account for some differences in behavior between
  16015. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16016. permissive than \LangAny{} regarding what kind of values can be used
  16017. in various places. For example, the condition of an \key{if} does
  16018. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16019. of the same type (in that case the result is \code{\#f}).}
  16020. \begin{figure}[btp]
  16021. \centering
  16022. {\if\edition\racketEd
  16023. \begin{tabular}{|lll|} \hline
  16024. \begin{minipage}{0.27\textwidth}
  16025. \begin{lstlisting}
  16026. #t
  16027. \end{lstlisting}
  16028. \end{minipage}
  16029. &
  16030. $\Rightarrow$
  16031. &
  16032. \begin{minipage}{0.65\textwidth}
  16033. \begin{lstlisting}
  16034. (inject #t Boolean)
  16035. \end{lstlisting}
  16036. \end{minipage}
  16037. \\[2ex]\hline
  16038. \begin{minipage}{0.27\textwidth}
  16039. \begin{lstlisting}
  16040. (+ |$e_1$| |$e_2$|)
  16041. \end{lstlisting}
  16042. \end{minipage}
  16043. &
  16044. $\Rightarrow$
  16045. &
  16046. \begin{minipage}{0.65\textwidth}
  16047. \begin{lstlisting}
  16048. (inject
  16049. (+ (project |$e'_1$| Integer)
  16050. (project |$e'_2$| Integer))
  16051. Integer)
  16052. \end{lstlisting}
  16053. \end{minipage}
  16054. \\[2ex]\hline
  16055. \begin{minipage}{0.27\textwidth}
  16056. \begin{lstlisting}
  16057. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  16058. \end{lstlisting}
  16059. \end{minipage}
  16060. &
  16061. $\Rightarrow$
  16062. &
  16063. \begin{minipage}{0.65\textwidth}
  16064. \begin{lstlisting}
  16065. (inject
  16066. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  16067. (Any|$\ldots$|Any -> Any))
  16068. \end{lstlisting}
  16069. \end{minipage}
  16070. \\[2ex]\hline
  16071. \begin{minipage}{0.27\textwidth}
  16072. \begin{lstlisting}
  16073. (|$e_0$| |$e_1 \ldots e_n$|)
  16074. \end{lstlisting}
  16075. \end{minipage}
  16076. &
  16077. $\Rightarrow$
  16078. &
  16079. \begin{minipage}{0.65\textwidth}
  16080. \begin{lstlisting}
  16081. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16082. \end{lstlisting}
  16083. \end{minipage}
  16084. \\[2ex]\hline
  16085. \begin{minipage}{0.27\textwidth}
  16086. \begin{lstlisting}
  16087. (vector-ref |$e_1$| |$e_2$|)
  16088. \end{lstlisting}
  16089. \end{minipage}
  16090. &
  16091. $\Rightarrow$
  16092. &
  16093. \begin{minipage}{0.65\textwidth}
  16094. \begin{lstlisting}
  16095. (any-vector-ref |$e_1'$| |$e_2'$|)
  16096. \end{lstlisting}
  16097. \end{minipage}
  16098. \\[2ex]\hline
  16099. \begin{minipage}{0.27\textwidth}
  16100. \begin{lstlisting}
  16101. (if |$e_1$| |$e_2$| |$e_3$|)
  16102. \end{lstlisting}
  16103. \end{minipage}
  16104. &
  16105. $\Rightarrow$
  16106. &
  16107. \begin{minipage}{0.65\textwidth}
  16108. \begin{lstlisting}
  16109. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16110. \end{lstlisting}
  16111. \end{minipage}
  16112. \\[2ex]\hline
  16113. \begin{minipage}{0.27\textwidth}
  16114. \begin{lstlisting}
  16115. (eq? |$e_1$| |$e_2$|)
  16116. \end{lstlisting}
  16117. \end{minipage}
  16118. &
  16119. $\Rightarrow$
  16120. &
  16121. \begin{minipage}{0.65\textwidth}
  16122. \begin{lstlisting}
  16123. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16124. \end{lstlisting}
  16125. \end{minipage}
  16126. \\[2ex]\hline
  16127. \begin{minipage}{0.27\textwidth}
  16128. \begin{lstlisting}
  16129. (not |$e_1$|)
  16130. \end{lstlisting}
  16131. \end{minipage}
  16132. &
  16133. $\Rightarrow$
  16134. &
  16135. \begin{minipage}{0.65\textwidth}
  16136. \begin{lstlisting}
  16137. (if (eq? |$e'_1$| (inject #f Boolean))
  16138. (inject #t Boolean) (inject #f Boolean))
  16139. \end{lstlisting}
  16140. \end{minipage}
  16141. \\[2ex]\hline
  16142. \end{tabular}
  16143. \fi}
  16144. {\if\edition\pythonEd
  16145. \begin{tabular}{|lll|} \hline
  16146. \begin{minipage}{0.22\textwidth}
  16147. \begin{lstlisting}
  16148. True
  16149. \end{lstlisting}
  16150. \end{minipage}
  16151. &
  16152. $\Rightarrow$
  16153. &
  16154. \begin{minipage}{0.7\textwidth}
  16155. \begin{lstlisting}
  16156. Inject(True, BoolType())
  16157. \end{lstlisting}
  16158. \end{minipage}
  16159. \\[2ex]\hline
  16160. \begin{minipage}{0.22\textwidth}
  16161. \begin{lstlisting}
  16162. |$e_1$| + |$e_2$|
  16163. \end{lstlisting}
  16164. \end{minipage}
  16165. &
  16166. $\Rightarrow$
  16167. &
  16168. \begin{minipage}{0.7\textwidth}
  16169. \begin{lstlisting}
  16170. Inject(Project(|$e'_1$|, IntType())
  16171. + Project(|$e'_2$|, IntType()),
  16172. IntType())
  16173. \end{lstlisting}
  16174. \end{minipage}
  16175. \\[2ex]\hline
  16176. \begin{minipage}{0.22\textwidth}
  16177. \begin{lstlisting}
  16178. lambda |$x_1 \ldots x_n$|: |$e$|
  16179. \end{lstlisting}
  16180. \end{minipage}
  16181. &
  16182. $\Rightarrow$
  16183. &
  16184. \begin{minipage}{0.7\textwidth}
  16185. \begin{lstlisting}
  16186. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|,(|$x_n$|,AnyType)], |$e'$|)
  16187. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16188. \end{lstlisting}
  16189. \end{minipage}
  16190. \\[2ex]\hline
  16191. \begin{minipage}{0.22\textwidth}
  16192. \begin{lstlisting}
  16193. |$e_0$|(|$e_1 \ldots e_n$|)
  16194. \end{lstlisting}
  16195. \end{minipage}
  16196. &
  16197. $\Rightarrow$
  16198. &
  16199. \begin{minipage}{0.7\textwidth}
  16200. \begin{lstlisting}
  16201. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16202. AnyType())), |$e'_1, \ldots, e'_n$|)
  16203. \end{lstlisting}
  16204. \end{minipage}
  16205. \\[2ex]\hline
  16206. \begin{minipage}{0.22\textwidth}
  16207. \begin{lstlisting}
  16208. |$e_1$|[|$e_2$|]
  16209. \end{lstlisting}
  16210. \end{minipage}
  16211. &
  16212. $\Rightarrow$
  16213. &
  16214. \begin{minipage}{0.7\textwidth}
  16215. \begin{lstlisting}
  16216. Call('any_tuple_load',[|$e_1'$|, |$e_2'$|])
  16217. \end{lstlisting}
  16218. \end{minipage}
  16219. \\[2ex]\hline
  16220. %% \begin{minipage}{0.22\textwidth}
  16221. %% \begin{lstlisting}
  16222. %% |$e_2$| if |$e_1$| else |$e_3$|
  16223. %% \end{lstlisting}
  16224. %% \end{minipage}
  16225. %% &
  16226. %% $\Rightarrow$
  16227. %% &
  16228. %% \begin{minipage}{0.7\textwidth}
  16229. %% \begin{lstlisting}
  16230. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16231. %% \end{lstlisting}
  16232. %% \end{minipage}
  16233. %% \\[2ex]\hline
  16234. %% \begin{minipage}{0.22\textwidth}
  16235. %% \begin{lstlisting}
  16236. %% (eq? |$e_1$| |$e_2$|)
  16237. %% \end{lstlisting}
  16238. %% \end{minipage}
  16239. %% &
  16240. %% $\Rightarrow$
  16241. %% &
  16242. %% \begin{minipage}{0.7\textwidth}
  16243. %% \begin{lstlisting}
  16244. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16245. %% \end{lstlisting}
  16246. %% \end{minipage}
  16247. %% \\[2ex]\hline
  16248. %% \begin{minipage}{0.22\textwidth}
  16249. %% \begin{lstlisting}
  16250. %% (not |$e_1$|)
  16251. %% \end{lstlisting}
  16252. %% \end{minipage}
  16253. %% &
  16254. %% $\Rightarrow$
  16255. %% &
  16256. %% \begin{minipage}{0.7\textwidth}
  16257. %% \begin{lstlisting}
  16258. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16259. %% (inject #t Boolean) (inject #f Boolean))
  16260. %% \end{lstlisting}
  16261. %% \end{minipage}
  16262. %% \\[2ex]\hline
  16263. \end{tabular}
  16264. \fi}
  16265. \caption{Cast Insertion}
  16266. \label{fig:compile-r7-Rany}
  16267. \end{figure}
  16268. \section{Reveal Casts}
  16269. \label{sec:reveal-casts-Rany}
  16270. % TODO: define R'_6
  16271. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16272. into a conditional expression that checks whether the value's tag
  16273. matches the target type; if it does, the value is converted to a value
  16274. of the target type by removing the tag; if it does not, the program
  16275. exits.
  16276. %
  16277. {\if\edition\racketEd
  16278. %
  16279. To perform these actions we need a new primitive operation,
  16280. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16281. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16282. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16283. underlying value from a tagged value. The \code{ValueOf} form
  16284. includes the type for the underlying value which is used by the type
  16285. checker. Finally, the \code{Exit} form ends the execution of the
  16286. program.
  16287. %
  16288. \fi}
  16289. %
  16290. {\if\edition\pythonEd
  16291. %
  16292. To perform these actions we need the \code{exit} function (from the C
  16293. standard library) and two new AST classes: \code{TagOf} and
  16294. \code{ValueOf}. The \code{exit} function ends the execution of the
  16295. program. The \code{TagOf} operation retrieves the type tag from a
  16296. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16297. the underlying value from a tagged value. The \code{ValueOf}
  16298. operation includes the type for the underlying value which is used by
  16299. the type checker.
  16300. %
  16301. \fi}
  16302. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16303. \code{Project} can be translated as follows.
  16304. \begin{center}
  16305. \begin{minipage}{1.0\textwidth}
  16306. {\if\edition\racketEd
  16307. \begin{lstlisting}
  16308. (Project |$e$| |$\FType$|)
  16309. |$\Rightarrow$|
  16310. (Let |$\itm{tmp}$| |$e'$|
  16311. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16312. (Int |$\itm{tagof}(\FType)$|)))
  16313. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16314. (Exit)))
  16315. \end{lstlisting}
  16316. \fi}
  16317. {\if\edition\pythonEd
  16318. \begin{lstlisting}
  16319. Project(|$e$|, |$\FType$|)
  16320. |$\Rightarrow$|
  16321. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16322. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16323. [Constant(|$\itm{tagof}(\FType)$|)]),
  16324. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16325. Call(Name('exit'), [])))
  16326. \end{lstlisting}
  16327. \fi}
  16328. \end{minipage}
  16329. \end{center}
  16330. If the target type of the projection is a tuple or function type, then
  16331. there is a bit more work to do. For tuples, check that the length of
  16332. the tuple type matches the length of the tuple. For functions, check
  16333. that the number of parameters in the function type matches the
  16334. function's arity.
  16335. Regarding \code{Inject}, we recommend compiling it to a slightly
  16336. lower-level primitive operation named \code{make\_any}. This operation
  16337. takes a tag instead of a type.
  16338. \begin{center}
  16339. \begin{minipage}{1.0\textwidth}
  16340. {\if\edition\racketEd
  16341. \begin{lstlisting}
  16342. (Inject |$e$| |$\FType$|)
  16343. |$\Rightarrow$|
  16344. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16345. \end{lstlisting}
  16346. \fi}
  16347. {\if\edition\pythonEd
  16348. \begin{lstlisting}
  16349. Inject(|$e$|, |$\FType$|)
  16350. |$\Rightarrow$|
  16351. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16352. \end{lstlisting}
  16353. \fi}
  16354. \end{minipage}
  16355. \end{center}
  16356. {\if\edition\pythonEd
  16357. %
  16358. The introduction of \code{make\_any} makes it difficult to use
  16359. bidirectional type checking because we no longer have an expected type
  16360. to use for type checking the expression $e'$. Thus, we run into
  16361. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16362. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16363. annotated lambda) whose parameters have type annotations and that
  16364. records the return type.
  16365. %
  16366. \fi}
  16367. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16368. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16369. translation of \code{Project}.}
  16370. {\if\edition\racketEd
  16371. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16372. combine the projection action with the vector operation. Also, the
  16373. read and write operations allow arbitrary expressions for the index so
  16374. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany})
  16375. cannot guarantee that the index is within bounds. Thus, we insert code
  16376. to perform bounds checking at runtime. The translation for
  16377. \code{any-vector-ref} is as follows and the other two operations are
  16378. translated in a similar way.
  16379. \begin{lstlisting}
  16380. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16381. |$\Rightarrow$|
  16382. (Let |$v$| |$e'_1$|
  16383. (Let |$i$| |$e'_2$|
  16384. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16385. (If (Prim '< (list (Var |$i$|)
  16386. (Prim 'any-vector-length (list (Var |$v$|)))))
  16387. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16388. (Exit))
  16389. (Exit))))
  16390. \end{lstlisting}
  16391. \fi}
  16392. %
  16393. {\if\edition\pythonEd
  16394. %
  16395. The \code{any\_tuple\_load} operation combines the projection action
  16396. with the load operation. Also, the load operation allows arbitrary
  16397. expressions for the index so the type checker for \LangAny{}
  16398. (Figure~\ref{fig:type-check-Rany}) cannot guarantee that the index is
  16399. within bounds. Thus, we insert code to perform bounds checking at
  16400. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16401. \begin{lstlisting}
  16402. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16403. |$\Rightarrow$|
  16404. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16405. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16406. IfExp(Compare(|$i$|, [LtE()], [Call(Name('any_len'), [|$t$|])]),
  16407. Call(Name('any_tuple_load'), [|$t$|, |$i$|]),
  16408. Call(Name('exit'), [])),
  16409. Call(Name('exit'), [])))
  16410. \end{lstlisting}
  16411. \fi}
  16412. {\if\edition\pythonEd
  16413. \section{Assignment Conversion}
  16414. \label{sec:convert-assignments-Lany}
  16415. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16416. \code{AnnLambda} AST classes.
  16417. \section{Closure Conversion}
  16418. \label{sec:closure-conversion-Lany}
  16419. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16420. \code{AnnLambda} AST classes.
  16421. \fi}
  16422. \section{Remove Complex Operands}
  16423. \label{sec:rco-Rany}
  16424. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16425. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16426. %
  16427. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16428. complex expressions. Their subexpressions must be atomic.}
  16429. \section{Explicate Control and \LangCAny{}}
  16430. \label{sec:explicate-Rany}
  16431. The output of \code{explicate\_control} is the \LangCAny{} language
  16432. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16433. %
  16434. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16435. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16436. note that the index argument of \code{vector-ref} and
  16437. \code{vector-set!} is an $\Atm$ instead of an integer, as in
  16438. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16439. %
  16440. \python{
  16441. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16442. and \code{explicate\_pred} as appropriately to handle the new expressions
  16443. in \LangCAny{}.
  16444. }
  16445. \newcommand{\CanyASTPython}{
  16446. \begin{array}{lcl}
  16447. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16448. &\MID& \key{TagOf}\LP \Atm \RP
  16449. \MID \key{ValueOf}\LP \Atm , \Type \RP \\
  16450. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS \Atm,\Atm \RS}\\
  16451. &\MID& \CALL{\VAR{\key{'any\_tuple\_store'}}}{\LS \Atm,\Atm,\Atm \RS}\\
  16452. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16453. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16454. \end{array}
  16455. }
  16456. \begin{figure}[tp]
  16457. \fbox{
  16458. \begin{minipage}{0.96\textwidth}
  16459. \small
  16460. {\if\edition\racketEd
  16461. \[
  16462. \begin{array}{lcl}
  16463. \Exp &::= & \ldots
  16464. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16465. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16466. &\MID& \VALUEOF{\Exp}{\FType} \\
  16467. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  16468. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  16469. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  16470. \MID \GOTO{\itm{label}} } \\
  16471. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  16472. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  16473. \MID \LP\key{Exit}\RP \\
  16474. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  16475. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  16476. \end{array}
  16477. \]
  16478. \fi}
  16479. {\if\edition\pythonEd
  16480. \[
  16481. \begin{array}{l}
  16482. \gray{\CifASTPython} \\ \hline
  16483. \gray{\CtupASTPython} \\ \hline
  16484. \gray{\CfunASTPython} \\ \hline
  16485. \gray{\ClambdaASTPython} \\ \hline
  16486. \CanyASTPython \\
  16487. \begin{array}{lcl}
  16488. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16489. \end{array}
  16490. \end{array}
  16491. \]
  16492. \fi}
  16493. \end{minipage}
  16494. }
  16495. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16496. \label{fig:c5-syntax}
  16497. \end{figure}
  16498. \section{Select Instructions}
  16499. \label{sec:select-Rany}
  16500. In the \code{select\_instructions} pass we translate the primitive
  16501. operations on the \ANYTY{} type to x86 instructions that manipulate
  16502. the 3 tag bits of the tagged value. In the following descriptions,
  16503. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16504. of translating $e$ into an x86 argument.
  16505. \paragraph{\code{make\_any}}
  16506. We recommend compiling the \code{make\_any} operation as follows if
  16507. the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16508. shifts the destination to the left by the number of bits specified its
  16509. source argument (in this case $3$, the length of the tag) and it
  16510. preserves the sign of the integer. We use the \key{orq} instruction to
  16511. combine the tag and the value to form the tagged value. \\
  16512. %
  16513. {\if\edition\racketEd
  16514. \begin{lstlisting}
  16515. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16516. |$\Rightarrow$|
  16517. movq |$e'$|, |\itm{lhs'}|
  16518. salq $3, |\itm{lhs'}|
  16519. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16520. \end{lstlisting}
  16521. \fi}
  16522. %
  16523. {\if\edition\pythonEd
  16524. \begin{lstlisting}
  16525. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16526. |$\Rightarrow$|
  16527. movq |$e'$|, |\itm{lhs'}|
  16528. salq $3, |\itm{lhs'}|
  16529. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16530. \end{lstlisting}
  16531. \fi}
  16532. %
  16533. The instruction selection for tuples and procedures is different
  16534. because their is no need to shift them to the left. The rightmost 3
  16535. bits are already zeros so we simply combine the value and the tag
  16536. using \key{orq}. \\
  16537. %
  16538. {\if\edition\racketEd
  16539. \begin{lstlisting}
  16540. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16541. |$\Rightarrow$|
  16542. movq |$e'$|, |\itm{lhs'}|
  16543. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16544. \end{lstlisting}
  16545. \fi}
  16546. %
  16547. {\if\edition\pythonEd
  16548. \begin{lstlisting}
  16549. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16550. |$\Rightarrow$|
  16551. movq |$e'$|, |\itm{lhs'}|
  16552. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16553. \end{lstlisting}
  16554. \fi}
  16555. \paragraph{\code{TagOf}}
  16556. Recall that the \code{TagOf} operation extracts the type tag from a
  16557. value of type \ANYTY{}. The type tag is the bottom three bits, so we
  16558. obtain the tag by taking the bitwise-and of the value with $111$ ($7$
  16559. in decimal).
  16560. %
  16561. {\if\edition\racketEd
  16562. \begin{lstlisting}
  16563. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16564. |$\Rightarrow$|
  16565. movq |$e'$|, |\itm{lhs'}|
  16566. andq $7, |\itm{lhs'}|
  16567. \end{lstlisting}
  16568. \fi}
  16569. %
  16570. {\if\edition\pythonEd
  16571. \begin{lstlisting}
  16572. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16573. |$\Rightarrow$|
  16574. movq |$e'$|, |\itm{lhs'}|
  16575. andq $7, |\itm{lhs'}|
  16576. \end{lstlisting}
  16577. \fi}
  16578. \paragraph{\code{ValueOf}}
  16579. Like \code{make\_any}, the instructions for \key{ValueOf} are
  16580. different depending on whether the type $T$ is a pointer (tuple or
  16581. function) or not (integer or Boolean). The following shows the
  16582. instruction selection for integers and Booleans. We produce an
  16583. untagged value by shifting it to the right by 3 bits.
  16584. %
  16585. {\if\edition\racketEd
  16586. \begin{lstlisting}
  16587. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16588. |$\Rightarrow$|
  16589. movq |$e'$|, |\itm{lhs'}|
  16590. sarq $3, |\itm{lhs'}|
  16591. \end{lstlisting}
  16592. \fi}
  16593. %
  16594. {\if\edition\pythonEd
  16595. \begin{lstlisting}
  16596. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16597. |$\Rightarrow$|
  16598. movq |$e'$|, |\itm{lhs'}|
  16599. sarq $3, |\itm{lhs'}|
  16600. \end{lstlisting}
  16601. \fi}
  16602. %
  16603. In the case for tuples and procedures, we just need to zero-out the
  16604. rightmost 3 bits. We accomplish this by creating the bit pattern
  16605. $\ldots 0111$ ($7$ in decimal) and apply bitwise-not to obtain $\ldots
  16606. 11111000$ (-8 in decimal) which we \code{movq} into the destination
  16607. $\itm{lhs'}$. Finally, we apply \code{andq} with the tagged value to
  16608. get the desired result.
  16609. %
  16610. {\if\edition\racketEd
  16611. \begin{lstlisting}
  16612. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16613. |$\Rightarrow$|
  16614. movq $|$-8$|, |\itm{lhs'}|
  16615. andq |$e'$|, |\itm{lhs'}|
  16616. \end{lstlisting}
  16617. \fi}
  16618. %
  16619. {\if\edition\pythonEd
  16620. \begin{lstlisting}
  16621. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16622. |$\Rightarrow$|
  16623. movq $|$-8$|, |\itm{lhs'}|
  16624. andq |$e'$|, |\itm{lhs'}|
  16625. \end{lstlisting}
  16626. \fi}
  16627. %% \paragraph{Type Predicates} We leave it to the reader to
  16628. %% devise a sequence of instructions to implement the type predicates
  16629. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16630. \paragraph{\racket{Any-vector-length}\python{\code{any\_len}}}
  16631. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16632. operation combines the effect of \code{ValueOf} with accessing the
  16633. length of a tuple from the tag stored at the zero index of the tuple.
  16634. {\if\edition\racketEd
  16635. \begin{lstlisting}
  16636. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16637. |$\Longrightarrow$|
  16638. movq $|$-8$|, %r11
  16639. andq |$e_1'$|, %r11
  16640. movq 0(%r11), %r11
  16641. andq $126, %r11
  16642. sarq $1, %r11
  16643. movq %r11, |$\itm{lhs'}$|
  16644. \end{lstlisting}
  16645. \fi}
  16646. {\if\edition\pythonEd
  16647. \begin{lstlisting}
  16648. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16649. |$\Longrightarrow$|
  16650. movq $|$-8$|, %r11
  16651. andq |$e_1'$|, %r11
  16652. movq 0(%r11), %r11
  16653. andq $126, %r11
  16654. sarq $1, %r11
  16655. movq %r11, |$\itm{lhs'}$|
  16656. \end{lstlisting}
  16657. \fi}
  16658. \paragraph{\racket{Any-vector-ref}\python{\code{\code{any\_tuple\_load}}}}
  16659. This operation combines the effect of \code{ValueOf} with reading an
  16660. element of the tuple (see
  16661. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16662. an arbitrary atom so instead of computing the offset at compile time,
  16663. we must generate instructions to compute the offset at runtime as
  16664. follows. Note the use of the new instruction \code{imulq}.
  16665. \begin{center}
  16666. \begin{minipage}{0.96\textwidth}
  16667. {\if\edition\racketEd
  16668. \begin{lstlisting}
  16669. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16670. |$\Longrightarrow$|
  16671. movq |$\neg 111$|, %r11
  16672. andq |$e_1'$|, %r11
  16673. movq |$e_2'$|, %rax
  16674. addq $1, %rax
  16675. imulq $8, %rax
  16676. addq %rax, %r11
  16677. movq 0(%r11) |$\itm{lhs'}$|
  16678. \end{lstlisting}
  16679. \fi}
  16680. %
  16681. {\if\edition\pythonEd
  16682. \begin{lstlisting}
  16683. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|]))
  16684. |$\Longrightarrow$|
  16685. movq $|$-8$|, %r11
  16686. andq |$e_1'$|, %r11
  16687. movq |$e_2'$|, %rax
  16688. addq $1, %rax
  16689. imulq $8, %rax
  16690. addq %rax, %r11
  16691. movq 0(%r11) |$\itm{lhs'}$|
  16692. \end{lstlisting}
  16693. \fi}
  16694. \end{minipage}
  16695. \end{center}
  16696. \paragraph{\racket{Any-vector-set!}\python{\code{any\_tuple\_store}}}
  16697. The code generation for
  16698. \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16699. analogous to the above translation for reading from a tuple.
  16700. \section{Register Allocation for \LangAny{}}
  16701. \label{sec:register-allocation-Rany}
  16702. \index{subject}{register allocation}
  16703. There is an interesting interaction between tagged values and garbage
  16704. collection that has an impact on register allocation. A variable of
  16705. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16706. that needs to be inspected and copied during garbage collection. Thus,
  16707. we need to treat variables of type \ANYTY{} in a similar way to
  16708. variables of tuple type for purposes of register allocation. In
  16709. particular,
  16710. \begin{itemize}
  16711. \item If a variable of type \ANYTY{} is live during a function call,
  16712. then it must be spilled. This can be accomplished by changing
  16713. \code{build\_interference} to mark all variables of type \ANYTY{}
  16714. that are live after a \code{callq} as interfering with all the
  16715. registers.
  16716. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16717. the root stack instead of the normal procedure call stack.
  16718. \end{itemize}
  16719. Another concern regarding the root stack is that the garbage collector
  16720. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16721. tagged value that points to a tuple, and (3) a tagged value that is
  16722. not a tuple. We enable this differentiation by choosing not to use the
  16723. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16724. reserved for identifying plain old pointers to tuples. That way, if
  16725. one of the first three bits is set, then we have a tagged value and
  16726. inspecting the tag can differentiation between tuples ($010$) and the
  16727. other kinds of values.
  16728. %% \begin{exercise}\normalfont
  16729. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16730. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16731. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16732. %% compiler on these new programs and all of your previously created test
  16733. %% programs.
  16734. %% \end{exercise}
  16735. \begin{exercise}\normalfont
  16736. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16737. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16738. by removing type annotations. Add 5 more tests programs that
  16739. specifically rely on the language being dynamically typed. That is,
  16740. they should not be legal programs in a statically typed language, but
  16741. nevertheless, they should be valid \LangDyn{} programs that run to
  16742. completion without error.
  16743. \end{exercise}
  16744. \begin{figure}[p]
  16745. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16746. \node (Rfun) at (0,4) {\large \LangDyn{}};
  16747. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  16748. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  16749. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  16750. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  16751. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  16752. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  16753. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  16754. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  16755. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  16756. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  16757. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16758. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16759. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16760. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16761. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16762. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16763. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16764. \path[->,bend left=15] (Rfun) edge [above] node
  16765. {\ttfamily\footnotesize shrink} (Rfun-2);
  16766. \path[->,bend left=15] (Rfun-2) edge [above] node
  16767. {\ttfamily\footnotesize uniquify} (Rfun-3);
  16768. \path[->,bend left=15] (Rfun-3) edge [above] node
  16769. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  16770. \path[->,bend right=15] (Rfun-4) edge [left] node
  16771. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  16772. \path[->,bend left=15] (Rfun-5) edge [above] node
  16773. {\ttfamily\footnotesize reveal\_casts} (Rfun-6);
  16774. \path[->,bend left=15] (Rfun-6) edge [left] node
  16775. {\ttfamily\footnotesize convert\_assign.} (Rfun-7);
  16776. \path[->,bend left=15] (Rfun-7) edge [below] node
  16777. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16778. \path[->,bend right=15] (F1-2) edge [above] node
  16779. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16780. \path[->,bend right=15] (F1-3) edge [above] node
  16781. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16782. \path[->,bend right=15] (F1-4) edge [above] node
  16783. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16784. \path[->,bend right=15] (F1-5) edge [right] node
  16785. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16786. \path[->,bend left=15] (C3-2) edge [left] node
  16787. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16788. \path[->,bend right=15] (x86-2) edge [left] node
  16789. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16790. \path[->,bend right=15] (x86-2-1) edge [below] node
  16791. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16792. \path[->,bend right=15] (x86-2-2) edge [left] node
  16793. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16794. \path[->,bend left=15] (x86-3) edge [above] node
  16795. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16796. \path[->,bend left=15] (x86-4) edge [right] node
  16797. {\ttfamily\footnotesize print\_x86} (x86-5);
  16798. \end{tikzpicture}
  16799. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16800. \label{fig:Rdyn-passes}
  16801. \end{figure}
  16802. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  16803. for the compilation of \LangDyn{}.
  16804. % Further Reading
  16805. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16806. %% {\if\edition\pythonEd
  16807. %% \chapter{Objects}
  16808. %% \label{ch:Lobject}
  16809. %% \index{subject}{objects}
  16810. %% \index{subject}{classes}
  16811. %% \fi}
  16812. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16813. \chapter{Gradual Typing}
  16814. \label{ch:Lgrad}
  16815. \index{subject}{gradual typing}
  16816. \if\edition\pythonEd
  16817. UNDER CONSTRUCTION
  16818. \fi
  16819. \if\edition\racketEd
  16820. This chapter studies a language, \LangGrad{}, in which the programmer
  16821. can choose between static and dynamic type checking in different parts
  16822. of a program, thereby mixing the statically typed \LangLoop{} language
  16823. with the dynamically typed \LangDyn{}. There are several approaches to
  16824. mixing static and dynamic typing, including multi-language
  16825. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16826. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16827. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16828. programmer controls the amount of static versus dynamic checking by
  16829. adding or removing type annotations on parameters and
  16830. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16831. %
  16832. The concrete syntax of \LangGrad{} is defined in
  16833. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  16834. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  16835. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16836. non-terminals that make type annotations optional. The return types
  16837. are not optional in the abstract syntax; the parser fills in
  16838. \code{Any} when the return type is not specified in the concrete
  16839. syntax.
  16840. \begin{figure}[tp]
  16841. \centering
  16842. \fbox{
  16843. \begin{minipage}{0.96\textwidth}
  16844. \small
  16845. \[
  16846. \begin{array}{lcl}
  16847. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16848. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16849. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  16850. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  16851. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  16852. &\MID& \gray{\key{\#t} \MID \key{\#f}
  16853. \MID (\key{and}\;\Exp\;\Exp)
  16854. \MID (\key{or}\;\Exp\;\Exp)
  16855. \MID (\key{not}\;\Exp) } \\
  16856. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  16857. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  16858. (\key{vector-ref}\;\Exp\;\Int)} \\
  16859. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  16860. \MID (\Exp \; \Exp\ldots) } \\
  16861. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  16862. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16863. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  16864. \MID \CBEGIN{\Exp\ldots}{\Exp}
  16865. \MID \CWHILE{\Exp}{\Exp} } \\
  16866. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  16867. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16868. \end{array}
  16869. \]
  16870. \end{minipage}
  16871. }
  16872. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16873. \label{fig:Rgrad-concrete-syntax}
  16874. \end{figure}
  16875. \begin{figure}[tp]
  16876. \centering
  16877. \fbox{
  16878. \begin{minipage}{0.96\textwidth}
  16879. \small
  16880. \[
  16881. \begin{array}{lcl}
  16882. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16883. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  16884. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  16885. &\MID& \gray{ \BOOL{\itm{bool}}
  16886. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  16887. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  16888. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  16889. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16890. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  16891. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  16892. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  16893. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16894. \end{array}
  16895. \]
  16896. \end{minipage}
  16897. }
  16898. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16899. \label{fig:Rgrad-syntax}
  16900. \end{figure}
  16901. Both the type checker and the interpreter for \LangGrad{} require some
  16902. interesting changes to enable gradual typing, which we discuss in the
  16903. next two sections in the context of the \code{map} example from
  16904. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  16905. revised the \code{map} example, omitting the type annotations from
  16906. the \code{inc} function.
  16907. \begin{figure}[btp]
  16908. % gradual_test_9.rkt
  16909. \begin{lstlisting}
  16910. (define (map [f : (Integer -> Integer)]
  16911. [v : (Vector Integer Integer)])
  16912. : (Vector Integer Integer)
  16913. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16914. (define (inc x) (+ x 1))
  16915. (vector-ref (map inc (vector 0 41)) 1)
  16916. \end{lstlisting}
  16917. \caption{A partially-typed version of the \code{map} example.}
  16918. \label{fig:gradual-map}
  16919. \end{figure}
  16920. \section{Type Checking \LangGrad{} and \LangCast{}}
  16921. \label{sec:gradual-type-check}
  16922. The type checker for \LangGrad{} uses the \code{Any} type for missing
  16923. parameter and return types. For example, the \code{x} parameter of
  16924. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  16925. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  16926. consider the \code{+} operator inside \code{inc}. It expects both
  16927. arguments to have type \code{Integer}, but its first argument \code{x}
  16928. has type \code{Any}. In a gradually typed language, such differences
  16929. are allowed so long as the types are \emph{consistent}, that is, they
  16930. are equal except in places where there is an \code{Any} type. The type
  16931. \code{Any} is consistent with every other type.
  16932. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  16933. \begin{figure}[tbp]
  16934. \begin{lstlisting}
  16935. (define/public (consistent? t1 t2)
  16936. (match* (t1 t2)
  16937. [('Integer 'Integer) #t]
  16938. [('Boolean 'Boolean) #t]
  16939. [('Void 'Void) #t]
  16940. [('Any t2) #t]
  16941. [(t1 'Any) #t]
  16942. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16943. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  16944. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16945. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  16946. (consistent? rt1 rt2))]
  16947. [(other wise) #f]))
  16948. \end{lstlisting}
  16949. \caption{The consistency predicate on types.}
  16950. \label{fig:consistent}
  16951. \end{figure}
  16952. Returning to the \code{map} example of
  16953. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  16954. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  16955. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  16956. because the two types are consistent. In particular, \code{->} is
  16957. equal to \code{->} and because \code{Any} is consistent with
  16958. \code{Integer}.
  16959. Next consider a program with an error, such as applying the
  16960. \code{map} to a function that sometimes returns a Boolean, as
  16961. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  16962. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  16963. consistent with the type of parameter \code{f} of \code{map}, that
  16964. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  16965. Integer)}. One might say that a gradual type checker is optimistic
  16966. in that it accepts programs that might execute without a runtime type
  16967. error.
  16968. %
  16969. Unfortunately, running this program with input \code{1} triggers an
  16970. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  16971. performs checking at runtime to ensure the integrity of the static
  16972. types, such as the \code{(Integer -> Integer)} annotation on parameter
  16973. \code{f} of \code{map}. This runtime checking is carried out by a
  16974. new \code{Cast} form that is inserted by the type checker. Thus, the
  16975. output of the type checker is a program in the \LangCast{} language, which
  16976. adds \code{Cast} to \LangLoop{}, as shown in
  16977. Figure~\ref{fig:Rgrad-prime-syntax}.
  16978. \begin{figure}[tp]
  16979. \centering
  16980. \fbox{
  16981. \begin{minipage}{0.96\textwidth}
  16982. \small
  16983. \[
  16984. \begin{array}{lcl}
  16985. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  16986. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16987. \end{array}
  16988. \]
  16989. \end{minipage}
  16990. }
  16991. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16992. \label{fig:Rgrad-prime-syntax}
  16993. \end{figure}
  16994. \begin{figure}[tbp]
  16995. \begin{lstlisting}
  16996. (define (map [f : (Integer -> Integer)]
  16997. [v : (Vector Integer Integer)])
  16998. : (Vector Integer Integer)
  16999. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17000. (define (inc x) (+ x 1))
  17001. (define (true) #t)
  17002. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  17003. (vector-ref (map maybe-inc (vector 0 41)) 0)
  17004. \end{lstlisting}
  17005. \caption{A variant of the \code{map} example with an error.}
  17006. \label{fig:map-maybe-inc}
  17007. \end{figure}
  17008. Figure~\ref{fig:map-cast} shows the output of the type checker for
  17009. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  17010. inserted every time the type checker sees two types that are
  17011. consistent but not equal. In the \code{inc} function, \code{x} is
  17012. cast to \code{Integer} and the result of the \code{+} is cast to
  17013. \code{Any}. In the call to \code{map}, the \code{inc} argument
  17014. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  17015. \begin{figure}[btp]
  17016. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17017. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17018. : (Vector Integer Integer)
  17019. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17020. (define (inc [x : Any]) : Any
  17021. (cast (+ (cast x Any Integer) 1) Integer Any))
  17022. (define (true) : Any (cast #t Boolean Any))
  17023. (define (maybe-inc [x : Any]) : Any
  17024. (if (eq? 0 (read)) (inc x) (true)))
  17025. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  17026. (vector 0 41)) 0)
  17027. \end{lstlisting}
  17028. \caption{Output of type checking \code{map}
  17029. and \code{maybe-inc}.}
  17030. \label{fig:map-cast}
  17031. \end{figure}
  17032. The type checker for \LangGrad{} is defined in
  17033. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  17034. and \ref{fig:type-check-Rgradual-3}.
  17035. \begin{figure}[tbp]
  17036. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17037. (define type-check-gradual_class
  17038. (class type-check-Rwhile_class
  17039. (super-new)
  17040. (inherit operator-types type-predicates)
  17041. (define/override (type-check-exp env)
  17042. (lambda (e)
  17043. (define recur (type-check-exp env))
  17044. (match e
  17045. [(Prim 'vector-length (list e1))
  17046. (define-values (e1^ t) (recur e1))
  17047. (match t
  17048. [`(Vector ,ts ...)
  17049. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17050. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17051. [(Prim 'vector-ref (list e1 e2))
  17052. (define-values (e1^ t1) (recur e1))
  17053. (define-values (e2^ t2) (recur e2))
  17054. (check-consistent? t2 'Integer e)
  17055. (match t1
  17056. [`(Vector ,ts ...)
  17057. (match e2^
  17058. [(Int i)
  17059. (unless (and (0 . <= . i) (i . < . (length ts)))
  17060. (error 'type-check "invalid index ~a in ~a" i e))
  17061. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17062. [else (define e1^^ (make-cast e1^ t1 'Any))
  17063. (define e2^^ (make-cast e2^ t2 'Integer))
  17064. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17065. ['Any
  17066. (define e2^^ (make-cast e2^ t2 'Integer))
  17067. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17068. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17069. [(Prim 'vector-set! (list e1 e2 e3) )
  17070. (define-values (e1^ t1) (recur e1))
  17071. (define-values (e2^ t2) (recur e2))
  17072. (define-values (e3^ t3) (recur e3))
  17073. (check-consistent? t2 'Integer e)
  17074. (match t1
  17075. [`(Vector ,ts ...)
  17076. (match e2^
  17077. [(Int i)
  17078. (unless (and (0 . <= . i) (i . < . (length ts)))
  17079. (error 'type-check "invalid index ~a in ~a" i e))
  17080. (check-consistent? (list-ref ts i) t3 e)
  17081. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17082. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17083. [else
  17084. (define e1^^ (make-cast e1^ t1 'Any))
  17085. (define e2^^ (make-cast e2^ t2 'Integer))
  17086. (define e3^^ (make-cast e3^ t3 'Any))
  17087. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17088. ['Any
  17089. (define e2^^ (make-cast e2^ t2 'Integer))
  17090. (define e3^^ (make-cast e3^ t3 'Any))
  17091. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17092. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17093. \end{lstlisting}
  17094. \caption{Type checker for the \LangGrad{} language, part 1.}
  17095. \label{fig:type-check-Rgradual-1}
  17096. \end{figure}
  17097. \begin{figure}[tbp]
  17098. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17099. [(Prim 'eq? (list e1 e2))
  17100. (define-values (e1^ t1) (recur e1))
  17101. (define-values (e2^ t2) (recur e2))
  17102. (check-consistent? t1 t2 e)
  17103. (define T (meet t1 t2))
  17104. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17105. 'Boolean)]
  17106. [(Prim 'not (list e1))
  17107. (define-values (e1^ t1) (recur e1))
  17108. (match t1
  17109. ['Any
  17110. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17111. (Bool #t) (Bool #f)))]
  17112. [else
  17113. (define-values (t-ret new-es^)
  17114. (type-check-op 'not (list t1) (list e1^) e))
  17115. (values (Prim 'not new-es^) t-ret)])]
  17116. [(Prim 'and (list e1 e2))
  17117. (recur (If e1 e2 (Bool #f)))]
  17118. [(Prim 'or (list e1 e2))
  17119. (define tmp (gensym 'tmp))
  17120. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17121. [(Prim op es)
  17122. #:when (not (set-member? explicit-prim-ops op))
  17123. (define-values (new-es ts)
  17124. (for/lists (exprs types) ([e es])
  17125. (recur e)))
  17126. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17127. (values (Prim op new-es^) t-ret)]
  17128. [(If e1 e2 e3)
  17129. (define-values (e1^ T1) (recur e1))
  17130. (define-values (e2^ T2) (recur e2))
  17131. (define-values (e3^ T3) (recur e3))
  17132. (check-consistent? T2 T3 e)
  17133. (match T1
  17134. ['Boolean
  17135. (define Tif (join T2 T3))
  17136. (values (If e1^ (make-cast e2^ T2 Tif)
  17137. (make-cast e3^ T3 Tif)) Tif)]
  17138. ['Any
  17139. (define Tif (meet T2 T3))
  17140. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17141. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17142. Tif)]
  17143. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17144. [(HasType e1 T)
  17145. (define-values (e1^ T1) (recur e1))
  17146. (check-consistent? T1 T)
  17147. (values (make-cast e1^ T1 T) T)]
  17148. [(SetBang x e1)
  17149. (define-values (e1^ T1) (recur e1))
  17150. (define varT (dict-ref env x))
  17151. (check-consistent? T1 varT e)
  17152. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17153. [(WhileLoop e1 e2)
  17154. (define-values (e1^ T1) (recur e1))
  17155. (check-consistent? T1 'Boolean e)
  17156. (define-values (e2^ T2) ((type-check-exp env) e2))
  17157. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17158. \end{lstlisting}
  17159. \caption{Type checker for the \LangGrad{} language, part 2.}
  17160. \label{fig:type-check-Rgradual-2}
  17161. \end{figure}
  17162. \begin{figure}[tbp]
  17163. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17164. [(Apply e1 e2s)
  17165. (define-values (e1^ T1) (recur e1))
  17166. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17167. (match T1
  17168. [`(,T1ps ... -> ,T1rt)
  17169. (for ([T2 T2s] [Tp T1ps])
  17170. (check-consistent? T2 Tp e))
  17171. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17172. (make-cast e2 src tgt)))
  17173. (values (Apply e1^ e2s^^) T1rt)]
  17174. [`Any
  17175. (define e1^^ (make-cast e1^ 'Any
  17176. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17177. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17178. (make-cast e2 src 'Any)))
  17179. (values (Apply e1^^ e2s^^) 'Any)]
  17180. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17181. [(Lambda params Tr e1)
  17182. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17183. (match p
  17184. [`[,x : ,T] (values x T)]
  17185. [(? symbol? x) (values x 'Any)])))
  17186. (define-values (e1^ T1)
  17187. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17188. (check-consistent? Tr T1 e)
  17189. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17190. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17191. [else ((super type-check-exp env) e)]
  17192. )))
  17193. \end{lstlisting}
  17194. \caption{Type checker for the \LangGrad{} language, part 3.}
  17195. \label{fig:type-check-Rgradual-3}
  17196. \end{figure}
  17197. \begin{figure}[tbp]
  17198. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17199. (define/public (join t1 t2)
  17200. (match* (t1 t2)
  17201. [('Integer 'Integer) 'Integer]
  17202. [('Boolean 'Boolean) 'Boolean]
  17203. [('Void 'Void) 'Void]
  17204. [('Any t2) t2]
  17205. [(t1 'Any) t1]
  17206. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17207. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17208. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17209. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17210. -> ,(join rt1 rt2))]))
  17211. (define/public (meet t1 t2)
  17212. (match* (t1 t2)
  17213. [('Integer 'Integer) 'Integer]
  17214. [('Boolean 'Boolean) 'Boolean]
  17215. [('Void 'Void) 'Void]
  17216. [('Any t2) 'Any]
  17217. [(t1 'Any) 'Any]
  17218. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17219. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17220. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17221. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17222. -> ,(meet rt1 rt2))]))
  17223. (define/public (make-cast e src tgt)
  17224. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17225. (define/public (check-consistent? t1 t2 e)
  17226. (unless (consistent? t1 t2)
  17227. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17228. (define/override (type-check-op op arg-types args e)
  17229. (match (dict-ref (operator-types) op)
  17230. [`(,param-types . ,return-type)
  17231. (for ([at arg-types] [pt param-types])
  17232. (check-consistent? at pt e))
  17233. (values return-type
  17234. (for/list ([e args] [s arg-types] [t param-types])
  17235. (make-cast e s t)))]
  17236. [else (error 'type-check-op "unrecognized ~a" op)]))
  17237. (define explicit-prim-ops
  17238. (set-union
  17239. (type-predicates)
  17240. (set 'procedure-arity 'eq?
  17241. 'vector 'vector-length 'vector-ref 'vector-set!
  17242. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17243. (define/override (fun-def-type d)
  17244. (match d
  17245. [(Def f params rt info body)
  17246. (define ps
  17247. (for/list ([p params])
  17248. (match p
  17249. [`[,x : ,T] T]
  17250. [(? symbol?) 'Any]
  17251. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17252. `(,@ps -> ,rt)]
  17253. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17254. \end{lstlisting}
  17255. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17256. \label{fig:type-check-Rgradual-aux}
  17257. \end{figure}
  17258. \clearpage
  17259. \section{Interpreting \LangCast{}}
  17260. \label{sec:interp-casts}
  17261. The runtime behavior of first-order casts is straightforward, that is,
  17262. casts involving simple types such as \code{Integer} and
  17263. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  17264. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  17265. puts the integer into a tagged value
  17266. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  17267. \code{Integer} is accomplished with the \code{Project} operator, that
  17268. is, by checking the value's tag and either retrieving the underlying
  17269. integer or signaling an error if it the tag is not the one for
  17270. integers (Figure~\ref{fig:interp-Rany-aux}).
  17271. %
  17272. Things get more interesting for higher-order casts, that is, casts
  17273. involving function or vector types.
  17274. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  17275. Any)} to \code{(Integer -> Integer)}. When a function flows through
  17276. this cast at runtime, we can't know in general whether the function
  17277. will always return an integer.\footnote{Predicting the return value of
  17278. a function is equivalent to the halting problem, which is
  17279. undecidable.} The \LangCast{} interpreter therefore delays the checking
  17280. of the cast until the function is applied. This is accomplished by
  17281. wrapping \code{maybe-inc} in a new function that casts its parameter
  17282. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  17283. casts the return value from \code{Any} to \code{Integer}.
  17284. Turning our attention to casts involving vector types, we consider the
  17285. example in Figure~\ref{fig:map-bang} that defines a
  17286. partially-typed version of \code{map} whose parameter \code{v} has
  17287. type \code{(Vector Any Any)} and that updates \code{v} in place
  17288. instead of returning a new vector. So we name this function
  17289. \code{map!}. We apply \code{map!} to a vector of integers, so
  17290. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17291. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17292. cast between vector types would be a build a new vector whose elements
  17293. are the result of casting each of the original elements to the
  17294. appropriate target type. However, this approach is only valid for
  17295. immutable vectors; and our vectors are mutable. In the example of
  17296. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  17297. the updates inside of \code{map!} would happen to the new vector
  17298. and not the original one.
  17299. \begin{figure}[tbp]
  17300. % gradual_test_11.rkt
  17301. \begin{lstlisting}
  17302. (define (map! [f : (Any -> Any)]
  17303. [v : (Vector Any Any)]) : Void
  17304. (begin
  17305. (vector-set! v 0 (f (vector-ref v 0)))
  17306. (vector-set! v 1 (f (vector-ref v 1)))))
  17307. (define (inc x) (+ x 1))
  17308. (let ([v (vector 0 41)])
  17309. (begin (map! inc v) (vector-ref v 1)))
  17310. \end{lstlisting}
  17311. \caption{An example involving casts on vectors.}
  17312. \label{fig:map-bang}
  17313. \end{figure}
  17314. Instead the interpreter needs to create a new kind of value, a
  17315. \emph{vector proxy}, that intercepts every vector operation. On a
  17316. read, the proxy reads from the underlying vector and then applies a
  17317. cast to the resulting value. On a write, the proxy casts the argument
  17318. value and then performs the write to the underlying vector. For the
  17319. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17320. \code{0} from \code{Integer} to \code{Any}. For the first
  17321. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  17322. to \code{Integer}.
  17323. The final category of cast that we need to consider are casts between
  17324. the \code{Any} type and either a function or a vector
  17325. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17326. in which parameter \code{v} does not have a type annotation, so it is
  17327. given type \code{Any}. In the call to \code{map!}, the vector has
  17328. type \code{(Vector Integer Integer)} so the type checker inserts a
  17329. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  17330. thought is to use \code{Inject}, but that doesn't work because
  17331. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17332. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17333. to \code{Any}.
  17334. \begin{figure}[tbp]
  17335. \begin{lstlisting}
  17336. (define (map! [f : (Any -> Any)] v) : Void
  17337. (begin
  17338. (vector-set! v 0 (f (vector-ref v 0)))
  17339. (vector-set! v 1 (f (vector-ref v 1)))))
  17340. (define (inc x) (+ x 1))
  17341. (let ([v (vector 0 41)])
  17342. (begin (map! inc v) (vector-ref v 1)))
  17343. \end{lstlisting}
  17344. \caption{Casting a vector to \code{Any}.}
  17345. \label{fig:map-any}
  17346. \end{figure}
  17347. The \LangCast{} interpreter uses an auxiliary function named
  17348. \code{apply-cast} to cast a value from a source type to a target type,
  17349. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17350. of the kinds of casts that we've discussed in this section.
  17351. \begin{figure}[tbp]
  17352. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17353. (define/public (apply-cast v s t)
  17354. (match* (s t)
  17355. [(t1 t2) #:when (equal? t1 t2) v]
  17356. [('Any t2)
  17357. (match t2
  17358. [`(,ts ... -> ,rt)
  17359. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17360. (define v^ (apply-project v any->any))
  17361. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17362. [`(Vector ,ts ...)
  17363. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17364. (define v^ (apply-project v vec-any))
  17365. (apply-cast v^ vec-any `(Vector ,@ts))]
  17366. [else (apply-project v t2)])]
  17367. [(t1 'Any)
  17368. (match t1
  17369. [`(,ts ... -> ,rt)
  17370. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17371. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17372. (apply-inject v^ (any-tag any->any))]
  17373. [`(Vector ,ts ...)
  17374. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17375. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17376. (apply-inject v^ (any-tag vec-any))]
  17377. [else (apply-inject v (any-tag t1))])]
  17378. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17379. (define x (gensym 'x))
  17380. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17381. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17382. (define cast-writes
  17383. (for/list ([t1 ts1] [t2 ts2])
  17384. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17385. `(vector-proxy ,(vector v (apply vector cast-reads)
  17386. (apply vector cast-writes)))]
  17387. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17388. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17389. `(function ,xs ,(Cast
  17390. (Apply (Value v)
  17391. (for/list ([x xs][t1 ts1][t2 ts2])
  17392. (Cast (Var x) t2 t1)))
  17393. rt1 rt2) ())]
  17394. ))
  17395. \end{lstlisting}
  17396. \caption{The \code{apply-cast} auxiliary method.}
  17397. \label{fig:apply-cast}
  17398. \end{figure}
  17399. The interpreter for \LangCast{} is defined in
  17400. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  17401. dispatching to \code{apply-cast}. To handle the addition of vector
  17402. proxies, we update the vector primitives in \code{interp-op} using the
  17403. functions in Figure~\ref{fig:guarded-vector}.
  17404. \begin{figure}[tbp]
  17405. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17406. (define interp-Rcast_class
  17407. (class interp-Rwhile_class
  17408. (super-new)
  17409. (inherit apply-fun apply-inject apply-project)
  17410. (define/override (interp-op op)
  17411. (match op
  17412. ['vector-length guarded-vector-length]
  17413. ['vector-ref guarded-vector-ref]
  17414. ['vector-set! guarded-vector-set!]
  17415. ['any-vector-ref (lambda (v i)
  17416. (match v [`(tagged ,v^ ,tg)
  17417. (guarded-vector-ref v^ i)]))]
  17418. ['any-vector-set! (lambda (v i a)
  17419. (match v [`(tagged ,v^ ,tg)
  17420. (guarded-vector-set! v^ i a)]))]
  17421. ['any-vector-length (lambda (v)
  17422. (match v [`(tagged ,v^ ,tg)
  17423. (guarded-vector-length v^)]))]
  17424. [else (super interp-op op)]
  17425. ))
  17426. (define/override ((interp-exp env) e)
  17427. (define (recur e) ((interp-exp env) e))
  17428. (match e
  17429. [(Value v) v]
  17430. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17431. [else ((super interp-exp env) e)]))
  17432. ))
  17433. (define (interp-Rcast p)
  17434. (send (new interp-Rcast_class) interp-program p))
  17435. \end{lstlisting}
  17436. \caption{The interpreter for \LangCast{}.}
  17437. \label{fig:interp-Rcast}
  17438. \end{figure}
  17439. \begin{figure}[tbp]
  17440. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17441. (define (guarded-vector-ref vec i)
  17442. (match vec
  17443. [`(vector-proxy ,proxy)
  17444. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17445. (define rd (vector-ref (vector-ref proxy 1) i))
  17446. (apply-fun rd (list val) 'guarded-vector-ref)]
  17447. [else (vector-ref vec i)]))
  17448. (define (guarded-vector-set! vec i arg)
  17449. (match vec
  17450. [`(vector-proxy ,proxy)
  17451. (define wr (vector-ref (vector-ref proxy 2) i))
  17452. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17453. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17454. [else (vector-set! vec i arg)]))
  17455. (define (guarded-vector-length vec)
  17456. (match vec
  17457. [`(vector-proxy ,proxy)
  17458. (guarded-vector-length (vector-ref proxy 0))]
  17459. [else (vector-length vec)]))
  17460. \end{lstlisting}
  17461. \caption{The guarded-vector auxiliary functions.}
  17462. \label{fig:guarded-vector}
  17463. \end{figure}
  17464. \section{Lower Casts}
  17465. \label{sec:lower-casts}
  17466. The next step in the journey towards x86 is the \code{lower-casts}
  17467. pass that translates the casts in \LangCast{} to the lower-level
  17468. \code{Inject} and \code{Project} operators and a new operator for
  17469. creating vector proxies, extending the \LangLoop{} language to create
  17470. \LangProxy{}. We recommend creating an auxiliary function named
  17471. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17472. and a target type, and translates it to expression in \LangProxy{} that has
  17473. the same behavior as casting the expression from the source to the
  17474. target type in the interpreter.
  17475. The \code{lower-cast} function can follow a code structure similar to
  17476. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17477. the interpreter for \LangCast{} because it must handle the same cases as
  17478. \code{apply-cast} and it needs to mimic the behavior of
  17479. \code{apply-cast}. The most interesting cases are those concerning the
  17480. casts between two vector types and between two function types.
  17481. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  17482. type to another vector type is accomplished by creating a proxy that
  17483. intercepts the operations on the underlying vector. Here we make the
  17484. creation of the proxy explicit with the \code{vector-proxy} primitive
  17485. operation. It takes three arguments, the first is an expression for
  17486. the vector, the second is a vector of functions for casting an element
  17487. that is being read from the vector, and the third is a vector of
  17488. functions for casting an element that is being written to the vector.
  17489. You can create the functions using \code{Lambda}. Also, as we shall
  17490. see in the next section, we need to differentiate these vectors from
  17491. the user-created ones, so we recommend using a new primitive operator
  17492. named \code{raw-vector} instead of \code{vector} to create these
  17493. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17494. the output of \code{lower-casts} on the example in
  17495. Figure~\ref{fig:map-bang} that involved casting a vector of
  17496. integers to a vector of \code{Any}.
  17497. \begin{figure}[tbp]
  17498. \begin{lstlisting}
  17499. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17500. (begin
  17501. (vector-set! v 0 (f (vector-ref v 0)))
  17502. (vector-set! v 1 (f (vector-ref v 1)))))
  17503. (define (inc [x : Any]) : Any
  17504. (inject (+ (project x Integer) 1) Integer))
  17505. (let ([v (vector 0 41)])
  17506. (begin
  17507. (map! inc (vector-proxy v
  17508. (raw-vector (lambda: ([x9 : Integer]) : Any
  17509. (inject x9 Integer))
  17510. (lambda: ([x9 : Integer]) : Any
  17511. (inject x9 Integer)))
  17512. (raw-vector (lambda: ([x9 : Any]) : Integer
  17513. (project x9 Integer))
  17514. (lambda: ([x9 : Any]) : Integer
  17515. (project x9 Integer)))))
  17516. (vector-ref v 1)))
  17517. \end{lstlisting}
  17518. \caption{Output of \code{lower-casts} on the example in
  17519. Figure~\ref{fig:map-bang}.}
  17520. \label{fig:map-bang-lower-cast}
  17521. \end{figure}
  17522. A cast from one function type to another function type is accomplished
  17523. by generating a \code{Lambda} whose parameter and return types match
  17524. the target function type. The body of the \code{Lambda} should cast
  17525. the parameters from the target type to the source type (yes,
  17526. backwards! functions are contravariant\index{subject}{contravariant} in the
  17527. parameters), then call the underlying function, and finally cast the
  17528. result from the source return type to the target return type.
  17529. Figure~\ref{fig:map-lower-cast} shows the output of the
  17530. \code{lower-casts} pass on the \code{map} example in
  17531. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  17532. in the call to \code{map} is wrapped in a \code{lambda}.
  17533. \begin{figure}[tbp]
  17534. \begin{lstlisting}
  17535. (define (map [f : (Integer -> Integer)]
  17536. [v : (Vector Integer Integer)])
  17537. : (Vector Integer Integer)
  17538. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17539. (define (inc [x : Any]) : Any
  17540. (inject (+ (project x Integer) 1) Integer))
  17541. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17542. (project (inc (inject x9 Integer)) Integer))
  17543. (vector 0 41)) 1)
  17544. \end{lstlisting}
  17545. \caption{Output of \code{lower-casts} on the example in
  17546. Figure~\ref{fig:gradual-map}.}
  17547. \label{fig:map-lower-cast}
  17548. \end{figure}
  17549. \section{Differentiate Proxies}
  17550. \label{sec:differentiate-proxies}
  17551. So far the job of differentiating vectors and vector proxies has been
  17552. the job of the interpreter. For example, the interpreter for \LangCast{}
  17553. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17554. function in Figure~\ref{fig:guarded-vector}. In the
  17555. \code{differentiate-proxies} pass we shift this responsibility to the
  17556. generated code.
  17557. We begin by designing the output language $R^p_8$. In
  17558. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  17559. proxies. In $R^p_8$ we return the \code{Vector} type to
  17560. its original meaning, as the type of real vectors, and we introduce a
  17561. new type, \code{PVector}, whose values can be either real vectors or
  17562. vector proxies. This new type comes with a suite of new primitive
  17563. operations for creating and using values of type \code{PVector}. We
  17564. don't need to introduce a new type to represent vector proxies. A
  17565. proxy is represented by a vector containing three things: 1) the
  17566. underlying vector, 2) a vector of functions for casting elements that
  17567. are read from the vector, and 3) a vector of functions for casting
  17568. values to be written to the vector. So we define the following
  17569. abbreviation for the type of a vector proxy:
  17570. \[
  17571. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17572. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17573. \to (\key{PVector}~ T' \ldots)
  17574. \]
  17575. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17576. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17577. %
  17578. Next we describe each of the new primitive operations.
  17579. \begin{description}
  17580. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17581. (\key{PVector} $T \ldots$)]\ \\
  17582. %
  17583. This operation brands a vector as a value of the \code{PVector} type.
  17584. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17585. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17586. %
  17587. This operation brands a vector proxy as value of the \code{PVector} type.
  17588. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17589. \code{Boolean}] \ \\
  17590. %
  17591. returns true if the value is a vector proxy and false if it is a
  17592. real vector.
  17593. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17594. (\key{Vector} $T \ldots$)]\ \\
  17595. %
  17596. Assuming that the input is a vector (and not a proxy), this
  17597. operation returns the vector.
  17598. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17599. $\to$ \code{Boolean}]\ \\
  17600. %
  17601. Given a vector proxy, this operation returns the length of the
  17602. underlying vector.
  17603. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17604. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17605. %
  17606. Given a vector proxy, this operation returns the $i$th element of
  17607. the underlying vector.
  17608. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17609. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  17610. proxy, this operation writes a value to the $i$th element of the
  17611. underlying vector.
  17612. \end{description}
  17613. Now to discuss the translation that differentiates vectors from
  17614. proxies. First, every type annotation in the program must be
  17615. translated (recursively) to replace \code{Vector} with \code{PVector}.
  17616. Next, we must insert uses of \code{PVector} operations in the
  17617. appropriate places. For example, we wrap every vector creation with an
  17618. \code{inject-vector}.
  17619. \begin{lstlisting}
  17620. (vector |$e_1 \ldots e_n$|)
  17621. |$\Rightarrow$|
  17622. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17623. \end{lstlisting}
  17624. The \code{raw-vector} operator that we introduced in the previous
  17625. section does not get injected.
  17626. \begin{lstlisting}
  17627. (raw-vector |$e_1 \ldots e_n$|)
  17628. |$\Rightarrow$|
  17629. (vector |$e'_1 \ldots e'_n$|)
  17630. \end{lstlisting}
  17631. The \code{vector-proxy} primitive translates as follows.
  17632. \begin{lstlisting}
  17633. (vector-proxy |$e_1~e_2~e_3$|)
  17634. |$\Rightarrow$|
  17635. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17636. \end{lstlisting}
  17637. We translate the vector operations into conditional expressions that
  17638. check whether the value is a proxy and then dispatch to either the
  17639. appropriate proxy vector operation or the regular vector operation.
  17640. For example, the following is the translation for \code{vector-ref}.
  17641. \begin{lstlisting}
  17642. (vector-ref |$e_1$| |$i$|)
  17643. |$\Rightarrow$|
  17644. (let ([|$v~e_1$|])
  17645. (if (proxy? |$v$|)
  17646. (proxy-vector-ref |$v$| |$i$|)
  17647. (vector-ref (project-vector |$v$|) |$i$|)
  17648. \end{lstlisting}
  17649. Note in the case of a real vector, we must apply \code{project-vector}
  17650. before the \code{vector-ref}.
  17651. \section{Reveal Casts}
  17652. \label{sec:reveal-casts-gradual}
  17653. Recall that the \code{reveal-casts} pass
  17654. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  17655. \code{Inject} and \code{Project} into lower-level operations. In
  17656. particular, \code{Project} turns into a conditional expression that
  17657. inspects the tag and retrieves the underlying value. Here we need to
  17658. augment the translation of \code{Project} to handle the situation when
  17659. the target type is \code{PVector}. Instead of using
  17660. \code{vector-length} we need to use \code{proxy-vector-length}.
  17661. \begin{lstlisting}
  17662. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17663. |$\Rightarrow$|
  17664. (let |$\itm{tmp}$| |$e'$|
  17665. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17666. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17667. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17668. (exit)))
  17669. \end{lstlisting}
  17670. \section{Closure Conversion}
  17671. \label{sec:closure-conversion-gradual}
  17672. The closure conversion pass only requires one minor adjustment. The
  17673. auxiliary function that translates type annotations needs to be
  17674. updated to handle the \code{PVector} type.
  17675. \section{Explicate Control}
  17676. \label{sec:explicate-control-gradual}
  17677. Update the \code{explicate\_control} pass to handle the new primitive
  17678. operations on the \code{PVector} type.
  17679. \section{Select Instructions}
  17680. \label{sec:select-instructions-gradual}
  17681. Recall that the \code{select\_instructions} pass is responsible for
  17682. lowering the primitive operations into x86 instructions. So we need
  17683. to translate the new \code{PVector} operations to x86. To do so, the
  17684. first question we need to answer is how will we differentiate the two
  17685. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  17686. We need just one bit to accomplish this, and use the bit in position
  17687. $57$ of the 64-bit tag at the front of every vector (see
  17688. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  17689. for \code{inject-vector} we leave it that way.
  17690. \begin{lstlisting}
  17691. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  17692. |$\Rightarrow$|
  17693. movq |$e'_1$|, |$\itm{lhs'}$|
  17694. \end{lstlisting}
  17695. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  17696. \begin{lstlisting}
  17697. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  17698. |$\Rightarrow$|
  17699. movq |$e'_1$|, %r11
  17700. movq |$(1 << 57)$|, %rax
  17701. orq 0(%r11), %rax
  17702. movq %rax, 0(%r11)
  17703. movq %r11, |$\itm{lhs'}$|
  17704. \end{lstlisting}
  17705. The \code{proxy?} operation consumes the information so carefully
  17706. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  17707. isolates the $57$th bit to tell whether the value is a real vector or
  17708. a proxy.
  17709. \begin{lstlisting}
  17710. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  17711. |$\Rightarrow$|
  17712. movq |$e_1'$|, %r11
  17713. movq 0(%r11), %rax
  17714. sarq $57, %rax
  17715. andq $1, %rax
  17716. movq %rax, |$\itm{lhs'}$|
  17717. \end{lstlisting}
  17718. The \code{project-vector} operation is straightforward to translate,
  17719. so we leave it up to the reader.
  17720. Regarding the \code{proxy-vector} operations, the runtime provides
  17721. procedures that implement them (they are recursive functions!) so
  17722. here we simply need to translate these vector operations into the
  17723. appropriate function call. For example, here is the translation for
  17724. \code{proxy-vector-ref}.
  17725. \begin{lstlisting}
  17726. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  17727. |$\Rightarrow$|
  17728. movq |$e_1'$|, %rdi
  17729. movq |$e_2'$|, %rsi
  17730. callq proxy_vector_ref
  17731. movq %rax, |$\itm{lhs'}$|
  17732. \end{lstlisting}
  17733. We have another batch of vector operations to deal with, those for the
  17734. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  17735. \code{any-vector-ref} when there is a \code{vector-ref} on something
  17736. of type \code{Any}, and similarly for \code{any-vector-set!} and
  17737. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  17738. Section~\ref{sec:select-Rany} we selected instructions for these
  17739. operations based on the idea that the underlying value was a real
  17740. vector. But in the current setting, the underlying value is of type
  17741. \code{PVector}. So \code{any-vector-ref} can be translates to
  17742. pseudo-x86 as follows. We begin by projecting the underlying value out
  17743. of the tagged value and then call the \code{proxy\_vector\_ref}
  17744. procedure in the runtime.
  17745. \begin{lstlisting}
  17746. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17747. movq |$\neg 111$|, %rdi
  17748. andq |$e_1'$|, %rdi
  17749. movq |$e_2'$|, %rsi
  17750. callq proxy_vector_ref
  17751. movq %rax, |$\itm{lhs'}$|
  17752. \end{lstlisting}
  17753. The \code{any-vector-set!} and \code{any-vector-length} operators can
  17754. be translated in a similar way.
  17755. \begin{exercise}\normalfont
  17756. Implement a compiler for the gradually-typed \LangGrad{} language by
  17757. extending and adapting your compiler for \LangLoop{}. Create 10 new
  17758. partially-typed test programs. In addition to testing with these
  17759. new programs, also test your compiler on all the tests for \LangLoop{}
  17760. and tests for \LangDyn{}. Sometimes you may get a type checking error
  17761. on the \LangDyn{} programs but you can adapt them by inserting
  17762. a cast to the \code{Any} type around each subexpression
  17763. causing a type error. While \LangDyn{} does not have explicit casts,
  17764. you can induce one by wrapping the subexpression \code{e}
  17765. with a call to an un-annotated identity function, like this:
  17766. \code{((lambda (x) x) e)}.
  17767. \end{exercise}
  17768. \begin{figure}[p]
  17769. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17770. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  17771. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17772. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17773. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17774. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17775. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17776. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17777. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17778. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17779. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17780. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17781. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17782. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17783. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17784. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17785. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17786. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17787. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17788. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17789. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17790. \path[->,bend right=15] (Rgradual) edge [above] node
  17791. {\ttfamily\footnotesize type\_check} (Rgradualp);
  17792. \path[->,bend right=15] (Rgradualp) edge [above] node
  17793. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17794. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17795. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17796. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17797. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17798. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17799. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17800. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17801. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17802. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17803. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17804. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17805. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17806. \path[->,bend left=15] (F1-1) edge [below] node
  17807. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17808. \path[->,bend right=15] (F1-2) edge [above] node
  17809. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17810. \path[->,bend right=15] (F1-3) edge [above] node
  17811. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17812. \path[->,bend right=15] (F1-4) edge [above] node
  17813. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17814. \path[->,bend right=15] (F1-5) edge [right] node
  17815. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17816. \path[->,bend left=15] (C3-2) edge [left] node
  17817. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17818. \path[->,bend right=15] (x86-2) edge [left] node
  17819. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17820. \path[->,bend right=15] (x86-2-1) edge [below] node
  17821. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17822. \path[->,bend right=15] (x86-2-2) edge [left] node
  17823. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17824. \path[->,bend left=15] (x86-3) edge [above] node
  17825. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17826. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  17827. \end{tikzpicture}
  17828. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17829. \label{fig:Rgradual-passes}
  17830. \end{figure}
  17831. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  17832. for the compilation of \LangGrad{}.
  17833. \section{Further Reading}
  17834. This chapter just scratches the surface of gradual typing. The basic
  17835. approach described here is missing two key ingredients that one would
  17836. want in a implementation of gradual typing: blame
  17837. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17838. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17839. problem addressed by blame tracking is that when a cast on a
  17840. higher-order value fails, it often does so at a point in the program
  17841. that is far removed from the original cast. Blame tracking is a
  17842. technique for propagating extra information through casts and proxies
  17843. so that when a cast fails, the error message can point back to the
  17844. original location of the cast in the source program.
  17845. The problem addressed by space-efficient casts also relates to
  17846. higher-order casts. It turns out that in partially typed programs, a
  17847. function or vector can flow through very-many casts at runtime. With
  17848. the approach described in this chapter, each cast adds another
  17849. \code{lambda} wrapper or a vector proxy. Not only does this take up
  17850. considerable space, but it also makes the function calls and vector
  17851. operations slow. For example, a partially-typed version of quicksort
  17852. could, in the worst case, build a chain of proxies of length $O(n)$
  17853. around the vector, changing the overall time complexity of the
  17854. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17855. solution to this problem by representing casts using the coercion
  17856. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17857. long chains of proxies by compressing them into a concise normal
  17858. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17859. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17860. the Grift compiler.
  17861. \begin{center}
  17862. \url{https://github.com/Gradual-Typing/Grift}
  17863. \end{center}
  17864. There are also interesting interactions between gradual typing and
  17865. other language features, such as parametetric polymorphism,
  17866. information-flow types, and type inference, to name a few. We
  17867. recommend the reader to the online gradual typing bibliography:
  17868. \begin{center}
  17869. \url{http://samth.github.io/gradual-typing-bib/}
  17870. \end{center}
  17871. % TODO: challenge problem:
  17872. % type analysis and type specialization?
  17873. % coercions?
  17874. \fi
  17875. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17876. \chapter{Parametric Polymorphism}
  17877. \label{ch:Lpoly}
  17878. \index{subject}{parametric polymorphism}
  17879. \index{subject}{generics}
  17880. \if\edition\pythonEd
  17881. UNDER CONSTRUCTION
  17882. \fi
  17883. \if\edition\racketEd
  17884. This chapter studies the compilation of parametric
  17885. polymorphism\index{subject}{parametric polymorphism}
  17886. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  17887. Racket. Parametric polymorphism enables improved code reuse by
  17888. parameterizing functions and data structures with respect to the types
  17889. that they operate on. For example, Figure~\ref{fig:map-poly}
  17890. revisits the \code{map} example but this time gives it a more
  17891. fitting type. This \code{map} function is parameterized with
  17892. respect to the element type of the vector. The type of \code{map}
  17893. is the following polymorphic type as specified by the \code{All} and
  17894. the type parameter \code{a}.
  17895. \begin{lstlisting}
  17896. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17897. \end{lstlisting}
  17898. The idea is that \code{map} can be used at \emph{all} choices of a
  17899. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17900. \code{map} to a vector of integers, a choice of \code{Integer} for
  17901. \code{a}, but we could have just as well applied \code{map} to a
  17902. vector of Booleans (and a function on Booleans).
  17903. \begin{figure}[tbp]
  17904. % poly_test_2.rkt
  17905. \begin{lstlisting}
  17906. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17907. (define (map f v)
  17908. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17909. (define (inc [x : Integer]) : Integer (+ x 1))
  17910. (vector-ref (map inc (vector 0 41)) 1)
  17911. \end{lstlisting}
  17912. \caption{The \code{map} example using parametric polymorphism.}
  17913. \label{fig:map-poly}
  17914. \end{figure}
  17915. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  17916. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  17917. syntax. We add a second form for function definitions in which a type
  17918. declaration comes before the \code{define}. In the abstract syntax,
  17919. the return type in the \code{Def} is \code{Any}, but that should be
  17920. ignored in favor of the return type in the type declaration. (The
  17921. \code{Any} comes from using the same parser as in
  17922. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  17923. enables the use of an \code{All} type for a function, thereby making
  17924. it polymorphic. The grammar for types is extended to include
  17925. polymorphic types and type variables.
  17926. \begin{figure}[tp]
  17927. \centering
  17928. \fbox{
  17929. \begin{minipage}{0.96\textwidth}
  17930. \small
  17931. \[
  17932. \begin{array}{lcl}
  17933. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17934. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  17935. &\MID& \LP\key{:}~\Var~\Type\RP \\
  17936. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  17937. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  17938. \end{array}
  17939. \]
  17940. \end{minipage}
  17941. }
  17942. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  17943. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  17944. \label{fig:Rpoly-concrete-syntax}
  17945. \end{figure}
  17946. \begin{figure}[tp]
  17947. \centering
  17948. \fbox{
  17949. \begin{minipage}{0.96\textwidth}
  17950. \small
  17951. \[
  17952. \begin{array}{lcl}
  17953. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17954. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  17955. &\MID& \DECL{\Var}{\Type} \\
  17956. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  17957. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17958. \end{array}
  17959. \]
  17960. \end{minipage}
  17961. }
  17962. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  17963. (Figure~\ref{fig:Lwhile-syntax}).}
  17964. \label{fig:Rpoly-syntax}
  17965. \end{figure}
  17966. By including polymorphic types in the $\Type$ non-terminal we choose
  17967. to make them first-class which has interesting repercussions on the
  17968. compiler. Many languages with polymorphism, such as
  17969. C++~\citep{stroustrup88:_param_types} and Standard
  17970. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  17971. it is useful to see an example of first-class polymorphism. In
  17972. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  17973. whose parameter is a polymorphic function. The occurrence of a
  17974. polymorphic type underneath a function type is enabled by the normal
  17975. recursive structure of the grammar for $\Type$ and the categorization
  17976. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  17977. applies the polymorphic function to a Boolean and to an integer.
  17978. \begin{figure}[tbp]
  17979. \begin{lstlisting}
  17980. (: apply-twice ((All (b) (b -> b)) -> Integer))
  17981. (define (apply-twice f)
  17982. (if (f #t) (f 42) (f 777)))
  17983. (: id (All (a) (a -> a)))
  17984. (define (id x) x)
  17985. (apply-twice id)
  17986. \end{lstlisting}
  17987. \caption{An example illustrating first-class polymorphism.}
  17988. \label{fig:apply-twice}
  17989. \end{figure}
  17990. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  17991. three new responsibilities (compared to \LangLoop{}). The type checking of
  17992. function application is extended to handle the case where the operator
  17993. expression is a polymorphic function. In that case the type arguments
  17994. are deduced by matching the type of the parameters with the types of
  17995. the arguments.
  17996. %
  17997. The \code{match-types} auxiliary function carries out this deduction
  17998. by recursively descending through a parameter type \code{pt} and the
  17999. corresponding argument type \code{at}, making sure that they are equal
  18000. except when there is a type parameter on the left (in the parameter
  18001. type). If it is the first time that the type parameter has been
  18002. encountered, then the algorithm deduces an association of the type
  18003. parameter to the corresponding type on the right (in the argument
  18004. type). If it is not the first time that the type parameter has been
  18005. encountered, the algorithm looks up its deduced type and makes sure
  18006. that it is equal to the type on the right.
  18007. %
  18008. Once the type arguments are deduced, the operator expression is
  18009. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18010. type of the operator, but more importantly, records the deduced type
  18011. arguments. The return type of the application is the return type of
  18012. the polymorphic function, but with the type parameters replaced by the
  18013. deduced type arguments, using the \code{subst-type} function.
  18014. The second responsibility of the type checker is extending the
  18015. function \code{type-equal?} to handle the \code{All} type. This is
  18016. not quite a simple as equal on other types, such as function and
  18017. vector types, because two polymorphic types can be syntactically
  18018. different even though they are equivalent types. For example,
  18019. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  18020. Two polymorphic types should be considered equal if they differ only
  18021. in the choice of the names of the type parameters. The
  18022. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  18023. renames the type parameters of the first type to match the type
  18024. parameters of the second type.
  18025. The third responsibility of the type checker is making sure that only
  18026. defined type variables appear in type annotations. The
  18027. \code{check-well-formed} function defined in
  18028. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18029. sure that each type variable has been defined.
  18030. The output language of the type checker is \LangInst{}, defined in
  18031. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  18032. declaration and polymorphic function into a single definition, using
  18033. the \code{Poly} form, to make polymorphic functions more convenient to
  18034. process in next pass of the compiler.
  18035. \begin{figure}[tp]
  18036. \centering
  18037. \fbox{
  18038. \begin{minipage}{0.96\textwidth}
  18039. \small
  18040. \[
  18041. \begin{array}{lcl}
  18042. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18043. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18044. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18045. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18046. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18047. \end{array}
  18048. \]
  18049. \end{minipage}
  18050. }
  18051. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  18052. (Figure~\ref{fig:Lwhile-syntax}).}
  18053. \label{fig:Rpoly-prime-syntax}
  18054. \end{figure}
  18055. The output of the type checker on the polymorphic \code{map}
  18056. example is listed in Figure~\ref{fig:map-type-check}.
  18057. \begin{figure}[tbp]
  18058. % poly_test_2.rkt
  18059. \begin{lstlisting}
  18060. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18061. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18062. (define (inc [x : Integer]) : Integer (+ x 1))
  18063. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18064. (Integer))
  18065. inc (vector 0 41)) 1)
  18066. \end{lstlisting}
  18067. \caption{Output of the type checker on the \code{map} example.}
  18068. \label{fig:map-type-check}
  18069. \end{figure}
  18070. \begin{figure}[tbp]
  18071. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18072. (define type-check-poly-class
  18073. (class type-check-Rwhile-class
  18074. (super-new)
  18075. (inherit check-type-equal?)
  18076. (define/override (type-check-apply env e1 es)
  18077. (define-values (e^ ty) ((type-check-exp env) e1))
  18078. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18079. ((type-check-exp env) e)))
  18080. (match ty
  18081. [`(,ty^* ... -> ,rt)
  18082. (for ([arg-ty ty*] [param-ty ty^*])
  18083. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18084. (values e^ es^ rt)]
  18085. [`(All ,xs (,tys ... -> ,rt))
  18086. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18087. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18088. (match-types env^^ param-ty arg-ty)))
  18089. (define targs
  18090. (for/list ([x xs])
  18091. (match (dict-ref env^^ x (lambda () #f))
  18092. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18093. x (Apply e1 es))]
  18094. [ty ty])))
  18095. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18096. [else (error 'type-check "expected a function, not ~a" ty)]))
  18097. (define/override ((type-check-exp env) e)
  18098. (match e
  18099. [(Lambda `([,xs : ,Ts] ...) rT body)
  18100. (for ([T Ts]) ((check-well-formed env) T))
  18101. ((check-well-formed env) rT)
  18102. ((super type-check-exp env) e)]
  18103. [(HasType e1 ty)
  18104. ((check-well-formed env) ty)
  18105. ((super type-check-exp env) e)]
  18106. [else ((super type-check-exp env) e)]))
  18107. (define/override ((type-check-def env) d)
  18108. (verbose 'type-check "poly/def" d)
  18109. (match d
  18110. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18111. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18112. (for ([p ps]) ((check-well-formed ts-env) p))
  18113. ((check-well-formed ts-env) rt)
  18114. (define new-env (append ts-env (map cons xs ps) env))
  18115. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18116. (check-type-equal? ty^ rt body)
  18117. (Generic ts (Def f p:t* rt info body^))]
  18118. [else ((super type-check-def env) d)]))
  18119. (define/override (type-check-program p)
  18120. (match p
  18121. [(Program info body)
  18122. (type-check-program (ProgramDefsExp info '() body))]
  18123. [(ProgramDefsExp info ds body)
  18124. (define ds^ (combine-decls-defs ds))
  18125. (define new-env (for/list ([d ds^])
  18126. (cons (def-name d) (fun-def-type d))))
  18127. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18128. (define-values (body^ ty) ((type-check-exp new-env) body))
  18129. (check-type-equal? ty 'Integer body)
  18130. (ProgramDefsExp info ds^^ body^)]))
  18131. ))
  18132. \end{lstlisting}
  18133. \caption{Type checker for the \LangPoly{} language.}
  18134. \label{fig:type-check-Lvar0}
  18135. \end{figure}
  18136. \begin{figure}[tbp]
  18137. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18138. (define/override (type-equal? t1 t2)
  18139. (match* (t1 t2)
  18140. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18141. (define env (map cons xs ys))
  18142. (type-equal? (subst-type env T1) T2)]
  18143. [(other wise)
  18144. (super type-equal? t1 t2)]))
  18145. (define/public (match-types env pt at)
  18146. (match* (pt at)
  18147. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18148. [('Void 'Void) env] [('Any 'Any) env]
  18149. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18150. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18151. (match-types env^ pt1 at1))]
  18152. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18153. (define env^ (match-types env prt art))
  18154. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18155. (match-types env^^ pt1 at1))]
  18156. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18157. (define env^ (append (map cons pxs axs) env))
  18158. (match-types env^ pt1 at1)]
  18159. [((? symbol? x) at)
  18160. (match (dict-ref env x (lambda () #f))
  18161. [#f (error 'type-check "undefined type variable ~a" x)]
  18162. ['Type (cons (cons x at) env)]
  18163. [t^ (check-type-equal? at t^ 'matching) env])]
  18164. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18165. (define/public (subst-type env pt)
  18166. (match pt
  18167. ['Integer 'Integer] ['Boolean 'Boolean]
  18168. ['Void 'Void] ['Any 'Any]
  18169. [`(Vector ,ts ...)
  18170. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18171. [`(,ts ... -> ,rt)
  18172. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18173. [`(All ,xs ,t)
  18174. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18175. [(? symbol? x) (dict-ref env x)]
  18176. [else (error 'type-check "expected a type not ~a" pt)]))
  18177. (define/public (combine-decls-defs ds)
  18178. (match ds
  18179. ['() '()]
  18180. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18181. (unless (equal? name f)
  18182. (error 'type-check "name mismatch, ~a != ~a" name f))
  18183. (match type
  18184. [`(All ,xs (,ps ... -> ,rt))
  18185. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18186. (cons (Generic xs (Def name params^ rt info body))
  18187. (combine-decls-defs ds^))]
  18188. [`(,ps ... -> ,rt)
  18189. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18190. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18191. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18192. [`(,(Def f params rt info body) . ,ds^)
  18193. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18194. \end{lstlisting}
  18195. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18196. \label{fig:type-check-Lvar0-aux}
  18197. \end{figure}
  18198. \begin{figure}[tbp]
  18199. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18200. (define/public ((check-well-formed env) ty)
  18201. (match ty
  18202. ['Integer (void)]
  18203. ['Boolean (void)]
  18204. ['Void (void)]
  18205. [(? symbol? a)
  18206. (match (dict-ref env a (lambda () #f))
  18207. ['Type (void)]
  18208. [else (error 'type-check "undefined type variable ~a" a)])]
  18209. [`(Vector ,ts ...)
  18210. (for ([t ts]) ((check-well-formed env) t))]
  18211. [`(,ts ... -> ,t)
  18212. (for ([t ts]) ((check-well-formed env) t))
  18213. ((check-well-formed env) t)]
  18214. [`(All ,xs ,t)
  18215. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18216. ((check-well-formed env^) t)]
  18217. [else (error 'type-check "unrecognized type ~a" ty)]))
  18218. \end{lstlisting}
  18219. \caption{Well-formed types.}
  18220. \label{fig:well-formed-types}
  18221. \end{figure}
  18222. % TODO: interpreter for R'_10
  18223. \section{Compiling Polymorphism}
  18224. \label{sec:compiling-poly}
  18225. Broadly speaking, there are four approaches to compiling parametric
  18226. polymorphism, which we describe below.
  18227. \begin{description}
  18228. \item[Monomorphization] generates a different version of a polymorphic
  18229. function for each set of type arguments that it is used with,
  18230. producing type-specialized code. This approach results in the most
  18231. efficient code but requires whole-program compilation (no separate
  18232. compilation) and increases code size. For our current purposes
  18233. monomorphization is a non-starter because, with first-class
  18234. polymorphism, it is sometimes not possible to determine which
  18235. generic functions are used with which type arguments during
  18236. compilation. (It can be done at runtime, with just-in-time
  18237. compilation.) This approach is used to compile C++
  18238. templates~\citep{stroustrup88:_param_types} and polymorphic
  18239. functions in NESL~\citep{Blelloch:1993aa} and
  18240. ML~\citep{Weeks:2006aa}.
  18241. \item[Uniform representation] generates one version of each
  18242. polymorphic function but requires all values have a common ``boxed''
  18243. format, such as the tagged values of type \code{Any} in
  18244. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  18245. similarly to code in a dynamically typed language (like \LangDyn{}),
  18246. in which primitive operators require their arguments to be projected
  18247. from \code{Any} and their results are injected into \code{Any}. (In
  18248. object-oriented languages, the projection is accomplished via
  18249. virtual method dispatch.) The uniform representation approach is
  18250. compatible with separate compilation and with first-class
  18251. polymorphism. However, it produces the least-efficient code because
  18252. it introduces overhead in the entire program, including
  18253. non-polymorphic code. This approach is used in implementations of
  18254. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18255. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18256. Java~\citep{Bracha:1998fk}.
  18257. \item[Mixed representation] generates one version of each polymorphic
  18258. function, using a boxed representation for type
  18259. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  18260. and conversions are performed at the boundaries between monomorphic
  18261. and polymorphic (e.g. when a polymorphic function is instantiated
  18262. and called). This approach is compatible with separate compilation
  18263. and first-class polymorphism and maintains the efficiency of
  18264. monomorphic code. The tradeoff is increased overhead at the boundary
  18265. between monomorphic and polymorphic code. This approach is used in
  18266. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18267. Java 5 with the addition of autoboxing.
  18268. \item[Type passing] uses the unboxed representation in both
  18269. monomorphic and polymorphic code. Each polymorphic function is
  18270. compiled to a single function with extra parameters that describe
  18271. the type arguments. The type information is used by the generated
  18272. code to know how to access the unboxed values at runtime. This
  18273. approach is used in implementation of the Napier88
  18274. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18275. passing is compatible with separate compilation and first-class
  18276. polymorphism and maintains the efficiency for monomorphic
  18277. code. There is runtime overhead in polymorphic code from dispatching
  18278. on type information.
  18279. \end{description}
  18280. In this chapter we use the mixed representation approach, partly
  18281. because of its favorable attributes, and partly because it is
  18282. straightforward to implement using the tools that we have already
  18283. built to support gradual typing. To compile polymorphic functions, we
  18284. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18285. \LangCast{}.
  18286. \section{Erase Types}
  18287. \label{sec:erase-types}
  18288. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  18289. represent type variables. For example, Figure~\ref{fig:map-erase}
  18290. shows the output of the \code{erase-types} pass on the polymorphic
  18291. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18292. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  18293. \code{All} types are removed from the type of \code{map}.
  18294. \begin{figure}[tbp]
  18295. \begin{lstlisting}
  18296. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18297. : (Vector Any Any)
  18298. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18299. (define (inc [x : Integer]) : Integer (+ x 1))
  18300. (vector-ref ((cast map
  18301. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18302. ((Integer -> Integer) (Vector Integer Integer)
  18303. -> (Vector Integer Integer)))
  18304. inc (vector 0 41)) 1)
  18305. \end{lstlisting}
  18306. \caption{The polymorphic \code{map} example after type erasure.}
  18307. \label{fig:map-erase}
  18308. \end{figure}
  18309. This process of type erasure creates a challenge at points of
  18310. instantiation. For example, consider the instantiation of
  18311. \code{map} in Figure~\ref{fig:map-type-check}.
  18312. The type of \code{map} is
  18313. \begin{lstlisting}
  18314. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18315. \end{lstlisting}
  18316. and it is instantiated to
  18317. \begin{lstlisting}
  18318. ((Integer -> Integer) (Vector Integer Integer)
  18319. -> (Vector Integer Integer))
  18320. \end{lstlisting}
  18321. After erasure, the type of \code{map} is
  18322. \begin{lstlisting}
  18323. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18324. \end{lstlisting}
  18325. but we need to convert it to the instantiated type. This is easy to
  18326. do in the target language \LangCast{} with a single \code{cast}. In
  18327. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  18328. has been compiled to a \code{cast} from the type of \code{map} to
  18329. the instantiated type. The source and target type of a cast must be
  18330. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18331. because both the source and target are obtained from the same
  18332. polymorphic type of \code{map}, replacing the type parameters with
  18333. \code{Any} in the former and with the deduced type arguments in the
  18334. later. (Recall that the \code{Any} type is consistent with any type.)
  18335. To implement the \code{erase-types} pass, we recommend defining a
  18336. recursive auxiliary function named \code{erase-type} that applies the
  18337. following two transformations. It replaces type variables with
  18338. \code{Any}
  18339. \begin{lstlisting}
  18340. |$x$|
  18341. |$\Rightarrow$|
  18342. Any
  18343. \end{lstlisting}
  18344. and it removes the polymorphic \code{All} types.
  18345. \begin{lstlisting}
  18346. (All |$xs$| |$T_1$|)
  18347. |$\Rightarrow$|
  18348. |$T'_1$|
  18349. \end{lstlisting}
  18350. Apply the \code{erase-type} function to all of the type annotations in
  18351. the program.
  18352. Regarding the translation of expressions, the case for \code{Inst} is
  18353. the interesting one. We translate it into a \code{Cast}, as shown
  18354. below. The type of the subexpression $e$ is the polymorphic type
  18355. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  18356. $T$, the type $T'$. The target type $T''$ is the result of
  18357. substituting the arguments types $ts$ for the type parameters $xs$ in
  18358. $T$ followed by doing type erasure.
  18359. \begin{lstlisting}
  18360. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18361. |$\Rightarrow$|
  18362. (Cast |$e'$| |$T'$| |$T''$|)
  18363. \end{lstlisting}
  18364. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18365. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18366. Finally, each polymorphic function is translated to a regular
  18367. functions in which type erasure has been applied to all the type
  18368. annotations and the body.
  18369. \begin{lstlisting}
  18370. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18371. |$\Rightarrow$|
  18372. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18373. \end{lstlisting}
  18374. \begin{exercise}\normalfont
  18375. Implement a compiler for the polymorphic language \LangPoly{} by
  18376. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18377. programs that use polymorphic functions. Some of them should make
  18378. use of first-class polymorphism.
  18379. \end{exercise}
  18380. \begin{figure}[p]
  18381. \begin{tikzpicture}[baseline=(current bounding box.center)]
  18382. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  18383. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  18384. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  18385. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  18386. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  18387. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  18388. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  18389. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  18390. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  18391. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  18392. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  18393. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  18394. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  18395. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  18396. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18397. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18398. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18399. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18400. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18401. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18402. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18403. \path[->,bend right=15] (Rpoly) edge [above] node
  18404. {\ttfamily\footnotesize type\_check} (Rpolyp);
  18405. \path[->,bend right=15] (Rpolyp) edge [above] node
  18406. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  18407. \path[->,bend right=15] (Rgradualp) edge [above] node
  18408. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  18409. \path[->,bend right=15] (Rwhilepp) edge [right] node
  18410. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  18411. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  18412. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  18413. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  18414. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  18415. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  18416. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  18417. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  18418. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  18419. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  18420. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18421. \path[->,bend left=15] (F1-1) edge [below] node
  18422. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18423. \path[->,bend right=15] (F1-2) edge [above] node
  18424. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18425. \path[->,bend right=15] (F1-3) edge [above] node
  18426. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18427. \path[->,bend right=15] (F1-4) edge [above] node
  18428. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  18429. \path[->,bend right=15] (F1-5) edge [right] node
  18430. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18431. \path[->,bend left=15] (C3-2) edge [left] node
  18432. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18433. \path[->,bend right=15] (x86-2) edge [left] node
  18434. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18435. \path[->,bend right=15] (x86-2-1) edge [below] node
  18436. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18437. \path[->,bend right=15] (x86-2-2) edge [left] node
  18438. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18439. \path[->,bend left=15] (x86-3) edge [above] node
  18440. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18441. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  18442. \end{tikzpicture}
  18443. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18444. \label{fig:Rpoly-passes}
  18445. \end{figure}
  18446. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  18447. for the compilation of \LangPoly{}.
  18448. % TODO: challenge problem: specialization of instantiations
  18449. % Further Reading
  18450. \fi
  18451. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18452. \clearpage
  18453. \appendix
  18454. \chapter{Appendix}
  18455. \if\edition\racketEd
  18456. \section{Interpreters}
  18457. \label{appendix:interp}
  18458. \index{subject}{interpreter}
  18459. We provide interpreters for each of the source languages \LangInt{},
  18460. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18461. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18462. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18463. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18464. and x86 are in the \key{interp.rkt} file.
  18465. \section{Utility Functions}
  18466. \label{appendix:utilities}
  18467. The utility functions described in this section are in the
  18468. \key{utilities.rkt} file of the support code.
  18469. \paragraph{\code{interp-tests}}
  18470. The \key{interp-tests} function runs the compiler passes and the
  18471. interpreters on each of the specified tests to check whether each pass
  18472. is correct. The \key{interp-tests} function has the following
  18473. parameters:
  18474. \begin{description}
  18475. \item[name (a string)] a name to identify the compiler,
  18476. \item[typechecker] a function of exactly one argument that either
  18477. raises an error using the \code{error} function when it encounters a
  18478. type error, or returns \code{\#f} when it encounters a type
  18479. error. If there is no type error, the type checker returns the
  18480. program.
  18481. \item[passes] a list with one entry per pass. An entry is a list with
  18482. four things:
  18483. \begin{enumerate}
  18484. \item a string giving the name of the pass,
  18485. \item the function that implements the pass (a translator from AST
  18486. to AST),
  18487. \item a function that implements the interpreter (a function from
  18488. AST to result value) for the output language,
  18489. \item and a type checker for the output language. Type checkers for
  18490. the $R$ and $C$ languages are provided in the support code. For
  18491. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18492. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18493. type checker entry is optional. The support code does not provide
  18494. type checkers for the x86 languages.
  18495. \end{enumerate}
  18496. \item[source-interp] an interpreter for the source language. The
  18497. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18498. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  18499. \item[tests] a list of test numbers that specifies which tests to
  18500. run. (see below)
  18501. \end{description}
  18502. %
  18503. The \key{interp-tests} function assumes that the subdirectory
  18504. \key{tests} has a collection of Racket programs whose names all start
  18505. with the family name, followed by an underscore and then the test
  18506. number, ending with the file extension \key{.rkt}. Also, for each test
  18507. program that calls \code{read} one or more times, there is a file with
  18508. the same name except that the file extension is \key{.in} that
  18509. provides the input for the Racket program. If the test program is
  18510. expected to fail type checking, then there should be an empty file of
  18511. the same name but with extension \key{.tyerr}.
  18512. \paragraph{\code{compiler-tests}}
  18513. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18514. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18515. machine code and checks that the output is $42$. The parameters to the
  18516. \code{compiler-tests} function are similar to those of the
  18517. \code{interp-tests} function, and consist of
  18518. \begin{itemize}
  18519. \item a compiler name (a string),
  18520. \item a type checker,
  18521. \item description of the passes,
  18522. \item name of a test-family, and
  18523. \item a list of test numbers.
  18524. \end{itemize}
  18525. \paragraph{\code{compile-file}}
  18526. takes a description of the compiler passes (see the comment for
  18527. \key{interp-tests}) and returns a function that, given a program file
  18528. name (a string ending in \key{.rkt}), applies all of the passes and
  18529. writes the output to a file whose name is the same as the program file
  18530. name but with \key{.rkt} replaced with \key{.s}.
  18531. \paragraph{\code{read-program}}
  18532. takes a file path and parses that file (it must be a Racket program)
  18533. into an abstract syntax tree.
  18534. \paragraph{\code{parse-program}}
  18535. takes an S-expression representation of an abstract syntax tree and converts it into
  18536. the struct-based representation.
  18537. \paragraph{\code{assert}}
  18538. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18539. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18540. \paragraph{\code{lookup}}
  18541. % remove discussion of lookup? -Jeremy
  18542. takes a key and an alist, and returns the first value that is
  18543. associated with the given key, if there is one. If not, an error is
  18544. triggered. The alist may contain both immutable pairs (built with
  18545. \key{cons}) and mutable pairs (built with \key{mcons}).
  18546. %The \key{map2} function ...
  18547. \fi %\racketEd
  18548. \section{x86 Instruction Set Quick-Reference}
  18549. \label{sec:x86-quick-reference}
  18550. \index{subject}{x86}
  18551. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18552. do. We write $A \to B$ to mean that the value of $A$ is written into
  18553. location $B$. Address offsets are given in bytes. The instruction
  18554. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18555. registers (such as \code{\%rax}), or memory references (such as
  18556. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18557. reference per instruction. Other operands must be immediates or
  18558. registers.
  18559. \begin{table}[tbp]
  18560. \centering
  18561. \begin{tabular}{l|l}
  18562. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18563. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18564. \texttt{negq} $A$ & $- A \to A$ \\
  18565. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18566. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18567. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18568. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18569. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18570. \texttt{retq} & Pops the return address and jumps to it \\
  18571. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18572. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18573. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18574. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18575. be an immediate) \\
  18576. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18577. matches the condition code of the instruction, otherwise go to the
  18578. next instructions. The condition codes are \key{e} for ``equal'',
  18579. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18580. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18581. \texttt{jl} $L$ & \\
  18582. \texttt{jle} $L$ & \\
  18583. \texttt{jg} $L$ & \\
  18584. \texttt{jge} $L$ & \\
  18585. \texttt{jmp} $L$ & Jump to label $L$ \\
  18586. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18587. \texttt{movzbq} $A$, $B$ &
  18588. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18589. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18590. and the extra bytes of $B$ are set to zero.} \\
  18591. & \\
  18592. & \\
  18593. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18594. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18595. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18596. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18597. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18598. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18599. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18600. description of the condition codes. $A$ must be a single byte register
  18601. (e.g., \texttt{al} or \texttt{cl}).} \\
  18602. \texttt{setl} $A$ & \\
  18603. \texttt{setle} $A$ & \\
  18604. \texttt{setg} $A$ & \\
  18605. \texttt{setge} $A$ &
  18606. \end{tabular}
  18607. \vspace{5pt}
  18608. \caption{Quick-reference for the x86 instructions used in this book.}
  18609. \label{tab:x86-instr}
  18610. \end{table}
  18611. \if\edition\racketEd
  18612. \cleardoublepage
  18613. \section{Concrete Syntax for Intermediate Languages}
  18614. The concrete syntax of \LangAny{} is defined in
  18615. Figure~\ref{fig:Rany-concrete-syntax}.
  18616. \begin{figure}[tp]
  18617. \centering
  18618. \fbox{
  18619. \begin{minipage}{0.97\textwidth}\small
  18620. \[
  18621. \begin{array}{lcl}
  18622. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18623. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18624. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18625. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18626. \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18627. &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18628. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18629. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18630. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18631. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18632. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18633. \MID \LP\key{void?}\;\Exp\RP \\
  18634. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18635. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18636. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  18637. \end{array}
  18638. \]
  18639. \end{minipage}
  18640. }
  18641. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  18642. (Figure~\ref{fig:Rlam-syntax}).}
  18643. \label{fig:Rany-concrete-syntax}
  18644. \end{figure}
  18645. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  18646. \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  18647. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  18648. \ref{fig:c3-concrete-syntax}, respectively.
  18649. \begin{figure}[tbp]
  18650. \fbox{
  18651. \begin{minipage}{0.96\textwidth}
  18652. \small
  18653. \[
  18654. \begin{array}{lcl}
  18655. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  18656. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18657. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  18658. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  18659. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  18660. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  18661. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  18662. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  18663. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  18664. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  18665. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  18666. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  18667. \end{array}
  18668. \]
  18669. \end{minipage}
  18670. }
  18671. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  18672. \label{fig:c2-concrete-syntax}
  18673. \end{figure}
  18674. \begin{figure}[tp]
  18675. \fbox{
  18676. \begin{minipage}{0.96\textwidth}
  18677. \small
  18678. \[
  18679. \begin{array}{lcl}
  18680. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  18681. \\
  18682. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18683. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  18684. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  18685. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  18686. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  18687. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  18688. &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  18689. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  18690. \MID \LP\key{collect} \,\itm{int}\RP }\\
  18691. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  18692. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  18693. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  18694. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  18695. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  18696. \LangCFunM{} & ::= & \Def\ldots
  18697. \end{array}
  18698. \]
  18699. \end{minipage}
  18700. }
  18701. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  18702. \label{fig:c3-concrete-syntax}
  18703. \end{figure}
  18704. \fi % racketEd
  18705. \backmatter
  18706. \addtocontents{toc}{\vspace{11pt}}
  18707. %% \addtocontents{toc}{\vspace{11pt}}
  18708. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  18709. \nocite{*}\let\bibname\refname
  18710. \addcontentsline{toc}{fmbm}{\refname}
  18711. \printbibliography
  18712. \printindex{authors}{Author Index}
  18713. \printindex{subject}{Subject Index}
  18714. \end{document}
  18715. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  18716. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  18717. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  18718. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  18719. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  18720. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  18721. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  18722. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  18723. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  18724. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  18725. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  18726. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  18727. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  18728. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  18729. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  18730. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  18731. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  18732. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  18733. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  18734. % LocalWords: morekeywords fullflexible