book.tex 760 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089
  1. \documentclass[7x10,nocrop]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \definecolor{lightgray}{gray}{1}
  19. \newcommand{\black}[1]{{\color{black} #1}}
  20. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  21. \newcommand{\gray}[1]{{\color{gray} #1}}
  22. \def\racketEd{0}
  23. \def\pythonEd{1}
  24. \def\edition{1}
  25. % material that is specific to the Racket edition of the book
  26. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  27. % would like a command for: \if\edition\racketEd\color{olive}
  28. % and : \fi\color{black}
  29. % material that is specific to the Python edition of the book
  30. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  31. %% For multiple indices:
  32. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  33. \makeindex{subject}
  34. %\makeindex{authors}
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \if\edition\racketEd
  37. \lstset{%
  38. language=Lisp,
  39. basicstyle=\ttfamily\small,
  40. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  41. deletekeywords={read,mapping,vector},
  42. escapechar=|,
  43. columns=flexible,
  44. moredelim=[is][\color{red}]{~}{~},
  45. showstringspaces=false
  46. }
  47. \fi
  48. \if\edition\pythonEd
  49. \lstset{%
  50. language=Python,
  51. basicstyle=\ttfamily\small,
  52. morekeywords={match,case,bool,int,let},
  53. deletekeywords={},
  54. escapechar=|,
  55. columns=flexible,
  56. moredelim=[is][\color{red}]{~}{~},
  57. showstringspaces=false
  58. }
  59. \fi
  60. %%% Any shortcut own defined macros place here
  61. %% sample of author macro:
  62. \input{defs}
  63. \newtheorem{exercise}[theorem]{Exercise}
  64. % Adjusted settings
  65. \setlength{\columnsep}{4pt}
  66. %% \begingroup
  67. %% \setlength{\intextsep}{0pt}%
  68. %% \setlength{\columnsep}{0pt}%
  69. %% \begin{wrapfigure}{r}{0.5\textwidth}
  70. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  71. %% \caption{Basic layout}
  72. %% \end{wrapfigure}
  73. %% \lipsum[1]
  74. %% \endgroup
  75. \newbox\oiintbox
  76. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  77. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  78. \def\oiint{\copy\oiintbox}
  79. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  80. %\usepackage{showframe}
  81. \def\ShowFrameLinethickness{0.125pt}
  82. \addbibresource{book.bib}
  83. \begin{document}
  84. \frontmatter
  85. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  86. \halftitlepage
  87. \Title{Essentials of Compilation}
  88. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  89. %\edition{First Edition}
  90. \BookAuthor{Jeremy G. Siek}
  91. \imprint{The MIT Press\\
  92. Cambridge, Massachusetts\\
  93. London, England}
  94. \begin{copyrightpage}
  95. \textcopyright\ 2022 Massachusetts Institute of Technology Press \\[2ex]
  96. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  97. Subject to such license, all rights are reserved. \\[2ex]
  98. \includegraphics{CCBY-logo}
  99. The MIT Press would like to thank the anonymous peer reviewers who
  100. provided comments on drafts of this book. The generous work of
  101. academic experts is essential for establishing the authority and
  102. quality of our publications. We acknowledge with gratitude the
  103. contributions of these otherwise uncredited readers.
  104. This book was set in Times LT Std Roman by the author. Printed and
  105. bound in the United States of America.
  106. Library of Congress Cataloging-in-Publication Data is available.
  107. ISBN:
  108. 10 9 8 7 6 5 4 3 2 1
  109. %% Jeremy G. Siek. Available for free viewing
  110. %% or personal downloading under the
  111. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  112. %% license.
  113. %% Copyright in this monograph has been licensed exclusively to The MIT
  114. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  115. %% version to the public in 2022. All inquiries regarding rights should
  116. %% be addressed to The MIT Press, Rights and Permissions Department.
  117. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  118. %% All rights reserved. No part of this book may be reproduced in any
  119. %% form by any electronic or mechanical means (including photocopying,
  120. %% recording, or information storage and retrieval) without permission in
  121. %% writing from the publisher.
  122. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  123. %% United States of America.
  124. %% Library of Congress Cataloging-in-Publication Data is available.
  125. %% ISBN:
  126. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  127. \end{copyrightpage}
  128. \dedication{This book is dedicated to the programming language wonks
  129. at Indiana University.}
  130. %% \begin{epigraphpage}
  131. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  132. %% \textit{Book Name if any}}
  133. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  134. %% \end{epigraphpage}
  135. \tableofcontents
  136. %\listoffigures
  137. %\listoftables
  138. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  139. \chapter*{Preface}
  140. \addcontentsline{toc}{fmbm}{Preface}
  141. There is a magical moment when a programmer presses the ``run'' button
  142. and the software begins to execute. Somehow a program written in a
  143. high-level language is running on a computer that is only capable of
  144. shuffling bits. Here we reveal the wizardry that makes that moment
  145. possible. Beginning with the groundbreaking work of Backus and
  146. colleagues in the 1950s, computer scientists discovered techniques for
  147. constructing programs, called \emph{compilers}, that automatically
  148. translate high-level programs into machine code.
  149. We take you on a journey of constructing your own compiler for a small
  150. but powerful language. Along the way we explain the essential
  151. concepts, algorithms, and data structures that underlie compilers. We
  152. develop your understanding of how programs are mapped onto computer
  153. hardware, which is helpful when reasoning about properties at the
  154. junction between hardware and software such as execution time,
  155. software errors, and security vulnerabilities. For those interested
  156. in pursuing compiler construction as a career, our goal is to provide a
  157. stepping-stone to advanced topics such as just-in-time compilation,
  158. program analysis, and program optimization. For those interested in
  159. designing and implementing programming languages, we connect
  160. language design choices to their impact on the compiler and the generated
  161. code.
  162. A compiler is typically organized as a sequence of stages that
  163. progressively translate a program to the code that runs on
  164. hardware. We take this approach to the extreme by partitioning our
  165. compiler into a large number of \emph{nanopasses}, each of which
  166. performs a single task. This enables the testing of each pass in
  167. isolation and focuses our attention, making the compiler far easier to
  168. understand.
  169. The most familiar approach to describing compilers is with each
  170. chapter dedicated to one pass. The problem with that approach is it
  171. obfuscates how language features motivate design choices in a
  172. compiler. We instead take an \emph{incremental} approach in which we
  173. build a complete compiler in each chapter, starting with a small input
  174. language that includes only arithmetic and variables. We add new
  175. language features in subsequent chapters, extending the compiler as
  176. necessary.
  177. Our choice of language features is designed to elicit fundamental
  178. concepts and algorithms used in compilers.
  179. \begin{itemize}
  180. \item We begin with integer arithmetic and local variables in
  181. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  182. the fundamental tools of compiler construction: \emph{abstract
  183. syntax trees} and \emph{recursive functions}.
  184. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  185. \emph{graph coloring} to assign variables to machine registers.
  186. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  187. motivates an elegant recursive algorithm for translating them into
  188. conditional \code{goto}'s.
  189. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  190. variables}. This elicits the need for \emph{dataflow
  191. analysis} in the register allocator.
  192. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  193. \emph{garbage collection}.
  194. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  195. without lexical scoping, similar to functions in the C programming
  196. language~\citep{Kernighan:1988nx}. The reader learns about the
  197. procedure call stack and \emph{calling conventions} and how they interact
  198. with register allocation and garbage collection. The chapter also
  199. describes how to generate efficient tail calls.
  200. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  201. scoping, i.e., \emph{lambda} expressions. The reader learns about
  202. \emph{closure conversion}, in which lambdas are translated into a
  203. combination of functions and tuples.
  204. % Chapter about classes and objects?
  205. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  206. point the input languages are statically typed. The reader extends
  207. the statically typed language with an \code{Any} type which serves
  208. as a target for compiling the dynamically typed language.
  209. {\if\edition\pythonEd
  210. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  211. \emph{classes}.
  212. \fi}
  213. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  214. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  215. in which different regions of a program may be static or dynamically
  216. typed. The reader implements runtime support for \emph{proxies} that
  217. allow values to safely move between regions.
  218. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  219. leveraging the \code{Any} type and type casts developed in Chapters
  220. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  221. \end{itemize}
  222. There are many language features that we do not include. Our choices
  223. balance the incidental complexity of a feature versus the fundamental
  224. concepts that it exposes. For example, we include tuples and not
  225. records because they both elicit the study of heap allocation and
  226. garbage collection but records come with more incidental complexity.
  227. Since 2009 drafts of this book have served as the textbook for 16-week
  228. compiler courses for upper-level undergraduates and first-year
  229. graduate students at the University of Colorado and Indiana
  230. University.
  231. %
  232. Students come into the course having learned the basics of
  233. programming, data structures and algorithms, and discrete
  234. mathematics.
  235. %
  236. At the beginning of the course, students form groups of 2-4 people.
  237. The groups complete one chapter every two weeks, starting with
  238. Chapter~\ref{ch:Lvar} and finishing with
  239. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  240. that we assign to the graduate students. The last two weeks of the
  241. course involve a final project in which students design and implement
  242. a compiler extension of their choosing. The later chapters can be
  243. used in support of these projects. For compiler courses at
  244. universities on the quarter system (about 10 weeks in length), we
  245. recommend completing up through Chapter~\ref{ch:Lvec} or
  246. Chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  247. students for each compiler pass.
  248. %
  249. The course can be adapted to emphasize functional languages by
  250. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  251. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  252. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  253. %
  254. \python{A course that emphasizes object-oriented languages would
  255. include Chapter~\ref{ch:Lobject}.}
  256. %
  257. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  258. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  259. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  260. tail calls.
  261. This book has been used in compiler courses at California Polytechnic
  262. State University, Portland State University, Rose–Hulman Institute of
  263. Technology, University of Freiburg, University of Massachusetts
  264. Lowell, and the University of Vermont.
  265. \begin{figure}[tp]
  266. \begin{tcolorbox}[colback=white]
  267. {\if\edition\racketEd
  268. \begin{tikzpicture}[baseline=(current bounding box.center)]
  269. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  270. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  271. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  272. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  273. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  274. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  275. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  276. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  277. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  278. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  279. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  280. \path[->] (C1) edge [above] node {} (C2);
  281. \path[->] (C2) edge [above] node {} (C3);
  282. \path[->] (C3) edge [above] node {} (C4);
  283. \path[->] (C4) edge [above] node {} (C5);
  284. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  285. \path[->] (C5) edge [above] node {} (C7);
  286. \path[->] (C6) edge [above] node {} (C7);
  287. \path[->] (C4) edge [above] node {} (C8);
  288. \path[->] (C4) edge [above] node {} (C9);
  289. \path[->] (C7) edge [above] node {} (C10);
  290. \path[->] (C8) edge [above] node {} (C10);
  291. \path[->] (C10) edge [above] node {} (C11);
  292. \end{tikzpicture}
  293. \fi}
  294. {\if\edition\pythonEd
  295. \begin{tikzpicture}[baseline=(current bounding box.center)]
  296. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  297. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  298. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  299. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  300. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  301. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  302. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  303. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  304. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  305. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  306. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  307. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  308. \path[->] (C1) edge [above] node {} (C2);
  309. \path[->] (C2) edge [above] node {} (C3);
  310. \path[->] (C3) edge [above] node {} (C4);
  311. \path[->] (C4) edge [above] node {} (C5);
  312. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  313. \path[->] (C5) edge [above] node {} (C7);
  314. \path[->] (C6) edge [above] node {} (C7);
  315. \path[->] (C4) edge [above] node {} (C8);
  316. \path[->] (C4) edge [above] node {} (C9);
  317. \path[->] (C7) edge [above] node {} (C10);
  318. \path[->] (C8) edge [above] node {} (C10);
  319. \path[->] (C8) edge [above] node {} (CO);
  320. \path[->] (C10) edge [above] node {} (C11);
  321. \end{tikzpicture}
  322. \fi}
  323. \end{tcolorbox}
  324. \caption{Diagram of chapter dependencies.}
  325. \label{fig:chapter-dependences}
  326. \end{figure}
  327. \racket{
  328. We use the \href{https://racket-lang.org/}{Racket} language both for
  329. the implementation of the compiler and for the input language, so the
  330. reader should be proficient with Racket or Scheme. There are many
  331. excellent resources for learning Scheme and
  332. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  333. }
  334. \python{
  335. This edition of the book uses \href{https://www.python.org/}{Python}
  336. both for the implementation of the compiler and for the input language, so the
  337. reader should be proficient with Python. There are many
  338. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  339. }
  340. The support code for this book is in the github repository at
  341. the following location:
  342. \if\edition\racketEd
  343. \begin{center}\small
  344. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  345. \end{center}
  346. \fi
  347. \if\edition\pythonEd
  348. \begin{center}\small
  349. \url{https://github.com/IUCompilerCourse/}
  350. \end{center}
  351. \fi
  352. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  353. is helpful but not necessary for the reader to have taken a computer
  354. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  355. assembly language that are needed in the compiler.
  356. %
  357. We follow the System V calling
  358. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  359. that we generate works with the runtime system (written in C) when it
  360. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  361. operating systems on Intel hardware.
  362. %
  363. On the Windows operating system, \code{gcc} uses the Microsoft x64
  364. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  365. assembly code that we generate does \emph{not} work with the runtime
  366. system on Windows. One workaround is to use a virtual machine with
  367. Linux as the guest operating system.
  368. \section*{Acknowledgments}
  369. The tradition of compiler construction at Indiana University goes back
  370. to research and courses on programming languages by Daniel Friedman in
  371. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  372. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  373. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  374. the compiler course and continued the development of Chez Scheme.
  375. %
  376. The compiler course evolved to incorporate novel pedagogical ideas
  377. while also including elements of real-world compilers. One of
  378. Friedman's ideas was to split the compiler into many small
  379. passes. Another idea, called ``the game'', was to test the code
  380. generated by each pass using interpreters.
  381. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  382. developed infrastructure to support this approach and evolved the
  383. course to use even smaller
  384. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  385. design decisions in this book are inspired by the assignment
  386. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  387. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  388. organization of the course made it difficult for students to
  389. understand the rationale for the compiler design. Ghuloum proposed the
  390. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  391. on.
  392. We thank the many students who served as teaching assistants for the
  393. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  394. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  395. garbage collector and x86 interpreter, Michael Vollmer for work on
  396. efficient tail calls, and Michael Vitousek for help with the first
  397. offering of the incremental compiler course at IU.
  398. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  399. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  400. Michael Wollowski for teaching courses based on drafts of this book
  401. and for their feedback. We thank the National Science Foundation for
  402. the grants that helped to support this work: Grant Numbers 1518844,
  403. 1763922, and 1814460.
  404. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  405. course in the early 2000's and especially for finding the bug that
  406. sent our garbage collector on a wild goose chase!
  407. \mbox{}\\
  408. \noindent Jeremy G. Siek \\
  409. Bloomington, Indiana
  410. \mainmatter
  411. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  412. \chapter{Preliminaries}
  413. \label{ch:trees-recur}
  414. In this chapter we review the basic tools that are needed to implement
  415. a compiler. Programs are typically input by a programmer as text,
  416. i.e., a sequence of characters. The program-as-text representation is
  417. called \emph{concrete syntax}. We use concrete syntax to concisely
  418. write down and talk about programs. Inside the compiler, we use
  419. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  420. that efficiently supports the operations that the compiler needs to
  421. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  422. The translation from concrete syntax to abstract syntax is a process called
  423. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  424. implementation of parsing in this book.
  425. %
  426. \racket{A parser is provided in the support code for translating from
  427. concrete to abstract syntax.}
  428. %
  429. \python{We use Python's \code{ast} module to translate from concrete
  430. to abstract syntax.}
  431. ASTs can be represented in many different ways inside the compiler,
  432. depending on the programming language used to write the compiler.
  433. %
  434. \racket{We use Racket's
  435. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  436. feature to represent ASTs (Section~\ref{sec:ast}).}
  437. %
  438. \python{We use Python classes and objects to represent ASTs, especially the
  439. classes defined in the standard \code{ast} module for the Python
  440. source language.}
  441. %
  442. We use grammars to define the abstract syntax of programming languages
  443. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  444. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  445. recursive functions to construct and deconstruct ASTs
  446. (Section~\ref{sec:recursion}). This chapter provides an brief
  447. introduction to these ideas.
  448. \racket{\index{subject}{struct}}
  449. \python{\index{subject}{class}\index{subject}{object}}
  450. \section{Abstract Syntax Trees}
  451. \label{sec:ast}
  452. Compilers use abstract syntax trees to represent programs because they
  453. often need to ask questions like: for a given part of a program, what
  454. kind of language feature is it? What are its sub-parts? Consider the
  455. program on the left and its AST on the right. This program is an
  456. addition operation and it has two sub-parts, a
  457. \racket{read}\python{input} operation and a negation. The negation has
  458. another sub-part, the integer constant \code{8}. By using a tree to
  459. represent the program, we can easily follow the links to go from one
  460. part of a program to its sub-parts.
  461. \begin{center}
  462. \begin{minipage}{0.4\textwidth}
  463. \if\edition\racketEd
  464. \begin{lstlisting}
  465. (+ (read) (- 8))
  466. \end{lstlisting}
  467. \fi
  468. \if\edition\pythonEd
  469. \begin{lstlisting}
  470. input_int() + -8
  471. \end{lstlisting}
  472. \fi
  473. \end{minipage}
  474. \begin{minipage}{0.4\textwidth}
  475. \begin{equation}
  476. \begin{tikzpicture}
  477. \node[draw] (plus) at (0 , 0) {\key{+}};
  478. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  479. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  480. \node[draw] (8) at (1 , -3) {\key{8}};
  481. \draw[->] (plus) to (read);
  482. \draw[->] (plus) to (minus);
  483. \draw[->] (minus) to (8);
  484. \end{tikzpicture}
  485. \label{eq:arith-prog}
  486. \end{equation}
  487. \end{minipage}
  488. \end{center}
  489. We use the standard terminology for trees to describe ASTs: each
  490. rectangle above is called a \emph{node}. The arrows connect a node to its
  491. \emph{children} (which are also nodes). The top-most node is the
  492. \emph{root}. Every node except for the root has a \emph{parent} (the
  493. node it is the child of). If a node has no children, it is a
  494. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  495. \index{subject}{node}
  496. \index{subject}{children}
  497. \index{subject}{root}
  498. \index{subject}{parent}
  499. \index{subject}{leaf}
  500. \index{subject}{internal node}
  501. %% Recall that an \emph{symbolic expression} (S-expression) is either
  502. %% \begin{enumerate}
  503. %% \item an atom, or
  504. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  505. %% where $e_1$ and $e_2$ are each an S-expression.
  506. %% \end{enumerate}
  507. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  508. %% null value \code{'()}, etc. We can create an S-expression in Racket
  509. %% simply by writing a backquote (called a quasi-quote in Racket)
  510. %% followed by the textual representation of the S-expression. It is
  511. %% quite common to use S-expressions to represent a list, such as $a, b
  512. %% ,c$ in the following way:
  513. %% \begin{lstlisting}
  514. %% `(a . (b . (c . ())))
  515. %% \end{lstlisting}
  516. %% Each element of the list is in the first slot of a pair, and the
  517. %% second slot is either the rest of the list or the null value, to mark
  518. %% the end of the list. Such lists are so common that Racket provides
  519. %% special notation for them that removes the need for the periods
  520. %% and so many parenthesis:
  521. %% \begin{lstlisting}
  522. %% `(a b c)
  523. %% \end{lstlisting}
  524. %% The following expression creates an S-expression that represents AST
  525. %% \eqref{eq:arith-prog}.
  526. %% \begin{lstlisting}
  527. %% `(+ (read) (- 8))
  528. %% \end{lstlisting}
  529. %% When using S-expressions to represent ASTs, the convention is to
  530. %% represent each AST node as a list and to put the operation symbol at
  531. %% the front of the list. The rest of the list contains the children. So
  532. %% in the above case, the root AST node has operation \code{`+} and its
  533. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  534. %% diagram \eqref{eq:arith-prog}.
  535. %% To build larger S-expressions one often needs to splice together
  536. %% several smaller S-expressions. Racket provides the comma operator to
  537. %% splice an S-expression into a larger one. For example, instead of
  538. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  539. %% we could have first created an S-expression for AST
  540. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  541. %% S-expression.
  542. %% \begin{lstlisting}
  543. %% (define ast1.4 `(- 8))
  544. %% (define ast1_1 `(+ (read) ,ast1.4))
  545. %% \end{lstlisting}
  546. %% In general, the Racket expression that follows the comma (splice)
  547. %% can be any expression that produces an S-expression.
  548. {\if\edition\racketEd
  549. We define a Racket \code{struct} for each kind of node. For this
  550. chapter we require just two kinds of nodes: one for integer constants
  551. and one for primitive operations. The following is the \code{struct}
  552. definition for integer constants.\footnote{All of the AST structures are
  553. defined in the file \code{utilities.rkt} in the support code.}
  554. \begin{lstlisting}
  555. (struct Int (value))
  556. \end{lstlisting}
  557. An integer node includes just one thing: the integer value.
  558. To create an AST node for the integer $8$, we write \INT{8}.
  559. \begin{lstlisting}
  560. (define eight (Int 8))
  561. \end{lstlisting}
  562. We say that the value created by \INT{8} is an
  563. \emph{instance} of the
  564. \code{Int} structure.
  565. The following is the \code{struct} definition for primitive operations.
  566. \begin{lstlisting}
  567. (struct Prim (op args))
  568. \end{lstlisting}
  569. A primitive operation node includes an operator symbol \code{op} and a
  570. list of child \code{args}. For example, to create an AST that negates
  571. the number $8$, we write the following.
  572. \begin{lstlisting}
  573. (define neg-eight (Prim '- (list eight)))
  574. \end{lstlisting}
  575. Primitive operations may have zero or more children. The \code{read}
  576. operator has zero:
  577. \begin{lstlisting}
  578. (define rd (Prim 'read '()))
  579. \end{lstlisting}
  580. The addition operator has two children:
  581. \begin{lstlisting}
  582. (define ast1_1 (Prim '+ (list rd neg-eight)))
  583. \end{lstlisting}
  584. We have made a design choice regarding the \code{Prim} structure.
  585. Instead of using one structure for many different operations
  586. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  587. structure for each operation, as follows.
  588. \begin{lstlisting}
  589. (struct Read ())
  590. (struct Add (left right))
  591. (struct Neg (value))
  592. \end{lstlisting}
  593. The reason we choose to use just one structure is that in many parts
  594. of the compiler the code for the different primitive operators is the
  595. same, so we might as well just write that code once, which is enabled
  596. by using a single structure.
  597. \fi}
  598. {\if\edition\pythonEd
  599. We use a Python \code{class} for each kind of node.
  600. The following is the class definition for
  601. constants.
  602. \begin{lstlisting}
  603. class Constant:
  604. def __init__(self, value):
  605. self.value = value
  606. \end{lstlisting}
  607. An integer constant node includes just one thing: the integer value.
  608. To create an AST node for the integer $8$, we write \INT{8}.
  609. \begin{lstlisting}
  610. eight = Constant(8)
  611. \end{lstlisting}
  612. We say that the value created by \INT{8} is an
  613. \emph{instance} of the \code{Constant} class.
  614. The following is the class definition for unary operators.
  615. \begin{lstlisting}
  616. class UnaryOp:
  617. def __init__(self, op, operand):
  618. self.op = op
  619. self.operand = operand
  620. \end{lstlisting}
  621. The specific operation is specified by the \code{op} parameter. For
  622. example, the class \code{USub} is for unary subtraction.
  623. (More unary operators are introduced in later chapters.) To create an AST that
  624. negates the number $8$, we write the following.
  625. \begin{lstlisting}
  626. neg_eight = UnaryOp(USub(), eight)
  627. \end{lstlisting}
  628. The call to the \code{input\_int} function is represented by the
  629. \code{Call} and \code{Name} classes.
  630. \begin{lstlisting}
  631. class Call:
  632. def __init__(self, func, args):
  633. self.func = func
  634. self.args = args
  635. class Name:
  636. def __init__(self, id):
  637. self.id = id
  638. \end{lstlisting}
  639. To create an AST node that calls \code{input\_int}, we write
  640. \begin{lstlisting}
  641. read = Call(Name('input_int'), [])
  642. \end{lstlisting}
  643. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  644. the \code{BinOp} class for binary operators.
  645. \begin{lstlisting}
  646. class BinOp:
  647. def __init__(self, left, op, right):
  648. self.op = op
  649. self.left = left
  650. self.right = right
  651. \end{lstlisting}
  652. Similar to \code{UnaryOp}, the specific operation is specified by the
  653. \code{op} parameter, which for now is just an instance of the
  654. \code{Add} class. So to create the AST
  655. node that adds negative eight to some user input, we write the following.
  656. \begin{lstlisting}
  657. ast1_1 = BinOp(read, Add(), neg_eight)
  658. \end{lstlisting}
  659. \fi}
  660. When compiling a program such as \eqref{eq:arith-prog}, we need to
  661. know that the operation associated with the root node is addition and
  662. we need to be able to access its two children. \racket{Racket}\python{Python}
  663. provides pattern matching to support these kinds of queries, as we see in
  664. Section~\ref{sec:pattern-matching}.
  665. We often write down the concrete syntax of a program even when we
  666. really have in mind the AST because the concrete syntax is more
  667. concise. We recommend that, in your mind, you always think of
  668. programs as abstract syntax trees.
  669. \section{Grammars}
  670. \label{sec:grammar}
  671. \index{subject}{integer}
  672. \index{subject}{literal}
  673. %\index{subject}{constant}
  674. A programming language can be thought of as a \emph{set} of programs.
  675. The set is typically infinite (one can always create larger and larger
  676. programs) so one cannot simply describe a language by listing all of
  677. the programs in the language. Instead we write down a set of rules, a
  678. \emph{grammar}, for building programs. Grammars are often used to
  679. define the concrete syntax of a language but they can also be used to
  680. describe the abstract syntax. We write our rules in a variant of
  681. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  682. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  683. As an example, we describe a small language, named \LangInt{}, that consists of
  684. integers and arithmetic operations.
  685. \index{subject}{grammar}
  686. The first grammar rule for the abstract syntax of \LangInt{} says that an
  687. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  688. \begin{equation}
  689. \Exp ::= \INT{\Int} \label{eq:arith-int}
  690. \end{equation}
  691. %
  692. Each rule has a left-hand-side and a right-hand-side.
  693. If you have an AST node that matches the
  694. right-hand-side, then you can categorize it according to the
  695. left-hand-side.
  696. %
  697. Symbols in typewriter font are \emph{terminal} symbols and must
  698. literally appear in the program for the rule to be applicable.
  699. \index{subject}{terminal}
  700. %
  701. Our grammars do not mention \emph{white-space}, that is, separating characters
  702. like spaces, tabulators, and newlines. White-space may be inserted
  703. between symbols for disambiguation and to improve readability.
  704. \index{subject}{white-space}
  705. %
  706. A name such as $\Exp$ that is defined by the grammar rules is a
  707. \emph{non-terminal}. \index{subject}{non-terminal}
  708. %
  709. The name $\Int$ is also a non-terminal, but instead of defining it
  710. with a grammar rule, we define it with the following explanation. An
  711. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  712. $-$ (for negative integers), such that the sequence of decimals
  713. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  714. the representation of integers using 63 bits, which simplifies several
  715. aspects of compilation. \racket{Thus, these integers correspond to
  716. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  717. \python{In contrast, integers in Python have unlimited precision, but
  718. the techniques needed to handle unlimited precision fall outside the
  719. scope of this book.}
  720. The second grammar rule is the \READOP{} operation that receives an
  721. input integer from the user of the program.
  722. \begin{equation}
  723. \Exp ::= \READ{} \label{eq:arith-read}
  724. \end{equation}
  725. The third rule categorizes the negation of an $\Exp$ node as an
  726. $\Exp$.
  727. \begin{equation}
  728. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  729. \end{equation}
  730. We can apply these rules to categorize the ASTs that are in the
  731. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  732. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  733. following AST is an $\Exp$.
  734. \begin{center}
  735. \begin{minipage}{0.5\textwidth}
  736. \NEG{\INT{\code{8}}}
  737. \end{minipage}
  738. \begin{minipage}{0.25\textwidth}
  739. \begin{equation}
  740. \begin{tikzpicture}
  741. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  742. \node[draw, circle] (8) at (0, -1.2) {$8$};
  743. \draw[->] (minus) to (8);
  744. \end{tikzpicture}
  745. \label{eq:arith-neg8}
  746. \end{equation}
  747. \end{minipage}
  748. \end{center}
  749. The next grammar rules are for addition and subtraction expressions:
  750. \begin{align}
  751. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  752. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  753. \end{align}
  754. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  755. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  756. \eqref{eq:arith-read} and we have already categorized
  757. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  758. to show that
  759. \[
  760. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  761. \]
  762. is an $\Exp$ in the \LangInt{} language.
  763. If you have an AST for which the above rules do not apply, then the
  764. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  765. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  766. because there is no rule for the \key{*} operator. Whenever we
  767. define a language with a grammar, the language only includes those
  768. programs that are justified by the grammar rules.
  769. {\if\edition\pythonEd
  770. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  771. There is a statement for printing the value of an expression
  772. \[
  773. \Stmt{} ::= \PRINT{\Exp}
  774. \]
  775. and a statement that evaluates an expression but ignores the result.
  776. \[
  777. \Stmt{} ::= \EXPR{\Exp}
  778. \]
  779. \fi}
  780. {\if\edition\racketEd
  781. The last grammar rule for \LangInt{} states that there is a
  782. \code{Program} node to mark the top of the whole program:
  783. \[
  784. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  785. \]
  786. The \code{Program} structure is defined as follows
  787. \begin{lstlisting}
  788. (struct Program (info body))
  789. \end{lstlisting}
  790. where \code{body} is an expression. In later chapters, the \code{info}
  791. part will be used to store auxiliary information but for now it is
  792. just the empty list.
  793. \fi}
  794. {\if\edition\pythonEd
  795. The last grammar rule for \LangInt{} states that there is a
  796. \code{Module} node to mark the top of the whole program:
  797. \[
  798. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  799. \]
  800. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  801. this case, a list of statements.
  802. %
  803. The \code{Module} class is defined as follows
  804. \begin{lstlisting}
  805. class Module:
  806. def __init__(self, body):
  807. self.body = body
  808. \end{lstlisting}
  809. where \code{body} is a list of statements.
  810. \fi}
  811. It is common to have many grammar rules with the same left-hand side
  812. but different right-hand sides, such as the rules for $\Exp$ in the
  813. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  814. combine several right-hand-sides into a single rule.
  815. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  816. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  817. defined in Figure~\ref{fig:r0-concrete-syntax}.
  818. \racket{The \code{read-program} function provided in
  819. \code{utilities.rkt} of the support code reads a program in from a
  820. file (the sequence of characters in the concrete syntax of Racket)
  821. and parses it into an abstract syntax tree. See the description of
  822. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  823. details.}
  824. \python{The \code{parse} function in Python's \code{ast} module
  825. converts the concrete syntax (represented as a string) into an
  826. abstract syntax tree.}
  827. \newcommand{\LintGrammarRacket}{
  828. \begin{array}{rcl}
  829. \Type &::=& \key{Integer} \\
  830. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  831. \MID \CSUB{\Exp}{\Exp}
  832. \end{array}
  833. }
  834. \newcommand{\LintASTRacket}{
  835. \begin{array}{rcl}
  836. \Type &::=& \key{Integer} \\
  837. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  838. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  839. \end{array}
  840. }
  841. \newcommand{\LintGrammarPython}{
  842. \begin{array}{rcl}
  843. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  844. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  845. \end{array}
  846. }
  847. \newcommand{\LintASTPython}{
  848. \begin{array}{rcl}
  849. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  850. \itm{unaryop} &::= & \code{USub()} \\
  851. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  852. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  853. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  854. \end{array}
  855. }
  856. \begin{figure}[tp]
  857. \begin{tcolorbox}[colback=white]
  858. {\if\edition\racketEd
  859. \[
  860. \begin{array}{l}
  861. \LintGrammarRacket \\
  862. \begin{array}{rcl}
  863. \LangInt{} &::=& \Exp
  864. \end{array}
  865. \end{array}
  866. \]
  867. \fi}
  868. {\if\edition\pythonEd
  869. \[
  870. \begin{array}{l}
  871. \LintGrammarPython \\
  872. \begin{array}{rcl}
  873. \LangInt{} &::=& \Stmt^{*}
  874. \end{array}
  875. \end{array}
  876. \]
  877. \fi}
  878. \end{tcolorbox}
  879. \caption{The concrete syntax of \LangInt{}.}
  880. \label{fig:r0-concrete-syntax}
  881. \end{figure}
  882. \begin{figure}[tp]
  883. \begin{tcolorbox}[colback=white]
  884. {\if\edition\racketEd
  885. \[
  886. \begin{array}{l}
  887. \LintASTRacket{} \\
  888. \begin{array}{rcl}
  889. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  890. \end{array}
  891. \end{array}
  892. \]
  893. \fi}
  894. {\if\edition\pythonEd
  895. \[
  896. \begin{array}{l}
  897. \LintASTPython\\
  898. \begin{array}{rcl}
  899. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  900. \end{array}
  901. \end{array}
  902. \]
  903. \fi}
  904. \end{tcolorbox}
  905. \python{
  906. \index{subject}{Constant@\texttt{Constant}}
  907. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  908. \index{subject}{USub@\texttt{USub}}
  909. \index{subject}{inputint@\texttt{input\_int}}
  910. \index{subject}{Call@\texttt{Call}}
  911. \index{subject}{Name@\texttt{Name}}
  912. \index{subject}{BinOp@\texttt{BinOp}}
  913. \index{subject}{Add@\texttt{Add}}
  914. \index{subject}{Sub@\texttt{Sub}}
  915. \index{subject}{print@\texttt{print}}
  916. \index{subject}{Expr@\texttt{Expr}}
  917. \index{subject}{Module@\texttt{Module}}
  918. }
  919. \caption{The abstract syntax of \LangInt{}.}
  920. \label{fig:r0-syntax}
  921. \end{figure}
  922. \section{Pattern Matching}
  923. \label{sec:pattern-matching}
  924. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  925. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  926. \texttt{match} feature to access the parts of a value.
  927. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  928. \begin{center}
  929. \begin{minipage}{0.5\textwidth}
  930. {\if\edition\racketEd
  931. \begin{lstlisting}
  932. (match ast1_1
  933. [(Prim op (list child1 child2))
  934. (print op)])
  935. \end{lstlisting}
  936. \fi}
  937. {\if\edition\pythonEd
  938. \begin{lstlisting}
  939. match ast1_1:
  940. case BinOp(child1, op, child2):
  941. print(op)
  942. \end{lstlisting}
  943. \fi}
  944. \end{minipage}
  945. \end{center}
  946. {\if\edition\racketEd
  947. %
  948. In the above example, the \texttt{match} form checks whether the AST
  949. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  950. three pattern variables \texttt{op}, \texttt{child1}, and
  951. \texttt{child2}. In general, a match clause consists of a
  952. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  953. recursively defined to be either a pattern variable, a structure name
  954. followed by a pattern for each of the structure's arguments, or an
  955. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  956. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  957. and Chapter 9 of The Racket
  958. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  959. for complete descriptions of \code{match}.)
  960. %
  961. The body of a match clause may contain arbitrary Racket code. The
  962. pattern variables can be used in the scope of the body, such as
  963. \code{op} in \code{(print op)}.
  964. %
  965. \fi}
  966. %
  967. %
  968. {\if\edition\pythonEd
  969. %
  970. In the above example, the \texttt{match} form checks whether the AST
  971. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  972. three pattern variables \texttt{child1}, \texttt{op}, and
  973. \texttt{child2}, and then prints out the operator. In general, each
  974. \code{case} consists of a \emph{pattern} and a
  975. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  976. to be either a pattern variable, a class name followed by a pattern
  977. for each of its constructor's arguments, or other literals such as
  978. strings, lists, etc.
  979. %
  980. The body of each \code{case} may contain arbitrary Python code. The
  981. pattern variables can be used in the body, such as \code{op} in
  982. \code{print(op)}.
  983. %
  984. \fi}
  985. A \code{match} form may contain several clauses, as in the following
  986. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  987. the AST. The \code{match} proceeds through the clauses in order,
  988. checking whether the pattern can match the input AST. The body of the
  989. first clause that matches is executed. The output of \code{leaf} for
  990. several ASTs is shown on the right.
  991. \begin{center}
  992. \begin{minipage}{0.6\textwidth}
  993. {\if\edition\racketEd
  994. \begin{lstlisting}
  995. (define (leaf arith)
  996. (match arith
  997. [(Int n) #t]
  998. [(Prim 'read '()) #t]
  999. [(Prim '- (list e1)) #f]
  1000. [(Prim '+ (list e1 e2)) #f]
  1001. [(Prim '- (list e1 e2)) #f]))
  1002. (leaf (Prim 'read '()))
  1003. (leaf (Prim '- (list (Int 8))))
  1004. (leaf (Int 8))
  1005. \end{lstlisting}
  1006. \fi}
  1007. {\if\edition\pythonEd
  1008. \begin{lstlisting}
  1009. def leaf(arith):
  1010. match arith:
  1011. case Constant(n):
  1012. return True
  1013. case Call(Name('input_int'), []):
  1014. return True
  1015. case UnaryOp(USub(), e1):
  1016. return False
  1017. case BinOp(e1, Add(), e2):
  1018. return False
  1019. case BinOp(e1, Sub(), e2):
  1020. return False
  1021. print(leaf(Call(Name('input_int'), [])))
  1022. print(leaf(UnaryOp(USub(), eight)))
  1023. print(leaf(Constant(8)))
  1024. \end{lstlisting}
  1025. \fi}
  1026. \end{minipage}
  1027. \vrule
  1028. \begin{minipage}{0.25\textwidth}
  1029. {\if\edition\racketEd
  1030. \begin{lstlisting}
  1031. #t
  1032. #f
  1033. #t
  1034. \end{lstlisting}
  1035. \fi}
  1036. {\if\edition\pythonEd
  1037. \begin{lstlisting}
  1038. True
  1039. False
  1040. True
  1041. \end{lstlisting}
  1042. \fi}
  1043. \end{minipage}
  1044. \end{center}
  1045. When constructing a \code{match} expression, we refer to the grammar
  1046. definition to identify which non-terminal we are expecting to match
  1047. against, then we make sure that 1) we have one
  1048. \racket{clause}\python{case} for each alternative of that non-terminal
  1049. and 2) that the pattern in each \racket{clause}\python{case}
  1050. corresponds to the corresponding right-hand side of a grammar
  1051. rule. For the \code{match} in the \code{leaf} function, we refer to
  1052. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1053. non-terminal has 4 alternatives, so the \code{match} has 4
  1054. \racket{clauses}\python{cases}. The pattern in each
  1055. \racket{clause}\python{case} corresponds to the right-hand side of a
  1056. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1057. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1058. translating from grammars to patterns, replace non-terminals such as
  1059. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1060. \code{e2}).
  1061. \section{Recursive Functions}
  1062. \label{sec:recursion}
  1063. \index{subject}{recursive function}
  1064. Programs are inherently recursive. For example, an expression is often
  1065. made of smaller expressions. Thus, the natural way to process an
  1066. entire program is with a recursive function. As a first example of
  1067. such a recursive function, we define the function \code{is\_exp} in
  1068. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1069. determines whether or not it is an expression in \LangInt{}.
  1070. %
  1071. We say that a function is defined by \emph{structural recursion} when
  1072. it is defined using a sequence of match \racket{clauses}\python{cases}
  1073. that correspond to a grammar, and the body of each
  1074. \racket{clause}\python{case} makes a recursive call on each child
  1075. node.\footnote{This principle of structuring code according to the
  1076. data definition is advocated in the book \emph{How to Design
  1077. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1078. second function, named \code{stmt}, that recognizes whether a value
  1079. is a \LangInt{} statement.} \python{Finally, }
  1080. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1081. which determines whether an AST is a program in \LangInt{}. In
  1082. general we can write one recursive function to handle each
  1083. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1084. two examples at the bottom of the figure, the first is in
  1085. \LangInt{} and the second is not.
  1086. \begin{figure}[tp]
  1087. \begin{tcolorbox}[colback=white]
  1088. {\if\edition\racketEd
  1089. \begin{lstlisting}
  1090. (define (is_exp ast)
  1091. (match ast
  1092. [(Int n) #t]
  1093. [(Prim 'read '()) #t]
  1094. [(Prim '- (list e)) (is_exp e)]
  1095. [(Prim '+ (list e1 e2))
  1096. (and (is_exp e1) (is_exp e2))]
  1097. [(Prim '- (list e1 e2))
  1098. (and (is_exp e1) (is_exp e2))]
  1099. [else #f]))
  1100. (define (is_Lint ast)
  1101. (match ast
  1102. [(Program '() e) (is_exp e)]
  1103. [else #f]))
  1104. (is_Lint (Program '() ast1_1)
  1105. (is_Lint (Program '()
  1106. (Prim '* (list (Prim 'read '())
  1107. (Prim '+ (list (Int 8)))))))
  1108. \end{lstlisting}
  1109. \fi}
  1110. {\if\edition\pythonEd
  1111. \begin{lstlisting}
  1112. def is_exp(e):
  1113. match e:
  1114. case Constant(n):
  1115. return True
  1116. case Call(Name('input_int'), []):
  1117. return True
  1118. case UnaryOp(USub(), e1):
  1119. return is_exp(e1)
  1120. case BinOp(e1, Add(), e2):
  1121. return is_exp(e1) and is_exp(e2)
  1122. case BinOp(e1, Sub(), e2):
  1123. return is_exp(e1) and is_exp(e2)
  1124. case _:
  1125. return False
  1126. def stmt(s):
  1127. match s:
  1128. case Expr(Call(Name('print'), [e])):
  1129. return is_exp(e)
  1130. case Expr(e):
  1131. return is_exp(e)
  1132. case _:
  1133. return False
  1134. def is_Lint(p):
  1135. match p:
  1136. case Module(body):
  1137. return all([stmt(s) for s in body])
  1138. case _:
  1139. return False
  1140. print(is_Lint(Module([Expr(ast1_1)])))
  1141. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1142. UnaryOp(Add(), Constant(8))))])))
  1143. \end{lstlisting}
  1144. \fi}
  1145. \end{tcolorbox}
  1146. \caption{Example of recursive functions for \LangInt{}. These functions
  1147. recognize whether an AST is in \LangInt{}.}
  1148. \label{fig:exp-predicate}
  1149. \end{figure}
  1150. %% You may be tempted to merge the two functions into one, like this:
  1151. %% \begin{center}
  1152. %% \begin{minipage}{0.5\textwidth}
  1153. %% \begin{lstlisting}
  1154. %% (define (Lint ast)
  1155. %% (match ast
  1156. %% [(Int n) #t]
  1157. %% [(Prim 'read '()) #t]
  1158. %% [(Prim '- (list e)) (Lint e)]
  1159. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1160. %% [(Program '() e) (Lint e)]
  1161. %% [else #f]))
  1162. %% \end{lstlisting}
  1163. %% \end{minipage}
  1164. %% \end{center}
  1165. %% %
  1166. %% Sometimes such a trick will save a few lines of code, especially when
  1167. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1168. %% \emph{not} recommended because it can get you into trouble.
  1169. %% %
  1170. %% For example, the above function is subtly wrong:
  1171. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1172. %% returns true when it should return false.
  1173. \section{Interpreters}
  1174. \label{sec:interp_Lint}
  1175. \index{subject}{interpreter}
  1176. The behavior of a program is defined by the specification of the
  1177. programming language.
  1178. %
  1179. \racket{For example, the Scheme language is defined in the report by
  1180. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1181. reference manual~\citep{plt-tr}.}
  1182. %
  1183. \python{For example, the Python language is defined in the Python
  1184. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1185. %
  1186. In this book we use interpreters to specify each language that we
  1187. consider. An interpreter that is designated as the definition of a
  1188. language is called a \emph{definitional
  1189. interpreter}~\citep{reynolds72:_def_interp}.
  1190. \index{subject}{definitional interpreter} We warm up by creating a
  1191. definitional interpreter for the \LangInt{} language. This interpreter
  1192. serves as a second example of structural recursion. The
  1193. \code{interp\_Lint} function is defined in
  1194. Figure~\ref{fig:interp_Lint}.
  1195. %
  1196. \racket{The body of the function is a match on the input program
  1197. followed by a call to the \lstinline{interp_exp} helper function,
  1198. which in turn has one match clause per grammar rule for \LangInt{}
  1199. expressions.}
  1200. %
  1201. \python{The body of the function matches on the \code{Module} AST node
  1202. and then invokes \code{interp\_stmt} on each statement in the
  1203. module. The \code{interp\_stmt} function includes a case for each
  1204. grammar rule of the \Stmt{} non-terminal and it calls
  1205. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1206. function includes a case for each grammar rule of the \Exp{}
  1207. non-terminal.}
  1208. \begin{figure}[tp]
  1209. \begin{tcolorbox}[colback=white]
  1210. {\if\edition\racketEd
  1211. \begin{lstlisting}
  1212. (define (interp_exp e)
  1213. (match e
  1214. [(Int n) n]
  1215. [(Prim 'read '())
  1216. (define r (read))
  1217. (cond [(fixnum? r) r]
  1218. [else (error 'interp_exp "read expected an integer" r)])]
  1219. [(Prim '- (list e))
  1220. (define v (interp_exp e))
  1221. (fx- 0 v)]
  1222. [(Prim '+ (list e1 e2))
  1223. (define v1 (interp_exp e1))
  1224. (define v2 (interp_exp e2))
  1225. (fx+ v1 v2)]
  1226. [(Prim '- (list e1 e2))
  1227. (define v1 ((interp-exp env) e1))
  1228. (define v2 ((interp-exp env) e2))
  1229. (fx- v1 v2)]))
  1230. (define (interp_Lint p)
  1231. (match p
  1232. [(Program '() e) (interp_exp e)]))
  1233. \end{lstlisting}
  1234. \fi}
  1235. {\if\edition\pythonEd
  1236. \begin{lstlisting}
  1237. def interp_exp(e):
  1238. match e:
  1239. case BinOp(left, Add(), right):
  1240. l = interp_exp(left); r = interp_exp(right)
  1241. return l + r
  1242. case BinOp(left, Sub(), right):
  1243. l = interp_exp(left); r = interp_exp(right)
  1244. return l - r
  1245. case UnaryOp(USub(), v):
  1246. return - interp_exp(v)
  1247. case Constant(value):
  1248. return value
  1249. case Call(Name('input_int'), []):
  1250. return int(input())
  1251. def interp_stmt(s):
  1252. match s:
  1253. case Expr(Call(Name('print'), [arg])):
  1254. print(interp_exp(arg))
  1255. case Expr(value):
  1256. interp_exp(value)
  1257. def interp_Lint(p):
  1258. match p:
  1259. case Module(body):
  1260. for s in body:
  1261. interp_stmt(s)
  1262. \end{lstlisting}
  1263. \fi}
  1264. \end{tcolorbox}
  1265. \caption{Interpreter for the \LangInt{} language.}
  1266. \label{fig:interp_Lint}
  1267. \end{figure}
  1268. Let us consider the result of interpreting a few \LangInt{} programs. The
  1269. following program adds two integers.
  1270. {\if\edition\racketEd
  1271. \begin{lstlisting}
  1272. (+ 10 32)
  1273. \end{lstlisting}
  1274. \fi}
  1275. {\if\edition\pythonEd
  1276. \begin{lstlisting}
  1277. print(10 + 32)
  1278. \end{lstlisting}
  1279. \fi}
  1280. %
  1281. \noindent The result is \key{42}, the answer to life, the universe,
  1282. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1283. the Galaxy} by Douglas Adams.}
  1284. %
  1285. We wrote the above program in concrete syntax whereas the parsed
  1286. abstract syntax is:
  1287. {\if\edition\racketEd
  1288. \begin{lstlisting}
  1289. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1290. \end{lstlisting}
  1291. \fi}
  1292. {\if\edition\pythonEd
  1293. \begin{lstlisting}
  1294. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1295. \end{lstlisting}
  1296. \fi}
  1297. The next example demonstrates that expressions may be nested within
  1298. each other, in this case nesting several additions and negations.
  1299. {\if\edition\racketEd
  1300. \begin{lstlisting}
  1301. (+ 10 (- (+ 12 20)))
  1302. \end{lstlisting}
  1303. \fi}
  1304. {\if\edition\pythonEd
  1305. \begin{lstlisting}
  1306. print(10 + -(12 + 20))
  1307. \end{lstlisting}
  1308. \fi}
  1309. %
  1310. \noindent What is the result of the above program?
  1311. {\if\edition\racketEd
  1312. As mentioned previously, the \LangInt{} language does not support
  1313. arbitrarily-large integers, but only $63$-bit integers, so we
  1314. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1315. in Racket.
  1316. Suppose
  1317. \[
  1318. n = 999999999999999999
  1319. \]
  1320. which indeed fits in $63$-bits. What happens when we run the
  1321. following program in our interpreter?
  1322. \begin{lstlisting}
  1323. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1324. \end{lstlisting}
  1325. It produces an error:
  1326. \begin{lstlisting}
  1327. fx+: result is not a fixnum
  1328. \end{lstlisting}
  1329. We establish the convention that if running the definitional
  1330. interpreter on a program produces an error then the meaning of that
  1331. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1332. error is a \code{trapped-error}. A compiler for the language is under
  1333. no obligations regarding programs with unspecified behavior; it does
  1334. not have to produce an executable, and if it does, that executable can
  1335. do anything. On the other hand, if the error is a
  1336. \code{trapped-error}, then the compiler must produce an executable and
  1337. it is required to report that an error occurred. To signal an error,
  1338. exit with a return code of \code{255}. The interpreters in chapters
  1339. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1340. \code{trapped-error}.
  1341. \fi}
  1342. % TODO: how to deal with too-large integers in the Python interpreter?
  1343. %% This convention applies to the languages defined in this
  1344. %% book, as a way to simplify the student's task of implementing them,
  1345. %% but this convention is not applicable to all programming languages.
  1346. %%
  1347. Moving on to the last feature of the \LangInt{} language, the
  1348. \READOP{} operation prompts the user of the program for an integer.
  1349. Recall that program \eqref{eq:arith-prog} requests an integer input
  1350. and then subtracts \code{8}. So if we run
  1351. {\if\edition\racketEd
  1352. \begin{lstlisting}
  1353. (interp_Lint (Program '() ast1_1))
  1354. \end{lstlisting}
  1355. \fi}
  1356. {\if\edition\pythonEd
  1357. \begin{lstlisting}
  1358. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1359. \end{lstlisting}
  1360. \fi}
  1361. \noindent and if the input is \code{50}, the result is \code{42}.
  1362. We include the \READOP{} operation in \LangInt{} so a clever student
  1363. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1364. during compilation to obtain the output and then generates the trivial
  1365. code to produce the output.\footnote{Yes, a clever student did this in the
  1366. first instance of this course!}
  1367. The job of a compiler is to translate a program in one language into a
  1368. program in another language so that the output program behaves the
  1369. same way as the input program. This idea is depicted in the
  1370. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1371. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1372. Given a compiler that translates from language $\mathcal{L}_1$ to
  1373. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1374. compiler must translate it into some program $P_2$ such that
  1375. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1376. same input $i$ yields the same output $o$.
  1377. \begin{equation} \label{eq:compile-correct}
  1378. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1379. \node (p1) at (0, 0) {$P_1$};
  1380. \node (p2) at (3, 0) {$P_2$};
  1381. \node (o) at (3, -2.5) {$o$};
  1382. \path[->] (p1) edge [above] node {compile} (p2);
  1383. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1384. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1385. \end{tikzpicture}
  1386. \end{equation}
  1387. In the next section we see our first example of a compiler.
  1388. \section{Example Compiler: a Partial Evaluator}
  1389. \label{sec:partial-evaluation}
  1390. In this section we consider a compiler that translates \LangInt{}
  1391. programs into \LangInt{} programs that may be more efficient. The
  1392. compiler eagerly computes the parts of the program that do not depend
  1393. on any inputs, a process known as \emph{partial
  1394. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1395. For example, given the following program
  1396. {\if\edition\racketEd
  1397. \begin{lstlisting}
  1398. (+ (read) (- (+ 5 3)))
  1399. \end{lstlisting}
  1400. \fi}
  1401. {\if\edition\pythonEd
  1402. \begin{lstlisting}
  1403. print(input_int() + -(5 + 3) )
  1404. \end{lstlisting}
  1405. \fi}
  1406. \noindent our compiler translates it into the program
  1407. {\if\edition\racketEd
  1408. \begin{lstlisting}
  1409. (+ (read) -8)
  1410. \end{lstlisting}
  1411. \fi}
  1412. {\if\edition\pythonEd
  1413. \begin{lstlisting}
  1414. print(input_int() + -8)
  1415. \end{lstlisting}
  1416. \fi}
  1417. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1418. evaluator for the \LangInt{} language. The output of the partial evaluator
  1419. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1420. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1421. whereas the code for partially evaluating the negation and addition
  1422. operations is factored into three auxiliary functions:
  1423. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1424. functions is the output of partially evaluating the children.
  1425. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1426. arguments are integers and if they are, perform the appropriate
  1427. arithmetic. Otherwise, they create an AST node for the arithmetic
  1428. operation.
  1429. \begin{figure}[tp]
  1430. \begin{tcolorbox}[colback=white]
  1431. {\if\edition\racketEd
  1432. \begin{lstlisting}
  1433. (define (pe_neg r)
  1434. (match r
  1435. [(Int n) (Int (fx- 0 n))]
  1436. [else (Prim '- (list r))]))
  1437. (define (pe_add r1 r2)
  1438. (match* (r1 r2)
  1439. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1440. [(_ _) (Prim '+ (list r1 r2))]))
  1441. (define (pe_sub r1 r2)
  1442. (match* (r1 r2)
  1443. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1444. [(_ _) (Prim '- (list r1 r2))]))
  1445. (define (pe_exp e)
  1446. (match e
  1447. [(Int n) (Int n)]
  1448. [(Prim 'read '()) (Prim 'read '())]
  1449. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1450. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1451. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1452. (define (pe_Lint p)
  1453. (match p
  1454. [(Program '() e) (Program '() (pe_exp e))]))
  1455. \end{lstlisting}
  1456. \fi}
  1457. {\if\edition\pythonEd
  1458. \begin{lstlisting}
  1459. def pe_neg(r):
  1460. match r:
  1461. case Constant(n):
  1462. return Constant(-n)
  1463. case _:
  1464. return UnaryOp(USub(), r)
  1465. def pe_add(r1, r2):
  1466. match (r1, r2):
  1467. case (Constant(n1), Constant(n2)):
  1468. return Constant(n1 + n2)
  1469. case _:
  1470. return BinOp(r1, Add(), r2)
  1471. def pe_sub(r1, r2):
  1472. match (r1, r2):
  1473. case (Constant(n1), Constant(n2)):
  1474. return Constant(n1 - n2)
  1475. case _:
  1476. return BinOp(r1, Sub(), r2)
  1477. def pe_exp(e):
  1478. match e:
  1479. case BinOp(left, Add(), right):
  1480. return pe_add(pe_exp(left), pe_exp(right))
  1481. case BinOp(left, Sub(), right):
  1482. return pe_sub(pe_exp(left), pe_exp(right))
  1483. case UnaryOp(USub(), v):
  1484. return pe_neg(pe_exp(v))
  1485. case Constant(value):
  1486. return e
  1487. case Call(Name('input_int'), []):
  1488. return e
  1489. def pe_stmt(s):
  1490. match s:
  1491. case Expr(Call(Name('print'), [arg])):
  1492. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1493. case Expr(value):
  1494. return Expr(pe_exp(value))
  1495. def pe_P_int(p):
  1496. match p:
  1497. case Module(body):
  1498. new_body = [pe_stmt(s) for s in body]
  1499. return Module(new_body)
  1500. \end{lstlisting}
  1501. \fi}
  1502. \end{tcolorbox}
  1503. \caption{A partial evaluator for \LangInt{}.}
  1504. \label{fig:pe-arith}
  1505. \end{figure}
  1506. To gain some confidence that the partial evaluator is correct, we can
  1507. test whether it produces programs that produce the same result as the
  1508. input programs. That is, we can test whether it satisfies Diagram
  1509. \ref{eq:compile-correct}.
  1510. %
  1511. {\if\edition\racketEd
  1512. The following code runs the partial evaluator on several examples and
  1513. tests the output program. The \texttt{parse-program} and
  1514. \texttt{assert} functions are defined in
  1515. Appendix~\ref{appendix:utilities}.\\
  1516. \begin{minipage}{1.0\textwidth}
  1517. \begin{lstlisting}
  1518. (define (test_pe p)
  1519. (assert "testing pe_Lint"
  1520. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1521. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1522. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1523. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1524. \end{lstlisting}
  1525. \end{minipage}
  1526. \fi}
  1527. % TODO: python version of testing the PE
  1528. \begin{exercise}\normalfont\normalsize
  1529. Create three programs in the \LangInt{} language and test whether
  1530. partially evaluating them with \code{pe\_Lint} and then
  1531. interpreting them with \code{interp\_Lint} gives the same result
  1532. as directly interpreting them with \code{interp\_Lint}.
  1533. \end{exercise}
  1534. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1535. \chapter{Integers and Variables}
  1536. \label{ch:Lvar}
  1537. This chapter is about compiling a subset of
  1538. \racket{Racket}\python{Python} to x86-64 assembly
  1539. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1540. integer arithmetic and local variables. We often refer to x86-64
  1541. simply as x86. The chapter begins with a description of the
  1542. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1543. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1544. large so we discuss only the instructions needed for compiling
  1545. \LangVar{}. We introduce more x86 instructions in later chapters.
  1546. After introducing \LangVar{} and x86, we reflect on their differences
  1547. and come up with a plan to break down the translation from \LangVar{}
  1548. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1549. rest of the sections in this chapter give detailed hints regarding
  1550. each step. We hope to give enough hints that the well-prepared
  1551. reader, together with a few friends, can implement a compiler from
  1552. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1553. the scale of this first compiler, the instructor solution for the
  1554. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1555. code.
  1556. \section{The \LangVar{} Language}
  1557. \label{sec:s0}
  1558. \index{subject}{variable}
  1559. The \LangVar{} language extends the \LangInt{} language with
  1560. variables. The concrete syntax of the \LangVar{} language is defined
  1561. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1562. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1563. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1564. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1565. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1566. syntax of \LangVar{} includes the \racket{\key{Program}
  1567. struct}\python{\key{Module} instance} to mark the top of the
  1568. program.
  1569. %% The $\itm{info}$
  1570. %% field of the \key{Program} structure contains an \emph{association
  1571. %% list} (a list of key-value pairs) that is used to communicate
  1572. %% auxiliary data from one compiler pass the next.
  1573. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1574. exhibit several compilation techniques.
  1575. \newcommand{\LvarGrammarRacket}{
  1576. \begin{array}{rcl}
  1577. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1578. \end{array}
  1579. }
  1580. \newcommand{\LvarASTRacket}{
  1581. \begin{array}{rcl}
  1582. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1583. \end{array}
  1584. }
  1585. \newcommand{\LvarGrammarPython}{
  1586. \begin{array}{rcl}
  1587. \Exp &::=& \Var{} \\
  1588. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1589. \end{array}
  1590. }
  1591. \newcommand{\LvarASTPython}{
  1592. \begin{array}{rcl}
  1593. \Exp{} &::=& \VAR{\Var{}} \\
  1594. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1595. \end{array}
  1596. }
  1597. \begin{figure}[tp]
  1598. \centering
  1599. \begin{tcolorbox}[colback=white]
  1600. {\if\edition\racketEd
  1601. \[
  1602. \begin{array}{l}
  1603. \gray{\LintGrammarRacket{}} \\ \hline
  1604. \LvarGrammarRacket{} \\
  1605. \begin{array}{rcl}
  1606. \LangVarM{} &::=& \Exp
  1607. \end{array}
  1608. \end{array}
  1609. \]
  1610. \fi}
  1611. {\if\edition\pythonEd
  1612. \[
  1613. \begin{array}{l}
  1614. \gray{\LintGrammarPython} \\ \hline
  1615. \LvarGrammarPython \\
  1616. \begin{array}{rcl}
  1617. \LangVarM{} &::=& \Stmt^{*}
  1618. \end{array}
  1619. \end{array}
  1620. \]
  1621. \fi}
  1622. \end{tcolorbox}
  1623. \caption{The concrete syntax of \LangVar{}.}
  1624. \label{fig:Lvar-concrete-syntax}
  1625. \end{figure}
  1626. \begin{figure}[tp]
  1627. \centering
  1628. \begin{tcolorbox}[colback=white]
  1629. {\if\edition\racketEd
  1630. \[
  1631. \begin{array}{l}
  1632. \gray{\LintASTRacket{}} \\ \hline
  1633. \LvarASTRacket \\
  1634. \begin{array}{rcl}
  1635. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1636. \end{array}
  1637. \end{array}
  1638. \]
  1639. \fi}
  1640. {\if\edition\pythonEd
  1641. \[
  1642. \begin{array}{l}
  1643. \gray{\LintASTPython}\\ \hline
  1644. \LvarASTPython \\
  1645. \begin{array}{rcl}
  1646. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1647. \end{array}
  1648. \end{array}
  1649. \]
  1650. \fi}
  1651. \end{tcolorbox}
  1652. \caption{The abstract syntax of \LangVar{}.}
  1653. \label{fig:Lvar-syntax}
  1654. \end{figure}
  1655. {\if\edition\racketEd
  1656. Let us dive further into the syntax and semantics of the \LangVar{}
  1657. language. The \key{let} feature defines a variable for use within its
  1658. body and initializes the variable with the value of an expression.
  1659. The abstract syntax for \key{let} is defined in
  1660. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1661. \begin{lstlisting}
  1662. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1663. \end{lstlisting}
  1664. For example, the following program initializes \code{x} to $32$ and then
  1665. evaluates the body \code{(+ 10 x)}, producing $42$.
  1666. \begin{lstlisting}
  1667. (let ([x (+ 12 20)]) (+ 10 x))
  1668. \end{lstlisting}
  1669. \fi}
  1670. %
  1671. {\if\edition\pythonEd
  1672. %
  1673. The \LangVar{} language includes assignment statements, which define a
  1674. variable for use in later statements and initializes the variable with
  1675. the value of an expression. The abstract syntax for assignment is
  1676. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1677. assignment is \index{subject}{Assign@\texttt{Assign}}
  1678. \begin{lstlisting}
  1679. |$\itm{var}$| = |$\itm{exp}$|
  1680. \end{lstlisting}
  1681. For example, the following program initializes the variable \code{x}
  1682. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1683. \begin{lstlisting}
  1684. x = 12 + 20
  1685. print(10 + x)
  1686. \end{lstlisting}
  1687. \fi}
  1688. {\if\edition\racketEd
  1689. %
  1690. When there are multiple \key{let}'s for the same variable, the closest
  1691. enclosing \key{let} is used. That is, variable definitions overshadow
  1692. prior definitions. Consider the following program with two \key{let}'s
  1693. that define two variables named \code{x}. Can you figure out the
  1694. result?
  1695. \begin{lstlisting}
  1696. (let ([x 32]) (+ (let ([x 10]) x) x))
  1697. \end{lstlisting}
  1698. For the purposes of depicting which variable occurrences correspond to
  1699. which definitions, the following shows the \code{x}'s annotated with
  1700. subscripts to distinguish them. Double check that your answer for the
  1701. above is the same as your answer for this annotated version of the
  1702. program.
  1703. \begin{lstlisting}
  1704. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1705. \end{lstlisting}
  1706. The initializing expression is always evaluated before the body of the
  1707. \key{let}, so in the following, the \key{read} for \code{x} is
  1708. performed before the \key{read} for \code{y}. Given the input
  1709. $52$ then $10$, the following produces $42$ (not $-42$).
  1710. \begin{lstlisting}
  1711. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1712. \end{lstlisting}
  1713. \fi}
  1714. \subsection{Extensible Interpreters via Method Overriding}
  1715. \label{sec:extensible-interp}
  1716. To prepare for discussing the interpreter of \LangVar{}, we explain
  1717. why we implement it in an object-oriented style. Throughout this book
  1718. we define many interpreters, one for each of language that we
  1719. study. Because each language builds on the prior one, there is a lot
  1720. of commonality between these interpreters. We want to write down the
  1721. common parts just once instead of many times. A naive
  1722. interpreter for \LangVar{} would handle the
  1723. \racket{cases for variables and \code{let}}
  1724. \python{case for variables}
  1725. but dispatch to an interpreter for \LangInt{}
  1726. in the rest of the cases. The following code sketches this idea. (We
  1727. explain the \code{env} parameter soon, in
  1728. Section~\ref{sec:interp-Lvar}.)
  1729. \begin{center}
  1730. {\if\edition\racketEd
  1731. \begin{minipage}{0.45\textwidth}
  1732. \begin{lstlisting}
  1733. (define ((interp_Lint env) e)
  1734. (match e
  1735. [(Prim '- (list e1))
  1736. (fx- 0 ((interp_Lint env) e1))]
  1737. ...))
  1738. \end{lstlisting}
  1739. \end{minipage}
  1740. \begin{minipage}{0.45\textwidth}
  1741. \begin{lstlisting}
  1742. (define ((interp_Lvar env) e)
  1743. (match e
  1744. [(Var x)
  1745. (dict-ref env x)]
  1746. [(Let x e body)
  1747. (define v ((interp_exp env) e))
  1748. (define env^ (dict-set env x v))
  1749. ((interp_exp env^) body)]
  1750. [else ((interp_Lint env) e)]))
  1751. \end{lstlisting}
  1752. \end{minipage}
  1753. \fi}
  1754. {\if\edition\pythonEd
  1755. \begin{minipage}{0.45\textwidth}
  1756. \begin{lstlisting}
  1757. def interp_Lint(e, env):
  1758. match e:
  1759. case UnaryOp(USub(), e1):
  1760. return - interp_Lint(e1, env)
  1761. ...
  1762. \end{lstlisting}
  1763. \end{minipage}
  1764. \begin{minipage}{0.45\textwidth}
  1765. \begin{lstlisting}
  1766. def interp_Lvar(e, env):
  1767. match e:
  1768. case Name(id):
  1769. return env[id]
  1770. case _:
  1771. return interp_Lint(e, env)
  1772. \end{lstlisting}
  1773. \end{minipage}
  1774. \fi}
  1775. \end{center}
  1776. The problem with this naive approach is that it does not handle
  1777. situations in which an \LangVar{} feature, such as a variable, is
  1778. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1779. the following program.
  1780. %
  1781. {\if\edition\racketEd
  1782. \begin{lstlisting}
  1783. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1784. \end{lstlisting}
  1785. \fi}
  1786. {\if\edition\pythonEd
  1787. \begin{lstlisting}
  1788. y = 10
  1789. print(-y)
  1790. \end{lstlisting}
  1791. \fi}
  1792. %
  1793. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1794. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1795. then it recursively calls \code{interp\_Lint} again on its argument.
  1796. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1797. an error!
  1798. To make our interpreters extensible we need something called
  1799. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1800. recursive knot is delayed to when the functions are
  1801. composed. Object-oriented languages provide open recursion via
  1802. method overriding\index{subject}{method overriding}. The
  1803. following code uses method overriding to interpret \LangInt{} and
  1804. \LangVar{} using
  1805. %
  1806. \racket{the
  1807. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1808. \index{subject}{class} feature of Racket.}
  1809. %
  1810. \python{a Python \code{class} definition.}
  1811. %
  1812. We define one class for each language and define a method for
  1813. interpreting expressions inside each class. The class for \LangVar{}
  1814. inherits from the class for \LangInt{} and the method
  1815. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1816. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1817. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1818. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1819. \code{interp\_exp} in \LangInt{}.
  1820. \begin{center}
  1821. \hspace{-20pt}
  1822. {\if\edition\racketEd
  1823. \begin{minipage}{0.45\textwidth}
  1824. \begin{lstlisting}
  1825. (define interp-Lint-class
  1826. (class object%
  1827. (define/public ((interp_exp env) e)
  1828. (match e
  1829. [(Prim '- (list e))
  1830. (fx- 0 ((interp_exp env) e))]
  1831. ...))
  1832. ...))
  1833. \end{lstlisting}
  1834. \end{minipage}
  1835. \begin{minipage}{0.45\textwidth}
  1836. \begin{lstlisting}
  1837. (define interp-Lvar-class
  1838. (class interp-Lint-class
  1839. (define/override ((interp_exp env) e)
  1840. (match e
  1841. [(Var x)
  1842. (dict-ref env x)]
  1843. [(Let x e body)
  1844. (define v ((interp_exp env) e))
  1845. (define env^ (dict-set env x v))
  1846. ((interp_exp env^) body)]
  1847. [else
  1848. (super (interp_exp env) e)]))
  1849. ...
  1850. ))
  1851. \end{lstlisting}
  1852. \end{minipage}
  1853. \fi}
  1854. {\if\edition\pythonEd
  1855. \begin{minipage}{0.45\textwidth}
  1856. \begin{lstlisting}
  1857. class InterpLint:
  1858. def interp_exp(e):
  1859. match e:
  1860. case UnaryOp(USub(), e1):
  1861. return -self.interp_exp(e1)
  1862. ...
  1863. ...
  1864. \end{lstlisting}
  1865. \end{minipage}
  1866. \begin{minipage}{0.45\textwidth}
  1867. \begin{lstlisting}
  1868. def InterpLvar(InterpLint):
  1869. def interp_exp(e):
  1870. match e:
  1871. case Name(id):
  1872. return env[id]
  1873. case _:
  1874. return super().interp_exp(e)
  1875. ...
  1876. \end{lstlisting}
  1877. \end{minipage}
  1878. \fi}
  1879. \end{center}
  1880. Getting back to the troublesome example, repeated here:
  1881. {\if\edition\racketEd
  1882. \begin{lstlisting}
  1883. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1884. \end{lstlisting}
  1885. \fi}
  1886. {\if\edition\pythonEd
  1887. \begin{lstlisting}
  1888. y = 10
  1889. print(-y)
  1890. \end{lstlisting}
  1891. \fi}
  1892. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1893. \racket{on this expression,}
  1894. \python{on the \code{-y} expression,}
  1895. %
  1896. call it \code{e0}, by creating an object of the \LangVar{} class
  1897. and calling the \code{interp\_exp} method.
  1898. {\if\edition\racketEd
  1899. \begin{lstlisting}
  1900. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1901. \end{lstlisting}
  1902. \fi}
  1903. {\if\edition\pythonEd
  1904. \begin{lstlisting}
  1905. InterpLvar().interp_exp(e0)
  1906. \end{lstlisting}
  1907. \fi}
  1908. \noindent To process the \code{-} operator, the default case of
  1909. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1910. method in \LangInt{}. But then for the recursive method call, it
  1911. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1912. \code{Var} node is handled correctly. Thus, method overriding gives us
  1913. the open recursion that we need to implement our interpreters in an
  1914. extensible way.
  1915. \subsection{Definitional Interpreter for \LangVar{}}
  1916. \label{sec:interp-Lvar}
  1917. {\if\edition\racketEd
  1918. \begin{figure}[tp]
  1919. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1920. \small
  1921. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1922. An \emph{association list} (alist) is a list of key-value pairs.
  1923. For example, we can map people to their ages with an alist.
  1924. \index{subject}{alist}\index{subject}{association list}
  1925. \begin{lstlisting}[basicstyle=\ttfamily]
  1926. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1927. \end{lstlisting}
  1928. The \emph{dictionary} interface is for mapping keys to values.
  1929. Every alist implements this interface. \index{subject}{dictionary} The package
  1930. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1931. provides many functions for working with dictionaries. Here
  1932. are a few of them:
  1933. \begin{description}
  1934. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1935. returns the value associated with the given $\itm{key}$.
  1936. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1937. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1938. but otherwise is the same as $\itm{dict}$.
  1939. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1940. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1941. of keys and values in $\itm{dict}$. For example, the following
  1942. creates a new alist in which the ages are incremented.
  1943. \end{description}
  1944. \vspace{-10pt}
  1945. \begin{lstlisting}[basicstyle=\ttfamily]
  1946. (for/list ([(k v) (in-dict ages)])
  1947. (cons k (add1 v)))
  1948. \end{lstlisting}
  1949. \end{tcolorbox}
  1950. %\end{wrapfigure}
  1951. \caption{Association lists implement the dictionary interface.}
  1952. \label{fig:alist}
  1953. \end{figure}
  1954. \fi}
  1955. Having justified the use of classes and methods to implement
  1956. interpreters, we revisit the definitional interpreter for \LangInt{}
  1957. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1958. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1959. interpreter for \LangVar{} adds two new \key{match} cases for
  1960. variables and \racket{\key{let}}\python{assignment}. For
  1961. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1962. value bound to a variable to all the uses of the variable. To
  1963. accomplish this, we maintain a mapping from variables to values
  1964. called an \emph{environment}\index{subject}{environment}.
  1965. %
  1966. We use
  1967. %
  1968. \racket{an association list (alist) }%
  1969. %
  1970. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1971. %
  1972. to represent the environment.
  1973. %
  1974. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1975. and the \code{racket/dict} package.}
  1976. %
  1977. The \code{interp\_exp} function takes the current environment,
  1978. \code{env}, as an extra parameter. When the interpreter encounters a
  1979. variable, it looks up the corresponding value in the dictionary.
  1980. %
  1981. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1982. initializing expression, extends the environment with the result
  1983. value bound to the variable, using \code{dict-set}, then evaluates
  1984. the body of the \key{Let}.}
  1985. %
  1986. \python{When the interpreter encounters an assignment, it evaluates
  1987. the initializing expression and then associates the resulting value
  1988. with the variable in the environment.}
  1989. \begin{figure}[tp]
  1990. \begin{tcolorbox}[colback=white]
  1991. {\if\edition\racketEd
  1992. \begin{lstlisting}
  1993. (define interp-Lint-class
  1994. (class object%
  1995. (super-new)
  1996. (define/public ((interp_exp env) e)
  1997. (match e
  1998. [(Int n) n]
  1999. [(Prim 'read '())
  2000. (define r (read))
  2001. (cond [(fixnum? r) r]
  2002. [else (error 'interp_exp "expected an integer" r)])]
  2003. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2004. [(Prim '+ (list e1 e2))
  2005. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2006. [(Prim '- (list e1 e2))
  2007. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2008. (define/public (interp_program p)
  2009. (match p
  2010. [(Program '() e) ((interp_exp '()) e)]))
  2011. ))
  2012. \end{lstlisting}
  2013. \fi}
  2014. {\if\edition\pythonEd
  2015. \begin{lstlisting}
  2016. class InterpLint:
  2017. def interp_exp(self, e, env):
  2018. match e:
  2019. case BinOp(left, Add(), right):
  2020. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2021. case BinOp(left, Sub(), right):
  2022. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2023. case UnaryOp(USub(), v):
  2024. return - self.interp_exp(v, env)
  2025. case Constant(value):
  2026. return value
  2027. case Call(Name('input_int'), []):
  2028. return int(input())
  2029. def interp_stmts(self, ss, env):
  2030. if len(ss) == 0:
  2031. return
  2032. match ss[0]:
  2033. case Expr(Call(Name('print'), [arg])):
  2034. print(self.interp_exp(arg, env), end='')
  2035. return self.interp_stmts(ss[1:], env)
  2036. case Expr(value):
  2037. self.interp_exp(value, env)
  2038. return self.interp_stmts(ss[1:], env)
  2039. def interp(self, p):
  2040. match p:
  2041. case Module(body):
  2042. self.interp_stmts(body, {})
  2043. def interp_Lint(p):
  2044. return InterpLint().interp(p)
  2045. \end{lstlisting}
  2046. \fi}
  2047. \end{tcolorbox}
  2048. \caption{Interpreter for \LangInt{} as a class.}
  2049. \label{fig:interp-Lint-class}
  2050. \end{figure}
  2051. \begin{figure}[tp]
  2052. \begin{tcolorbox}[colback=white]
  2053. {\if\edition\racketEd
  2054. \begin{lstlisting}
  2055. (define interp-Lvar-class
  2056. (class interp-Lint-class
  2057. (super-new)
  2058. (define/override ((interp_exp env) e)
  2059. (match e
  2060. [(Var x) (dict-ref env x)]
  2061. [(Let x e body)
  2062. (define new-env (dict-set env x ((interp_exp env) e)))
  2063. ((interp_exp new-env) body)]
  2064. [else ((super interp-exp env) e)]))
  2065. ))
  2066. (define (interp_Lvar p)
  2067. (send (new interp-Lvar-class) interp_program p))
  2068. \end{lstlisting}
  2069. \fi}
  2070. {\if\edition\pythonEd
  2071. \begin{lstlisting}
  2072. class InterpLvar(InterpLint):
  2073. def interp_exp(self, e, env):
  2074. match e:
  2075. case Name(id):
  2076. return env[id]
  2077. case _:
  2078. return super().interp_exp(e, env)
  2079. def interp_stmts(self, ss, env):
  2080. if len(ss) == 0:
  2081. return
  2082. match ss[0]:
  2083. case Assign([lhs], value):
  2084. env[lhs.id] = self.interp_exp(value, env)
  2085. return self.interp_stmts(ss[1:], env)
  2086. case _:
  2087. return super().interp_stmts(ss, env)
  2088. def interp_Lvar(p):
  2089. return InterpLvar().interp(p)
  2090. \end{lstlisting}
  2091. \fi}
  2092. \end{tcolorbox}
  2093. \caption{Interpreter for the \LangVar{} language.}
  2094. \label{fig:interp-Lvar}
  2095. \end{figure}
  2096. The goal for this chapter is to implement a compiler that translates
  2097. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2098. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2099. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2100. That is, they output the same integer $n$. We depict this correctness
  2101. criteria in the following diagram.
  2102. \[
  2103. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2104. \node (p1) at (0, 0) {$P_1$};
  2105. \node (p2) at (4, 0) {$P_2$};
  2106. \node (o) at (4, -2) {$n$};
  2107. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2108. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2109. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2110. \end{tikzpicture}
  2111. \]
  2112. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2113. compiling \LangVar{}.
  2114. \section{The \LangXInt{} Assembly Language}
  2115. \label{sec:x86}
  2116. \index{subject}{x86}
  2117. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2118. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2119. assembler.
  2120. %
  2121. A program begins with a \code{main} label followed by a sequence of
  2122. instructions. The \key{globl} directive says that the \key{main}
  2123. procedure is externally visible, which is necessary so that the
  2124. operating system can call it.
  2125. %
  2126. An x86 program is stored in the computer's memory. For our purposes,
  2127. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2128. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2129. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2130. the address of the next instruction to be executed. For most
  2131. instructions, the program counter is incremented after the instruction
  2132. is executed, so it points to the next instruction in memory. Most x86
  2133. instructions take two operands, where each operand is either an
  2134. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2135. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2136. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2137. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2138. && \key{r8} \MID \key{r9} \MID \key{r10}
  2139. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2140. \MID \key{r14} \MID \key{r15}}
  2141. \newcommand{\GrammarXInt}{
  2142. \begin{array}{rcl}
  2143. \Reg &::=& \allregisters{} \\
  2144. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2145. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2146. \key{subq} \; \Arg\key{,} \Arg \MID
  2147. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2148. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2149. \key{callq} \; \mathit{label} \MID
  2150. \key{retq} \MID
  2151. \key{jmp}\,\itm{label} \MID \\
  2152. && \itm{label}\key{:}\; \Instr
  2153. \end{array}
  2154. }
  2155. \begin{figure}[tp]
  2156. \begin{tcolorbox}[colback=white]
  2157. {\if\edition\racketEd
  2158. \[
  2159. \begin{array}{l}
  2160. \GrammarXInt \\
  2161. \begin{array}{lcl}
  2162. \LangXIntM{} &::= & \key{.globl main}\\
  2163. & & \key{main:} \; \Instr\ldots
  2164. \end{array}
  2165. \end{array}
  2166. \]
  2167. \fi}
  2168. {\if\edition\pythonEd
  2169. \[
  2170. \begin{array}{lcl}
  2171. \Reg &::=& \allregisters{} \\
  2172. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2173. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2174. \key{subq} \; \Arg\key{,} \Arg \MID
  2175. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2176. && \key{callq} \; \mathit{label} \MID
  2177. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2178. \LangXIntM{} &::= & \key{.globl main}\\
  2179. & & \key{main:} \; \Instr^{*}
  2180. \end{array}
  2181. \]
  2182. \fi}
  2183. \end{tcolorbox}
  2184. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2185. \label{fig:x86-int-concrete}
  2186. \end{figure}
  2187. A register is a special kind of variable that holds a 64-bit
  2188. value. There are 16 general-purpose registers in the computer and
  2189. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2190. is written with a \key{\%} followed by the register name, such as
  2191. \key{\%rax}.
  2192. An immediate value is written using the notation \key{\$}$n$ where $n$
  2193. is an integer.
  2194. %
  2195. %
  2196. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2197. which obtains the address stored in register $r$ and then adds $n$
  2198. bytes to the address. The resulting address is used to load or store
  2199. to memory depending on whether it occurs as a source or destination
  2200. argument of an instruction.
  2201. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2202. source $s$ and destination $d$, applies the arithmetic operation, then
  2203. writes the result back to the destination $d$. \index{subject}{instruction}
  2204. %
  2205. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2206. stores the result in $d$.
  2207. %
  2208. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2209. specified by the label and $\key{retq}$ returns from a procedure to
  2210. its caller.
  2211. %
  2212. We discuss procedure calls in more detail later in this chapter and in
  2213. Chapter~\ref{ch:Lfun}.
  2214. %
  2215. The last letter \key{q} indicates that these instructions operate on
  2216. quadwords, i.e., 64-bit values.
  2217. %
  2218. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2219. counter to the address of the instruction after the specified
  2220. label.}
  2221. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2222. all of the x86 instructions used in this book.
  2223. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2224. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2225. \lstinline{movq $10, %rax}
  2226. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2227. adds $32$ to the $10$ in \key{rax} and
  2228. puts the result, $42$, back into \key{rax}.
  2229. %
  2230. The last instruction \key{retq} finishes the \key{main} function by
  2231. returning the integer in \key{rax} to the operating system. The
  2232. operating system interprets this integer as the program's exit
  2233. code. By convention, an exit code of 0 indicates that a program
  2234. completed successfully, and all other exit codes indicate various
  2235. errors.
  2236. %
  2237. \racket{Nevertheless, in this book we return the result of the program
  2238. as the exit code.}
  2239. \begin{figure}[tbp]
  2240. \begin{minipage}{0.45\textwidth}
  2241. \begin{tcolorbox}[colback=white]
  2242. \begin{lstlisting}
  2243. .globl main
  2244. main:
  2245. movq $10, %rax
  2246. addq $32, %rax
  2247. retq
  2248. \end{lstlisting}
  2249. \end{tcolorbox}
  2250. \end{minipage}
  2251. \caption{An x86 program that computes
  2252. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2253. \label{fig:p0-x86}
  2254. \end{figure}
  2255. We exhibit the use of memory for storing intermediate results in the
  2256. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2257. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2258. uses a region of memory called the \emph{procedure call stack} (or
  2259. \emph{stack} for
  2260. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2261. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2262. for each procedure call. The memory layout for an individual frame is
  2263. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2264. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2265. address of the item at the top of the stack. In general, we use the
  2266. term \emph{pointer}\index{subject}{pointer} for something that
  2267. contains an address. The stack grows downward in memory, so we
  2268. increase the size of the stack by subtracting from the stack pointer.
  2269. In the context of a procedure call, the \emph{return
  2270. address}\index{subject}{return address} is the instruction after the
  2271. call instruction on the caller side. The function call instruction,
  2272. \code{callq}, pushes the return address onto the stack prior to
  2273. jumping to the procedure. The register \key{rbp} is the \emph{base
  2274. pointer}\index{subject}{base pointer} and is used to access
  2275. variables that are stored in the frame of the current procedure call.
  2276. The base pointer of the caller is stored after the return address. In
  2277. Figure~\ref{fig:frame} we number the variables from $1$ to
  2278. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2279. at $-16\key{(\%rbp)}$, etc.
  2280. \begin{figure}[tbp]
  2281. \begin{minipage}{0.66\textwidth}
  2282. \begin{tcolorbox}[colback=white]
  2283. {\if\edition\racketEd
  2284. \begin{lstlisting}
  2285. start:
  2286. movq $10, -8(%rbp)
  2287. negq -8(%rbp)
  2288. movq -8(%rbp), %rax
  2289. addq $52, %rax
  2290. jmp conclusion
  2291. .globl main
  2292. main:
  2293. pushq %rbp
  2294. movq %rsp, %rbp
  2295. subq $16, %rsp
  2296. jmp start
  2297. conclusion:
  2298. addq $16, %rsp
  2299. popq %rbp
  2300. retq
  2301. \end{lstlisting}
  2302. \fi}
  2303. {\if\edition\pythonEd
  2304. \begin{lstlisting}
  2305. .globl main
  2306. main:
  2307. pushq %rbp
  2308. movq %rsp, %rbp
  2309. subq $16, %rsp
  2310. movq $10, -8(%rbp)
  2311. negq -8(%rbp)
  2312. movq -8(%rbp), %rax
  2313. addq $52, %rax
  2314. addq $16, %rsp
  2315. popq %rbp
  2316. retq
  2317. \end{lstlisting}
  2318. \fi}
  2319. \end{tcolorbox}
  2320. \end{minipage}
  2321. \caption{An x86 program that computes
  2322. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2323. \label{fig:p1-x86}
  2324. \end{figure}
  2325. \begin{figure}[tbp]
  2326. \centering
  2327. \begin{tabular}{|r|l|} \hline
  2328. Position & Contents \\ \hline
  2329. 8(\key{\%rbp}) & return address \\
  2330. 0(\key{\%rbp}) & old \key{rbp} \\
  2331. -8(\key{\%rbp}) & variable $1$ \\
  2332. -16(\key{\%rbp}) & variable $2$ \\
  2333. \ldots & \ldots \\
  2334. 0(\key{\%rsp}) & variable $n$\\ \hline
  2335. \end{tabular}
  2336. \caption{Memory layout of a frame.}
  2337. \label{fig:frame}
  2338. \end{figure}
  2339. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2340. control is transferred from the operating system to the \code{main}
  2341. function. The operating system issues a \code{callq main} instruction
  2342. which pushes its return address on the stack and then jumps to
  2343. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2344. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2345. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2346. alignment (because the \code{callq} pushed the return address). The
  2347. first three instructions are the typical
  2348. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2349. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2350. pointer \code{rsp} and then saves the base pointer of the caller at
  2351. address \code{rsp} on the stack. The next instruction \code{movq
  2352. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2353. which is pointing at the location of the old base pointer. The
  2354. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2355. make enough room for storing variables. This program needs one
  2356. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2357. 16-byte aligned and we're ready to make calls to other functions.
  2358. \racket{The last instruction of the prelude is \code{jmp start}, which
  2359. transfers control to the instructions that were generated from the
  2360. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2361. \racket{The first instruction under the \code{start} label is}
  2362. %
  2363. \python{The first instruction after the prelude is}
  2364. %
  2365. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2366. %
  2367. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2368. $1$ to $-10$.
  2369. %
  2370. The next instruction moves the $-10$ from variable $1$ into the
  2371. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2372. the value in \code{rax}, updating its contents to $42$.
  2373. \racket{The three instructions under the label \code{conclusion} are the
  2374. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2375. %
  2376. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2377. \code{main} function consists of the last three instructions.}
  2378. %
  2379. The first two restore the \code{rsp} and \code{rbp} registers to the
  2380. state they were in at the beginning of the procedure. In particular,
  2381. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2382. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2383. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2384. \key{retq}, jumps back to the procedure that called this one and adds
  2385. $8$ to the stack pointer.
  2386. Our compiler needs a convenient representation for manipulating x86
  2387. programs, so we define an abstract syntax for x86 in
  2388. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2389. \LangXInt{}.
  2390. %
  2391. {\if\edition\pythonEd%
  2392. The main difference compared to the concrete syntax of \LangXInt{}
  2393. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2394. names, and register names are explicitly represented by strings.
  2395. \fi} %
  2396. {\if\edition\racketEd
  2397. The main difference compared to the concrete syntax of \LangXInt{}
  2398. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2399. front of every instruction. Instead instructions are grouped into
  2400. \emph{basic blocks}\index{subject}{basic block} with a
  2401. label associated with every basic block, which is why the \key{X86Program}
  2402. struct includes an alist mapping labels to basic blocks. The reason for this
  2403. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2404. introduce conditional branching. The \code{Block} structure includes
  2405. an $\itm{info}$ field that is not needed for this chapter but becomes
  2406. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2407. $\itm{info}$ field should contain an empty list.
  2408. \fi}
  2409. %
  2410. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2411. node includes an integer for representing the arity of the function,
  2412. i.e., the number of arguments, which is helpful to know during
  2413. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2414. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2415. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2416. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2417. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2418. \MID \skey{r14} \MID \skey{r15}}
  2419. \newcommand{\ASTXIntRacket}{
  2420. \begin{array}{lcl}
  2421. \Reg &::=& \allregisters{} \\
  2422. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2423. \MID \DEREF{\Reg}{\Int} \\
  2424. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2425. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2426. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2427. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2428. \MID \PUSHQ{\Arg}
  2429. \MID \POPQ{\Arg} \\
  2430. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2431. \MID \RETQ{}
  2432. \MID \JMP{\itm{label}} \\
  2433. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2434. \end{array}
  2435. }
  2436. \begin{figure}[tp]
  2437. \begin{tcolorbox}[colback=white]
  2438. \small
  2439. {\if\edition\racketEd
  2440. \[\arraycolsep=3pt
  2441. \begin{array}{l}
  2442. \ASTXIntRacket \\
  2443. \begin{array}{lcl}
  2444. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2445. \end{array}
  2446. \end{array}
  2447. \]
  2448. \fi}
  2449. {\if\edition\pythonEd
  2450. \[
  2451. \begin{array}{lcl}
  2452. \Reg &::=& \allastregisters{} \\
  2453. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2454. \MID \DEREF{\Reg}{\Int} \\
  2455. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2456. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2457. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2458. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2459. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2460. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2461. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2462. \end{array}
  2463. \]
  2464. \fi}
  2465. \end{tcolorbox}
  2466. \caption{The abstract syntax of \LangXInt{} assembly.}
  2467. \label{fig:x86-int-ast}
  2468. \end{figure}
  2469. \section{Planning the trip to x86}
  2470. \label{sec:plan-s0-x86}
  2471. To compile one language to another it helps to focus on the
  2472. differences between the two languages because the compiler will need
  2473. to bridge those differences. What are the differences between \LangVar{}
  2474. and x86 assembly? Here are some of the most important ones:
  2475. \begin{enumerate}
  2476. \item x86 arithmetic instructions typically have two arguments and
  2477. update the second argument in place. In contrast, \LangVar{}
  2478. arithmetic operations take two arguments and produce a new value.
  2479. An x86 instruction may have at most one memory-accessing argument.
  2480. Furthermore, some x86 instructions place special restrictions on
  2481. their arguments.
  2482. \item An argument of an \LangVar{} operator can be a deeply-nested
  2483. expression, whereas x86 instructions restrict their arguments to be
  2484. integer constants, registers, and memory locations.
  2485. {\if\edition\racketEd
  2486. \item The order of execution in x86 is explicit in the syntax: a
  2487. sequence of instructions and jumps to labeled positions, whereas in
  2488. \LangVar{} the order of evaluation is a left-to-right depth-first
  2489. traversal of the abstract syntax tree.
  2490. \fi}
  2491. \item A program in \LangVar{} can have any number of variables
  2492. whereas x86 has 16 registers and the procedure call stack.
  2493. {\if\edition\racketEd
  2494. \item Variables in \LangVar{} can shadow other variables with the
  2495. same name. In x86, registers have unique names and memory locations
  2496. have unique addresses.
  2497. \fi}
  2498. \end{enumerate}
  2499. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2500. down the problem into several steps, dealing with the above
  2501. differences one at a time. Each of these steps is called a \emph{pass}
  2502. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2503. %
  2504. This terminology comes from the way each step passes over, or
  2505. traverses, the AST of the program.
  2506. %
  2507. Furthermore, we follow the nanopass approach, which means we strive
  2508. for each pass to accomplish one clear objective (not two or three at
  2509. the same time).
  2510. %
  2511. We begin by sketching how we might implement each pass, and give them
  2512. names. We then figure out an ordering of the passes and the
  2513. input/output language for each pass. The very first pass has
  2514. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2515. its output language. In between we can choose whichever language is
  2516. most convenient for expressing the output of each pass, whether that
  2517. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2518. our own design. Finally, to implement each pass we write one
  2519. recursive function per non-terminal in the grammar of the input
  2520. language of the pass. \index{subject}{intermediate language}
  2521. Our compiler for \LangVar{} consists of the following passes.
  2522. %
  2523. \begin{description}
  2524. {\if\edition\racketEd
  2525. \item[\key{uniquify}] deals with the shadowing of variables by
  2526. renaming every variable to a unique name.
  2527. \fi}
  2528. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2529. of a primitive operation or function call is a variable or integer,
  2530. that is, an \emph{atomic} expression. We refer to non-atomic
  2531. expressions as \emph{complex}. This pass introduces temporary
  2532. variables to hold the results of complex
  2533. subexpressions.\index{subject}{atomic
  2534. expression}\index{subject}{complex expression}%
  2535. {\if\edition\racketEd
  2536. \item[\key{explicate\_control}] makes the execution order of the
  2537. program explicit. It converts the abstract syntax tree
  2538. representation into a graph in which each node is a labeled sequence
  2539. of statements and the edges are \code{goto} statements.
  2540. \fi}
  2541. \item[\key{select\_instructions}] handles the difference between
  2542. \LangVar{} operations and x86 instructions. This pass converts each
  2543. \LangVar{} operation to a short sequence of instructions that
  2544. accomplishes the same task.
  2545. \item[\key{assign\_homes}] replaces variables with registers or stack
  2546. locations.
  2547. \end{description}
  2548. %
  2549. {\if\edition\racketEd
  2550. %
  2551. Our treatment of \code{remove\_complex\_operands} and
  2552. \code{explicate\_control} as separate passes is an example of the
  2553. nanopass approach\footnote{For analogous decompositions of the
  2554. translation into continuation passing style, see the work of
  2555. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2556. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2557. %
  2558. \fi}
  2559. The next question is: in what order should we apply these passes? This
  2560. question can be challenging because it is difficult to know ahead of
  2561. time which orderings will be better (easier to implement, produce more
  2562. efficient code, etc.) so oftentimes trial-and-error is
  2563. involved. Nevertheless, we can plan ahead and make educated choices
  2564. regarding the ordering.
  2565. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2566. \key{uniquify}? The \key{uniquify} pass should come first because
  2567. \key{explicate\_control} changes all the \key{let}-bound variables to
  2568. become local variables whose scope is the entire program, which would
  2569. confuse variables with the same name.}
  2570. %
  2571. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2572. because the later removes the \key{let} form, but it is convenient to
  2573. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2574. %
  2575. \racket{The ordering of \key{uniquify} with respect to
  2576. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2577. \key{uniquify} to come first.}
  2578. The \key{select\_instructions} and \key{assign\_homes} passes are
  2579. intertwined.
  2580. %
  2581. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2582. passing arguments to functions and it is preferable to assign
  2583. parameters to their corresponding registers. This suggests that it
  2584. would be better to start with the \key{select\_instructions} pass,
  2585. which generates the instructions for argument passing, before
  2586. performing register allocation.
  2587. %
  2588. On the other hand, by selecting instructions first we may run into a
  2589. dead end in \key{assign\_homes}. Recall that only one argument of an
  2590. x86 instruction may be a memory access but \key{assign\_homes} might
  2591. be forced to assign both arguments to memory locations.
  2592. %
  2593. A sophisticated approach is to repeat the two passes until a solution
  2594. is found. However, to reduce implementation complexity we recommend
  2595. placing \key{select\_instructions} first, followed by the
  2596. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2597. that uses a reserved register to fix outstanding problems.
  2598. \begin{figure}[tbp]
  2599. \begin{tcolorbox}[colback=white]
  2600. {\if\edition\racketEd
  2601. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2602. \node (Lvar) at (0,2) {\large \LangVar{}};
  2603. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2604. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2605. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2606. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2607. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2608. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2609. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2610. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2611. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2612. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2613. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2614. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2615. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2616. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2617. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2618. \end{tikzpicture}
  2619. \fi}
  2620. {\if\edition\pythonEd
  2621. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2622. \node (Lvar) at (0,2) {\large \LangVar{}};
  2623. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2624. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2625. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2626. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2627. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2628. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2629. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2630. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2631. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2632. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2633. \end{tikzpicture}
  2634. \fi}
  2635. \end{tcolorbox}
  2636. \caption{Diagram of the passes for compiling \LangVar{}. }
  2637. \label{fig:Lvar-passes}
  2638. \end{figure}
  2639. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2640. passes and identifies the input and output language of each pass.
  2641. %
  2642. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2643. language, which extends \LangXInt{} with an unbounded number of
  2644. program-scope variables and removes the restrictions regarding
  2645. instruction arguments.
  2646. %
  2647. The last pass, \key{prelude\_and\_conclusion}, places the program
  2648. instructions inside a \code{main} function with instructions for the
  2649. prelude and conclusion.
  2650. %
  2651. \racket{In the next section we discuss the \LangCVar{} intermediate
  2652. language that serves as the output of \code{explicate\_control}.}
  2653. %
  2654. The remainder of this chapter provides guidance on the implementation
  2655. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2656. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2657. %% are programs that are still in the \LangVar{} language, though the
  2658. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2659. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2660. %% %
  2661. %% The output of \code{explicate\_control} is in an intermediate language
  2662. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2663. %% syntax, which we introduce in the next section. The
  2664. %% \key{select-instruction} pass translates from \LangCVar{} to
  2665. %% \LangXVar{}. The \key{assign-homes} and
  2666. %% \key{patch-instructions}
  2667. %% passes input and output variants of x86 assembly.
  2668. \newcommand{\CvarGrammarRacket}{
  2669. \begin{array}{lcl}
  2670. \Atm &::=& \Int \MID \Var \\
  2671. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2672. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2673. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2674. \end{array}
  2675. }
  2676. \newcommand{\CvarASTRacket}{
  2677. \begin{array}{lcl}
  2678. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2679. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2680. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2681. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2682. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2683. \end{array}
  2684. }
  2685. {\if\edition\racketEd
  2686. \subsection{The \LangCVar{} Intermediate Language}
  2687. The output of \code{explicate\_control} is similar to the $C$
  2688. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2689. categories for expressions and statements, so we name it \LangCVar{}.
  2690. This style of intermediate language is also known as
  2691. \emph{three-address code}, to emphasize that the typical form of a
  2692. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2693. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2694. The concrete syntax for \LangCVar{} is defined in
  2695. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2696. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2697. %
  2698. The \LangCVar{} language supports the same operators as \LangVar{} but
  2699. the arguments of operators are restricted to atomic
  2700. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2701. assignment statements which can be executed in sequence using the
  2702. \key{Seq} form. A sequence of statements always ends with
  2703. \key{Return}, a guarantee that is baked into the grammar rules for
  2704. \itm{tail}. The naming of this non-terminal comes from the term
  2705. \emph{tail position}\index{subject}{tail position}, which refers to an
  2706. expression that is the last one to execute within a function or
  2707. program.
  2708. A \LangCVar{} program consists of an alist mapping labels to
  2709. tails. This is more general than necessary for the present chapter, as
  2710. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2711. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2712. there will be just one label, \key{start}, and the whole program is
  2713. its tail.
  2714. %
  2715. The $\itm{info}$ field of the \key{CProgram} form, after the
  2716. \code{explicate\_control} pass, contains a mapping from the symbol
  2717. \key{locals} to a list of variables, that is, a list of all the
  2718. variables used in the program. At the start of the program, these
  2719. variables are uninitialized; they become initialized on their first
  2720. assignment.
  2721. \begin{figure}[tbp]
  2722. \begin{tcolorbox}[colback=white]
  2723. \[
  2724. \begin{array}{l}
  2725. \CvarGrammarRacket \\
  2726. \begin{array}{lcl}
  2727. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2728. \end{array}
  2729. \end{array}
  2730. \]
  2731. \end{tcolorbox}
  2732. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2733. \label{fig:c0-concrete-syntax}
  2734. \end{figure}
  2735. \begin{figure}[tbp]
  2736. \begin{tcolorbox}[colback=white]
  2737. \[
  2738. \begin{array}{l}
  2739. \CvarASTRacket \\
  2740. \begin{array}{lcl}
  2741. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2742. \end{array}
  2743. \end{array}
  2744. \]
  2745. \end{tcolorbox}
  2746. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2747. \label{fig:c0-syntax}
  2748. \end{figure}
  2749. The definitional interpreter for \LangCVar{} is in the support code,
  2750. in the file \code{interp-Cvar.rkt}.
  2751. \fi}
  2752. {\if\edition\racketEd
  2753. \section{Uniquify Variables}
  2754. \label{sec:uniquify-Lvar}
  2755. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2756. programs in which every \key{let} binds a unique variable name. For
  2757. example, the \code{uniquify} pass should translate the program on the
  2758. left into the program on the right.
  2759. \begin{transformation}
  2760. \begin{lstlisting}
  2761. (let ([x 32])
  2762. (+ (let ([x 10]) x) x))
  2763. \end{lstlisting}
  2764. \compilesto
  2765. \begin{lstlisting}
  2766. (let ([x.1 32])
  2767. (+ (let ([x.2 10]) x.2) x.1))
  2768. \end{lstlisting}
  2769. \end{transformation}
  2770. The following is another example translation, this time of a program
  2771. with a \key{let} nested inside the initializing expression of another
  2772. \key{let}.
  2773. \begin{transformation}
  2774. \begin{lstlisting}
  2775. (let ([x (let ([x 4])
  2776. (+ x 1))])
  2777. (+ x 2))
  2778. \end{lstlisting}
  2779. \compilesto
  2780. \begin{lstlisting}
  2781. (let ([x.2 (let ([x.1 4])
  2782. (+ x.1 1))])
  2783. (+ x.2 2))
  2784. \end{lstlisting}
  2785. \end{transformation}
  2786. We recommend implementing \code{uniquify} by creating a structurally
  2787. recursive function named \code{uniquify\_exp} that mostly just copies
  2788. an expression. However, when encountering a \key{let}, it should
  2789. generate a unique name for the variable and associate the old name
  2790. with the new name in an alist.\footnote{The Racket function
  2791. \code{gensym} is handy for generating unique variable names.} The
  2792. \code{uniquify\_exp} function needs to access this alist when it gets
  2793. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2794. for the alist.
  2795. The skeleton of the \code{uniquify\_exp} function is shown in
  2796. Figure~\ref{fig:uniquify-Lvar}.
  2797. %% The function is curried so that it is
  2798. %% convenient to partially apply it to an alist and then apply it to
  2799. %% different expressions, as in the last case for primitive operations in
  2800. %% Figure~\ref{fig:uniquify-Lvar}.
  2801. The
  2802. %
  2803. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2804. %
  2805. form of Racket is useful for transforming the element of a list to
  2806. produce a new list.\index{subject}{for/list}
  2807. \begin{figure}[tbp]
  2808. \begin{tcolorbox}[colback=white]
  2809. \begin{lstlisting}
  2810. (define (uniquify_exp env)
  2811. (lambda (e)
  2812. (match e
  2813. [(Var x) ___]
  2814. [(Int n) (Int n)]
  2815. [(Let x e body) ___]
  2816. [(Prim op es)
  2817. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2818. (define (uniquify p)
  2819. (match p
  2820. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2821. \end{lstlisting}
  2822. \end{tcolorbox}
  2823. \caption{Skeleton for the \key{uniquify} pass.}
  2824. \label{fig:uniquify-Lvar}
  2825. \end{figure}
  2826. \begin{exercise}
  2827. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2828. Complete the \code{uniquify} pass by filling in the blanks in
  2829. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2830. variables and for the \key{let} form in the file \code{compiler.rkt}
  2831. in the support code.
  2832. \end{exercise}
  2833. \begin{exercise}
  2834. \normalfont\normalsize
  2835. \label{ex:Lvar}
  2836. Create five \LangVar{} programs that exercise the most interesting
  2837. parts of the \key{uniquify} pass, that is, the programs should include
  2838. \key{let} forms, variables, and variables that shadow each other.
  2839. The five programs should be placed in the subdirectory named
  2840. \key{tests} and the file names should start with \code{var\_test\_}
  2841. followed by a unique integer and end with the file extension
  2842. \key{.rkt}.
  2843. %
  2844. The \key{run-tests.rkt} script in the support code checks whether the
  2845. output programs produce the same result as the input programs. The
  2846. script uses the \key{interp-tests} function
  2847. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2848. your \key{uniquify} pass on the example programs. The \code{passes}
  2849. parameter of \key{interp-tests} is a list that should have one entry
  2850. for each pass in your compiler. For now, define \code{passes} to
  2851. contain just one entry for \code{uniquify} as shown below.
  2852. \begin{lstlisting}
  2853. (define passes
  2854. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2855. \end{lstlisting}
  2856. Run the \key{run-tests.rkt} script in the support code to check
  2857. whether the output programs produce the same result as the input
  2858. programs.
  2859. \end{exercise}
  2860. \fi}
  2861. \section{Remove Complex Operands}
  2862. \label{sec:remove-complex-opera-Lvar}
  2863. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2864. into a restricted form in which the arguments of operations are atomic
  2865. expressions. Put another way, this pass removes complex
  2866. operands\index{subject}{complex operand}, such as the expression
  2867. \racket{\code{(- 10)}}\python{\code{-10}}
  2868. in the program below. This is accomplished by introducing a new
  2869. temporary variable, assigning the complex operand to the new
  2870. variable, and then using the new variable in place of the complex
  2871. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2872. right.
  2873. {\if\edition\racketEd
  2874. \begin{transformation}
  2875. % var_test_19.rkt
  2876. \begin{lstlisting}
  2877. (let ([x (+ 42 (- 10))])
  2878. (+ x 10))
  2879. \end{lstlisting}
  2880. \compilesto
  2881. \begin{lstlisting}
  2882. (let ([x (let ([tmp.1 (- 10)])
  2883. (+ 42 tmp.1))])
  2884. (+ x 10))
  2885. \end{lstlisting}
  2886. \end{transformation}
  2887. \fi}
  2888. {\if\edition\pythonEd
  2889. \begin{transformation}
  2890. \begin{lstlisting}
  2891. x = 42 + -10
  2892. print(x + 10)
  2893. \end{lstlisting}
  2894. \compilesto
  2895. \begin{lstlisting}
  2896. tmp_0 = -10
  2897. x = 42 + tmp_0
  2898. tmp_1 = x + 10
  2899. print(tmp_1)
  2900. \end{lstlisting}
  2901. \end{transformation}
  2902. \fi}
  2903. \newcommand{\LvarMonadASTRacket}{
  2904. \begin{array}{rcl}
  2905. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2906. \Exp &::=& \Atm \MID \READ{} \\
  2907. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2908. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2909. \end{array}
  2910. }
  2911. \newcommand{\LvarMonadASTPython}{
  2912. \begin{array}{rcl}
  2913. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2914. \Exp{} &::=& \Atm \MID \READ{} \\
  2915. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2916. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2917. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2918. \end{array}
  2919. }
  2920. \begin{figure}[tp]
  2921. \centering
  2922. \begin{tcolorbox}[colback=white]
  2923. {\if\edition\racketEd
  2924. \[
  2925. \begin{array}{l}
  2926. \LvarMonadASTRacket \\
  2927. \begin{array}{rcl}
  2928. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2929. \end{array}
  2930. \end{array}
  2931. \]
  2932. \fi}
  2933. {\if\edition\pythonEd
  2934. \[
  2935. \begin{array}{l}
  2936. \LvarMonadASTPython \\
  2937. \begin{array}{rcl}
  2938. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2939. \end{array}
  2940. \end{array}
  2941. \]
  2942. \fi}
  2943. \end{tcolorbox}
  2944. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2945. atomic expressions.}
  2946. \label{fig:Lvar-anf-syntax}
  2947. \end{figure}
  2948. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2949. of this pass, the language \LangVarANF{}. The only difference is that
  2950. operator arguments are restricted to be atomic expressions that are
  2951. defined by the \Atm{} non-terminal. In particular, integer constants
  2952. and variables are atomic.
  2953. The atomic expressions are pure (they do not cause or depend on
  2954. side-effects) whereas complex expressions may have side effects, such
  2955. as \READ{}. A language with this separation between pure versus
  2956. side-effecting expressions is said to be in monadic normal
  2957. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2958. in the name \LangVarANF{}. An important invariant of the
  2959. \code{remove\_complex\_operands} pass is that the relative ordering
  2960. among complex expressions is not changed, but the relative ordering
  2961. between atomic expressions and complex expressions can change and
  2962. often does. The reason that these changes are behavior preserving is
  2963. that the atomic expressions are pure.
  2964. Another well-known form for intermediate languages is the
  2965. \emph{administrative normal form}
  2966. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2967. \index{subject}{administrative normal form} \index{subject}{ANF}
  2968. %
  2969. The \LangVarANF{} language is not quite in ANF because we allow the
  2970. right-hand side of a \code{let} to be a complex expression.
  2971. {\if\edition\racketEd
  2972. We recommend implementing this pass with two mutually recursive
  2973. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2974. \code{rco\_atom} to subexpressions that need to become atomic and to
  2975. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2976. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2977. returns an expression. The \code{rco\_atom} function returns two
  2978. things: an atomic expression and an alist mapping temporary variables to
  2979. complex subexpressions. You can return multiple things from a function
  2980. using Racket's \key{values} form and you can receive multiple things
  2981. from a function call using the \key{define-values} form.
  2982. \fi}
  2983. %
  2984. {\if\edition\pythonEd
  2985. %
  2986. We recommend implementing this pass with an auxiliary method named
  2987. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2988. Boolean that specifies whether the expression needs to become atomic
  2989. or not. The \code{rco\_exp} method should return a pair consisting of
  2990. the new expression and a list of pairs, associating new temporary
  2991. variables with their initializing expressions.
  2992. %
  2993. \fi}
  2994. {\if\edition\racketEd
  2995. %
  2996. Returning to the example program with the expression \code{(+ 42 (-
  2997. 10))}, the subexpression \code{(- 10)} should be processed using the
  2998. \code{rco\_atom} function because it is an argument of the \code{+}
  2999. operator and therefore needs to become atomic. The output of
  3000. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  3001. \begin{transformation}
  3002. \begin{lstlisting}
  3003. (- 10)
  3004. \end{lstlisting}
  3005. \compilesto
  3006. \begin{lstlisting}
  3007. tmp.1
  3008. ((tmp.1 . (- 10)))
  3009. \end{lstlisting}
  3010. \end{transformation}
  3011. \fi}
  3012. %
  3013. {\if\edition\pythonEd
  3014. %
  3015. Returning to the example program with the expression \code{42 + -10},
  3016. the subexpression \code{-10} should be processed using the
  3017. \code{rco\_exp} function with \code{True} as the second argument
  3018. because \code{-10} is an argument of the \code{+} operator and
  3019. therefore needs to become atomic. The output of \code{rco\_exp}
  3020. applied to \code{-10} is as follows.
  3021. \begin{transformation}
  3022. \begin{lstlisting}
  3023. -10
  3024. \end{lstlisting}
  3025. \compilesto
  3026. \begin{lstlisting}
  3027. tmp_1
  3028. [(tmp_1, -10)]
  3029. \end{lstlisting}
  3030. \end{transformation}
  3031. %
  3032. \fi}
  3033. Take special care of programs such as the following that
  3034. %
  3035. \racket{bind a variable to an atomic expression.}
  3036. %
  3037. \python{assign an atomic expression to a variable.}
  3038. %
  3039. You should leave such \racket{variable bindings}\python{assignments}
  3040. unchanged, as shown in the program on the right\\
  3041. %
  3042. {\if\edition\racketEd
  3043. \begin{transformation}
  3044. % var_test_20.rkt
  3045. \begin{lstlisting}
  3046. (let ([a 42])
  3047. (let ([b a])
  3048. b))
  3049. \end{lstlisting}
  3050. \compilesto
  3051. \begin{lstlisting}
  3052. (let ([a 42])
  3053. (let ([b a])
  3054. b))
  3055. \end{lstlisting}
  3056. \end{transformation}
  3057. \fi}
  3058. {\if\edition\pythonEd
  3059. \begin{transformation}
  3060. \begin{lstlisting}
  3061. a = 42
  3062. b = a
  3063. print(b)
  3064. \end{lstlisting}
  3065. \compilesto
  3066. \begin{lstlisting}
  3067. a = 42
  3068. b = a
  3069. print(b)
  3070. \end{lstlisting}
  3071. \end{transformation}
  3072. \fi}
  3073. %
  3074. \noindent A careless implementation might produce the following output with
  3075. unnecessary temporary variables.
  3076. \begin{center}
  3077. \begin{minipage}{0.4\textwidth}
  3078. {\if\edition\racketEd
  3079. \begin{lstlisting}
  3080. (let ([tmp.1 42])
  3081. (let ([a tmp.1])
  3082. (let ([tmp.2 a])
  3083. (let ([b tmp.2])
  3084. b))))
  3085. \end{lstlisting}
  3086. \fi}
  3087. {\if\edition\pythonEd
  3088. \begin{lstlisting}
  3089. tmp_1 = 42
  3090. a = tmp_1
  3091. tmp_2 = a
  3092. b = tmp_2
  3093. print(b)
  3094. \end{lstlisting}
  3095. \fi}
  3096. \end{minipage}
  3097. \end{center}
  3098. \begin{exercise}
  3099. \normalfont\normalsize
  3100. {\if\edition\racketEd
  3101. Implement the \code{remove\_complex\_operands} function in
  3102. \code{compiler.rkt}.
  3103. %
  3104. Create three new \LangVar{} programs that exercise the interesting
  3105. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3106. regarding file names described in Exercise~\ref{ex:Lvar}.
  3107. %
  3108. In the \code{run-tests.rkt} script, add the following entry to the
  3109. list of \code{passes} and then run the script to test your compiler.
  3110. \begin{lstlisting}
  3111. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3112. \end{lstlisting}
  3113. While debugging your compiler, it is often useful to see the
  3114. intermediate programs that are output from each pass. To print the
  3115. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3116. \code{interp-tests} in \code{run-tests.rkt}.
  3117. \fi}
  3118. %
  3119. {\if\edition\pythonEd
  3120. Implement the \code{remove\_complex\_operands} pass in
  3121. \code{compiler.py}, creating auxiliary functions for each
  3122. non-terminal in the grammar, i.e., \code{rco\_exp}
  3123. and \code{rco\_stmt}. We recommend you use the function
  3124. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3125. \fi}
  3126. \end{exercise}
  3127. {\if\edition\pythonEd
  3128. \begin{exercise}
  3129. \normalfont\normalsize
  3130. \label{ex:Lvar}
  3131. Create five \LangVar{} programs that exercise the most interesting
  3132. parts of the \code{remove\_complex\_operands} pass. The five programs
  3133. should be placed in the subdirectory named \key{tests} and the file
  3134. names should start with \code{var\_test\_} followed by a unique
  3135. integer and end with the file extension \key{.py}.
  3136. %% The \key{run-tests.rkt} script in the support code checks whether the
  3137. %% output programs produce the same result as the input programs. The
  3138. %% script uses the \key{interp-tests} function
  3139. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3140. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3141. %% parameter of \key{interp-tests} is a list that should have one entry
  3142. %% for each pass in your compiler. For now, define \code{passes} to
  3143. %% contain just one entry for \code{uniquify} as shown below.
  3144. %% \begin{lstlisting}
  3145. %% (define passes
  3146. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3147. %% \end{lstlisting}
  3148. Run the \key{run-tests.py} script in the support code to check
  3149. whether the output programs produce the same result as the input
  3150. programs.
  3151. \end{exercise}
  3152. \fi}
  3153. {\if\edition\racketEd
  3154. \section{Explicate Control}
  3155. \label{sec:explicate-control-Lvar}
  3156. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3157. programs that make the order of execution explicit in their
  3158. syntax. For now this amounts to flattening \key{let} constructs into a
  3159. sequence of assignment statements. For example, consider the following
  3160. \LangVar{} program.\\
  3161. % var_test_11.rkt
  3162. \begin{minipage}{0.96\textwidth}
  3163. \begin{lstlisting}
  3164. (let ([y (let ([x 20])
  3165. (+ x (let ([x 22]) x)))])
  3166. y)
  3167. \end{lstlisting}
  3168. \end{minipage}\\
  3169. %
  3170. The output of the previous pass is shown below, on the left, and the
  3171. output of \code{explicate\_control} is on the right. Recall that the
  3172. right-hand-side of a \key{let} executes before its body, so the order
  3173. of evaluation for this program is to assign \code{20} to \code{x.1},
  3174. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3175. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3176. this ordering explicit.
  3177. \begin{transformation}
  3178. \begin{lstlisting}
  3179. (let ([y (let ([x.1 20])
  3180. (let ([x.2 22])
  3181. (+ x.1 x.2)))])
  3182. y)
  3183. \end{lstlisting}
  3184. \compilesto
  3185. \begin{lstlisting}[language=C]
  3186. start:
  3187. x.1 = 20;
  3188. x.2 = 22;
  3189. y = (+ x.1 x.2);
  3190. return y;
  3191. \end{lstlisting}
  3192. \end{transformation}
  3193. \begin{figure}[tbp]
  3194. \begin{tcolorbox}[colback=white]
  3195. \begin{lstlisting}
  3196. (define (explicate_tail e)
  3197. (match e
  3198. [(Var x) ___]
  3199. [(Int n) (Return (Int n))]
  3200. [(Let x rhs body) ___]
  3201. [(Prim op es) ___]
  3202. [else (error "explicate_tail unhandled case" e)]))
  3203. (define (explicate_assign e x cont)
  3204. (match e
  3205. [(Var x) ___]
  3206. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3207. [(Let y rhs body) ___]
  3208. [(Prim op es) ___]
  3209. [else (error "explicate_assign unhandled case" e)]))
  3210. (define (explicate_control p)
  3211. (match p
  3212. [(Program info body) ___]))
  3213. \end{lstlisting}
  3214. \end{tcolorbox}
  3215. \caption{Skeleton for the \code{explicate\_control} pass.}
  3216. \label{fig:explicate-control-Lvar}
  3217. \end{figure}
  3218. The organization of this pass depends on the notion of tail position
  3219. that we have alluded to earlier. Here is the definition.
  3220. \begin{definition}
  3221. The following rules define when an expression is in \textbf{\emph{tail
  3222. position}}\index{subject}{tail position} for the language \LangVar{}.
  3223. \begin{enumerate}
  3224. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3225. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3226. \end{enumerate}
  3227. \end{definition}
  3228. We recommend implementing \code{explicate\_control} using two
  3229. recursive functions, \code{explicate\_tail} and
  3230. \code{explicate\_assign}, as suggested in the skeleton code in
  3231. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3232. function should be applied to expressions in tail position whereas the
  3233. \code{explicate\_assign} should be applied to expressions that occur on
  3234. the right-hand-side of a \key{let}.
  3235. %
  3236. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3237. input and produces a \Tail{} in \LangCVar{} (see
  3238. Figure~\ref{fig:c0-syntax}).
  3239. %
  3240. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3241. the variable that it is to be assigned to, and a \Tail{} in
  3242. \LangCVar{} for the code that comes after the assignment. The
  3243. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3244. The \code{explicate\_assign} function is in accumulator-passing style:
  3245. the \code{cont} parameter is used for accumulating the output. This
  3246. accumulator-passing style plays an important role in how we generate
  3247. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3248. The abbreviation \code{cont} is for continuation because it contains
  3249. the generated code that should come after the current assignment.
  3250. This code organization is also related to continuation-passing style,
  3251. except that \code{cont} is not what happens next during compilation,
  3252. but what happens next in the generated code.
  3253. \begin{exercise}\normalfont\normalsize
  3254. %
  3255. Implement the \code{explicate\_control} function in
  3256. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3257. exercise the code in \code{explicate\_control}.
  3258. %
  3259. In the \code{run-tests.rkt} script, add the following entry to the
  3260. list of \code{passes} and then run the script to test your compiler.
  3261. \begin{lstlisting}
  3262. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3263. \end{lstlisting}
  3264. \end{exercise}
  3265. \fi}
  3266. \section{Select Instructions}
  3267. \label{sec:select-Lvar}
  3268. \index{subject}{instruction selection}
  3269. In the \code{select\_instructions} pass we begin the work of
  3270. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3271. language of this pass is a variant of x86 that still uses variables,
  3272. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3273. non-terminal of the \LangXInt{} abstract syntax
  3274. (Figure~\ref{fig:x86-int-ast}).
  3275. \racket{We recommend implementing the
  3276. \code{select\_instructions} with three auxiliary functions, one for
  3277. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3278. $\Tail$.}
  3279. \python{We recommend implementing an auxiliary function
  3280. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3281. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3282. same and integer constants change to immediates, that is, $\INT{n}$
  3283. changes to $\IMM{n}$.}
  3284. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3285. arithmetic operations. For example, consider the addition operation
  3286. below, on the left side. There is an \key{addq} instruction in x86,
  3287. but it performs an in-place update. So we could move $\Arg_1$
  3288. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3289. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3290. $\Atm_1$ and $\Atm_2$ respectively.
  3291. \begin{transformation}
  3292. {\if\edition\racketEd
  3293. \begin{lstlisting}
  3294. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3295. \end{lstlisting}
  3296. \fi}
  3297. {\if\edition\pythonEd
  3298. \begin{lstlisting}
  3299. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3300. \end{lstlisting}
  3301. \fi}
  3302. \compilesto
  3303. \begin{lstlisting}
  3304. movq |$\Arg_1$|, |$\itm{var}$|
  3305. addq |$\Arg_2$|, |$\itm{var}$|
  3306. \end{lstlisting}
  3307. \end{transformation}
  3308. There are also cases that require special care to avoid generating
  3309. needlessly complicated code. For example, if one of the arguments of
  3310. the addition is the same variable as the left-hand side of the
  3311. assignment, as shown below, then there is no need for the extra move
  3312. instruction. The assignment statement can be translated into a single
  3313. \key{addq} instruction as follows.
  3314. \begin{transformation}
  3315. {\if\edition\racketEd
  3316. \begin{lstlisting}
  3317. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3318. \end{lstlisting}
  3319. \fi}
  3320. {\if\edition\pythonEd
  3321. \begin{lstlisting}
  3322. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3323. \end{lstlisting}
  3324. \fi}
  3325. \compilesto
  3326. \begin{lstlisting}
  3327. addq |$\Arg_1$|, |$\itm{var}$|
  3328. \end{lstlisting}
  3329. \end{transformation}
  3330. The \READOP{} operation does not have a direct counterpart in x86
  3331. assembly, so we provide this functionality with the function
  3332. \code{read\_int} in the file \code{runtime.c}, written in
  3333. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3334. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3335. system}, or simply the \emph{runtime} for short. When compiling your
  3336. generated x86 assembly code, you need to compile \code{runtime.c} to
  3337. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3338. \code{-c}) and link it into the executable. For our purposes of code
  3339. generation, all you need to do is translate an assignment of
  3340. \READOP{} into a call to the \code{read\_int} function followed by a
  3341. move from \code{rax} to the left-hand-side variable. (Recall that the
  3342. return value of a function goes into \code{rax}.)
  3343. \begin{transformation}
  3344. {\if\edition\racketEd
  3345. \begin{lstlisting}
  3346. |$\itm{var}$| = (read);
  3347. \end{lstlisting}
  3348. \fi}
  3349. {\if\edition\pythonEd
  3350. \begin{lstlisting}
  3351. |$\itm{var}$| = input_int();
  3352. \end{lstlisting}
  3353. \fi}
  3354. \compilesto
  3355. \begin{lstlisting}
  3356. callq read_int
  3357. movq %rax, |$\itm{var}$|
  3358. \end{lstlisting}
  3359. \end{transformation}
  3360. {\if\edition\pythonEd
  3361. %
  3362. Similarly, we translate the \code{print} operation, shown below, into
  3363. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3364. In x86, the first six arguments to functions are passed in registers,
  3365. with the first argument passed in register \code{rdi}. So we move the
  3366. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3367. \code{callq} instruction.
  3368. \begin{transformation}
  3369. \begin{lstlisting}
  3370. print(|$\Atm$|)
  3371. \end{lstlisting}
  3372. \compilesto
  3373. \begin{lstlisting}
  3374. movq |$\Arg$|, %rdi
  3375. callq print_int
  3376. \end{lstlisting}
  3377. \end{transformation}
  3378. %
  3379. \fi}
  3380. {\if\edition\racketEd
  3381. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3382. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3383. assignment to the \key{rax} register followed by a jump to the
  3384. conclusion of the program (so the conclusion needs to be labeled).
  3385. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3386. recursively and then append the resulting instructions.
  3387. \fi}
  3388. {\if\edition\pythonEd
  3389. We recommend that you use the function \code{utils.label\_name()} to
  3390. transform a string into an label argument suitably suitable for, e.g.,
  3391. the target of the \code{callq} instruction. This practice makes your
  3392. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3393. all labels.
  3394. \fi}
  3395. \begin{exercise}
  3396. \normalfont\normalsize
  3397. {\if\edition\racketEd
  3398. Implement the \code{select\_instructions} pass in
  3399. \code{compiler.rkt}. Create three new example programs that are
  3400. designed to exercise all of the interesting cases in this pass.
  3401. %
  3402. In the \code{run-tests.rkt} script, add the following entry to the
  3403. list of \code{passes} and then run the script to test your compiler.
  3404. \begin{lstlisting}
  3405. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3406. \end{lstlisting}
  3407. \fi}
  3408. {\if\edition\pythonEd
  3409. Implement the \key{select\_instructions} pass in
  3410. \code{compiler.py}. Create three new example programs that are
  3411. designed to exercise all of the interesting cases in this pass.
  3412. Run the \code{run-tests.py} script to to check
  3413. whether the output programs produce the same result as the input
  3414. programs.
  3415. \fi}
  3416. \end{exercise}
  3417. \section{Assign Homes}
  3418. \label{sec:assign-Lvar}
  3419. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3420. \LangXVar{} programs that no longer use program variables.
  3421. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3422. the program variables in registers or on the stack. For runtime
  3423. efficiency, it is better to place variables in registers, but as there
  3424. are only 16 registers, some programs must necessarily resort to
  3425. placing some variables on the stack. In this chapter we focus on the
  3426. mechanics of placing variables on the stack. We study an algorithm for
  3427. placing variables in registers in
  3428. Chapter~\ref{ch:register-allocation-Lvar}.
  3429. Consider again the following \LangVar{} program from
  3430. Section~\ref{sec:remove-complex-opera-Lvar}.
  3431. % var_test_20.rkt
  3432. {\if\edition\racketEd
  3433. \begin{lstlisting}
  3434. (let ([a 42])
  3435. (let ([b a])
  3436. b))
  3437. \end{lstlisting}
  3438. \fi}
  3439. {\if\edition\pythonEd
  3440. \begin{lstlisting}
  3441. a = 42
  3442. b = a
  3443. print(b)
  3444. \end{lstlisting}
  3445. \fi}
  3446. %
  3447. The output of \code{select\_instructions} is shown below, on the left,
  3448. and the output of \code{assign\_homes} is on the right. In this
  3449. example, we assign variable \code{a} to stack location
  3450. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3451. \begin{transformation}
  3452. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3453. movq $42, a
  3454. movq a, b
  3455. movq b, %rax
  3456. \end{lstlisting}
  3457. \compilesto
  3458. %stack-space: 16
  3459. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3460. movq $42, -8(%rbp)
  3461. movq -8(%rbp), -16(%rbp)
  3462. movq -16(%rbp), %rax
  3463. \end{lstlisting}
  3464. \end{transformation}
  3465. \racket{
  3466. The \code{assign\_homes} pass should replace all variables
  3467. with stack locations.
  3468. The list of variables can be obtain from
  3469. the \code{locals-types} entry in the $\itm{info}$ of the
  3470. \code{X86Program} node. The \code{locals-types} entry is an alist
  3471. mapping all the variables in the program to their types
  3472. (for now just \code{Integer}).
  3473. As an aside, the \code{locals-types} entry is
  3474. computed by \code{type-check-Cvar} in the support code, which
  3475. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3476. which you should propagate to the \code{X86Program} node.}
  3477. %
  3478. \python{The \code{assign\_homes} pass should replace all uses of
  3479. variables with stack locations.}
  3480. %
  3481. In the process of assigning variables to stack locations, it is
  3482. convenient for you to compute and store the size of the frame (in
  3483. bytes) in
  3484. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3485. %
  3486. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3487. %
  3488. which is needed later to generate the conclusion of the \code{main}
  3489. procedure. The x86-64 standard requires the frame size to be a
  3490. multiple of 16 bytes.\index{subject}{frame}
  3491. % TODO: store the number of variables instead? -Jeremy
  3492. \begin{exercise}\normalfont\normalsize
  3493. Implement the \code{assign\_homes} pass in
  3494. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3495. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3496. grammar. We recommend that the auxiliary functions take an extra
  3497. parameter that maps variable names to homes (stack locations for now).
  3498. %
  3499. {\if\edition\racketEd
  3500. In the \code{run-tests.rkt} script, add the following entry to the
  3501. list of \code{passes} and then run the script to test your compiler.
  3502. \begin{lstlisting}
  3503. (list "assign homes" assign-homes interp_x86-0)
  3504. \end{lstlisting}
  3505. \fi}
  3506. {\if\edition\pythonEd
  3507. Run the \code{run-tests.py} script to to check
  3508. whether the output programs produce the same result as the input
  3509. programs.
  3510. \fi}
  3511. \end{exercise}
  3512. \section{Patch Instructions}
  3513. \label{sec:patch-s0}
  3514. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3515. \LangXInt{} by making sure that each instruction adheres to the
  3516. restriction that at most one argument of an instruction may be a
  3517. memory reference.
  3518. We return to the following example.\\
  3519. \begin{minipage}{0.5\textwidth}
  3520. % var_test_20.rkt
  3521. {\if\edition\racketEd
  3522. \begin{lstlisting}
  3523. (let ([a 42])
  3524. (let ([b a])
  3525. b))
  3526. \end{lstlisting}
  3527. \fi}
  3528. {\if\edition\pythonEd
  3529. \begin{lstlisting}
  3530. a = 42
  3531. b = a
  3532. print(b)
  3533. \end{lstlisting}
  3534. \fi}
  3535. \end{minipage}\\
  3536. The \code{assign\_homes} pass produces the following translation. \\
  3537. \begin{minipage}{0.5\textwidth}
  3538. {\if\edition\racketEd
  3539. \begin{lstlisting}
  3540. movq $42, -8(%rbp)
  3541. movq -8(%rbp), -16(%rbp)
  3542. movq -16(%rbp), %rax
  3543. \end{lstlisting}
  3544. \fi}
  3545. {\if\edition\pythonEd
  3546. \begin{lstlisting}
  3547. movq 42, -8(%rbp)
  3548. movq -8(%rbp), -16(%rbp)
  3549. movq -16(%rbp), %rdi
  3550. callq print_int
  3551. \end{lstlisting}
  3552. \fi}
  3553. \end{minipage}\\
  3554. The second \key{movq} instruction is problematic because both
  3555. arguments are stack locations. We suggest fixing this problem by
  3556. moving from the source location to the register \key{rax} and then
  3557. from \key{rax} to the destination location, as follows.
  3558. \begin{lstlisting}
  3559. movq -8(%rbp), %rax
  3560. movq %rax, -16(%rbp)
  3561. \end{lstlisting}
  3562. \begin{exercise}
  3563. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3564. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3565. Create three new example programs that are
  3566. designed to exercise all of the interesting cases in this pass.
  3567. %
  3568. {\if\edition\racketEd
  3569. In the \code{run-tests.rkt} script, add the following entry to the
  3570. list of \code{passes} and then run the script to test your compiler.
  3571. \begin{lstlisting}
  3572. (list "patch instructions" patch_instructions interp_x86-0)
  3573. \end{lstlisting}
  3574. \fi}
  3575. {\if\edition\pythonEd
  3576. Run the \code{run-tests.py} script to to check
  3577. whether the output programs produce the same result as the input
  3578. programs.
  3579. \fi}
  3580. \end{exercise}
  3581. \section{Generate Prelude and Conclusion}
  3582. \label{sec:print-x86}
  3583. \index{subject}{prelude}\index{subject}{conclusion}
  3584. The last step of the compiler from \LangVar{} to x86 is to generate
  3585. the \code{main} function with a prelude and conclusion wrapped around
  3586. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3587. discussed in Section~\ref{sec:x86}.
  3588. When running on Mac OS X, your compiler should prefix an underscore to
  3589. all labels, e.g., changing \key{main} to \key{\_main}.
  3590. %
  3591. \racket{The Racket call \code{(system-type 'os)} is useful for
  3592. determining which operating system the compiler is running on. It
  3593. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3594. %
  3595. \python{The Python \code{platform} library includes a \code{system()}
  3596. function that returns \code{'Linux'}, \code{'Windows'}, or
  3597. \code{'Darwin'} (for Mac).}
  3598. \begin{exercise}\normalfont\normalsize
  3599. %
  3600. Implement the \key{prelude\_and\_conclusion} pass in
  3601. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3602. %
  3603. {\if\edition\racketEd
  3604. In the \code{run-tests.rkt} script, add the following entry to the
  3605. list of \code{passes} and then run the script to test your compiler.
  3606. \begin{lstlisting}
  3607. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3608. \end{lstlisting}
  3609. %
  3610. Uncomment the call to the \key{compiler-tests} function
  3611. (Appendix~\ref{appendix:utilities}), which tests your complete
  3612. compiler by executing the generated x86 code. It translates the x86
  3613. AST that you produce into a string by invoking the \code{print-x86}
  3614. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3615. the provided \key{runtime.c} file to \key{runtime.o} using
  3616. \key{gcc}. Run the script to test your compiler.
  3617. %
  3618. \fi}
  3619. {\if\edition\pythonEd
  3620. %
  3621. Run the \code{run-tests.py} script to to check whether the output
  3622. programs produce the same result as the input programs. That script
  3623. translates the x86 AST that you produce into a string by invoking the
  3624. \code{repr} method that is implemented by the x86 AST classes in
  3625. \code{x86\_ast.py}.
  3626. %
  3627. \fi}
  3628. \end{exercise}
  3629. \section{Challenge: Partial Evaluator for \LangVar{}}
  3630. \label{sec:pe-Lvar}
  3631. \index{subject}{partial evaluation}
  3632. This section describes two optional challenge exercises that involve
  3633. adapting and improving the partial evaluator for \LangInt{} that was
  3634. introduced in Section~\ref{sec:partial-evaluation}.
  3635. \begin{exercise}\label{ex:pe-Lvar}
  3636. \normalfont\normalsize
  3637. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3638. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3639. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3640. %
  3641. \racket{\key{let} binding}\python{assignment}
  3642. %
  3643. to the \LangInt{} language, so you will need to add cases for them in
  3644. the \code{pe\_exp}
  3645. %
  3646. \racket{function.}
  3647. %
  3648. \python{and \code{pe\_stmt} functions.}
  3649. %
  3650. Once complete, add the partial evaluation pass to the front of your
  3651. compiler and make sure that your compiler still passes all of the
  3652. tests.
  3653. \end{exercise}
  3654. \begin{exercise}
  3655. \normalfont\normalsize
  3656. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3657. \code{pe\_add} auxiliary functions with functions that know more about
  3658. arithmetic. For example, your partial evaluator should translate
  3659. {\if\edition\racketEd
  3660. \[
  3661. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3662. \code{(+ 2 (read))}
  3663. \]
  3664. \fi}
  3665. {\if\edition\pythonEd
  3666. \[
  3667. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3668. \code{2 + input\_int()}
  3669. \]
  3670. \fi}
  3671. To accomplish this, the \code{pe\_exp} function should produce output
  3672. in the form of the $\itm{residual}$ non-terminal of the following
  3673. grammar. The idea is that when processing an addition expression, we
  3674. can always produce either 1) an integer constant, 2) an addition
  3675. expression with an integer constant on the left-hand side but not the
  3676. right-hand side, or 3) or an addition expression in which neither
  3677. subexpression is a constant.
  3678. {\if\edition\racketEd
  3679. \[
  3680. \begin{array}{lcl}
  3681. \itm{inert} &::=& \Var
  3682. \MID \LP\key{read}\RP
  3683. \MID \LP\key{-} ~\Var\RP
  3684. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3685. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3686. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3687. \itm{residual} &::=& \Int
  3688. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3689. \MID \itm{inert}
  3690. \end{array}
  3691. \]
  3692. \fi}
  3693. {\if\edition\pythonEd
  3694. \[
  3695. \begin{array}{lcl}
  3696. \itm{inert} &::=& \Var
  3697. \MID \key{input\_int}\LP\RP
  3698. \MID \key{-} \Var
  3699. \MID \key{-} \key{input\_int}\LP\RP
  3700. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3701. \itm{residual} &::=& \Int
  3702. \MID \Int ~ \key{+} ~ \itm{inert}
  3703. \MID \itm{inert}
  3704. \end{array}
  3705. \]
  3706. \fi}
  3707. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3708. inputs are $\itm{residual}$ expressions and they should return
  3709. $\itm{residual}$ expressions. Once the improvements are complete,
  3710. make sure that your compiler still passes all of the tests. After
  3711. all, fast code is useless if it produces incorrect results!
  3712. \end{exercise}
  3713. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3714. \chapter{Register Allocation}
  3715. \label{ch:register-allocation-Lvar}
  3716. \index{subject}{register allocation}
  3717. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3718. variables on the procedure call stack. It can take 10s to 100s of
  3719. cycles for the CPU to access locations on the stack whereas accessing
  3720. a register takes only a single cycle. In this chapter we improve the
  3721. efficiency of our generated code by storing some variables in
  3722. registers. The goal of register allocation is to fit as many variables
  3723. into registers as possible. Some programs have more variables than
  3724. registers so we cannot always map each variable to a different
  3725. register. Fortunately, it is common for different variables to be
  3726. in-use during different periods of time during program execution, and
  3727. in those cases we can map multiple variables to the same register.
  3728. The program in Figure~\ref{fig:reg-eg} serves as a running
  3729. example. The source program is on the left and the output of
  3730. instruction selection is on the right. The program is almost in the
  3731. x86 assembly language but it still uses variables. Consider variables
  3732. \code{x} and \code{z}. After the variable \code{x} is moved to
  3733. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3734. hand, is used only after this point, so \code{x} and \code{z} could
  3735. share the same register.
  3736. \begin{figure}
  3737. \begin{tcolorbox}[colback=white]
  3738. \begin{minipage}{0.45\textwidth}
  3739. Example \LangVar{} program:
  3740. % var_test_28.rkt
  3741. {\if\edition\racketEd
  3742. \begin{lstlisting}
  3743. (let ([v 1])
  3744. (let ([w 42])
  3745. (let ([x (+ v 7)])
  3746. (let ([y x])
  3747. (let ([z (+ x w)])
  3748. (+ z (- y)))))))
  3749. \end{lstlisting}
  3750. \fi}
  3751. {\if\edition\pythonEd
  3752. \begin{lstlisting}
  3753. v = 1
  3754. w = 42
  3755. x = v + 7
  3756. y = x
  3757. z = x + w
  3758. print(z + (- y))
  3759. \end{lstlisting}
  3760. \fi}
  3761. \end{minipage}
  3762. \begin{minipage}{0.45\textwidth}
  3763. After instruction selection:
  3764. {\if\edition\racketEd
  3765. \begin{lstlisting}
  3766. locals-types:
  3767. x : Integer, y : Integer,
  3768. z : Integer, t : Integer,
  3769. v : Integer, w : Integer
  3770. start:
  3771. movq $1, v
  3772. movq $42, w
  3773. movq v, x
  3774. addq $7, x
  3775. movq x, y
  3776. movq x, z
  3777. addq w, z
  3778. movq y, t
  3779. negq t
  3780. movq z, %rax
  3781. addq t, %rax
  3782. jmp conclusion
  3783. \end{lstlisting}
  3784. \fi}
  3785. {\if\edition\pythonEd
  3786. \begin{lstlisting}
  3787. movq $1, v
  3788. movq $42, w
  3789. movq v, x
  3790. addq $7, x
  3791. movq x, y
  3792. movq x, z
  3793. addq w, z
  3794. movq y, tmp_0
  3795. negq tmp_0
  3796. movq z, tmp_1
  3797. addq tmp_0, tmp_1
  3798. movq tmp_1, %rdi
  3799. callq print_int
  3800. \end{lstlisting}
  3801. \fi}
  3802. \end{minipage}
  3803. \end{tcolorbox}
  3804. \caption{A running example for register allocation.}
  3805. \label{fig:reg-eg}
  3806. \end{figure}
  3807. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3808. compute where a variable is in-use. Once we have that information, we
  3809. compute which variables are in-use at the same time, i.e., which ones
  3810. \emph{interfere}\index{subject}{interfere} with each other, and
  3811. represent this relation as an undirected graph whose vertices are
  3812. variables and edges indicate when two variables interfere
  3813. (Section~\ref{sec:build-interference}). We then model register
  3814. allocation as a graph coloring problem
  3815. (Section~\ref{sec:graph-coloring}).
  3816. If we run out of registers despite these efforts, we place the
  3817. remaining variables on the stack, similar to what we did in
  3818. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3819. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3820. location. The decision to spill a variable is handled as part of the
  3821. graph coloring process.
  3822. We make the simplifying assumption that each variable is assigned to
  3823. one location (a register or stack address). A more sophisticated
  3824. approach is to assign a variable to one or more locations in different
  3825. regions of the program. For example, if a variable is used many times
  3826. in short sequence and then only used again after many other
  3827. instructions, it could be more efficient to assign the variable to a
  3828. register during the initial sequence and then move it to the stack for
  3829. the rest of its lifetime. We refer the interested reader to
  3830. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3831. approach.
  3832. % discuss prioritizing variables based on how much they are used.
  3833. \section{Registers and Calling Conventions}
  3834. \label{sec:calling-conventions}
  3835. \index{subject}{calling conventions}
  3836. As we perform register allocation, we must be aware of the
  3837. \emph{calling conventions} \index{subject}{calling conventions} that
  3838. govern how functions calls are performed in x86.
  3839. %
  3840. Even though \LangVar{} does not include programmer-defined functions,
  3841. our generated code includes a \code{main} function that is called by
  3842. the operating system and our generated code contains calls to the
  3843. \code{read\_int} function.
  3844. Function calls require coordination between two pieces of code that
  3845. may be written by different programmers or generated by different
  3846. compilers. Here we follow the System V calling conventions that are
  3847. used by the GNU C compiler on Linux and
  3848. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3849. %
  3850. The calling conventions include rules about how functions share the
  3851. use of registers. In particular, the caller is responsible for freeing
  3852. up some registers prior to the function call for use by the callee.
  3853. These are called the \emph{caller-saved registers}
  3854. \index{subject}{caller-saved registers}
  3855. and they are
  3856. \begin{lstlisting}
  3857. rax rcx rdx rsi rdi r8 r9 r10 r11
  3858. \end{lstlisting}
  3859. On the other hand, the callee is responsible for preserving the values
  3860. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3861. which are
  3862. \begin{lstlisting}
  3863. rsp rbp rbx r12 r13 r14 r15
  3864. \end{lstlisting}
  3865. We can think about this caller/callee convention from two points of
  3866. view, the caller view and the callee view:
  3867. \begin{itemize}
  3868. \item The caller should assume that all the caller-saved registers get
  3869. overwritten with arbitrary values by the callee. On the other hand,
  3870. the caller can safely assume that all the callee-saved registers
  3871. retain their original values.
  3872. \item The callee can freely use any of the caller-saved registers.
  3873. However, if the callee wants to use a callee-saved register, the
  3874. callee must arrange to put the original value back in the register
  3875. prior to returning to the caller. This can be accomplished by saving
  3876. the value to the stack in the prelude of the function and restoring
  3877. the value in the conclusion of the function.
  3878. \end{itemize}
  3879. In x86, registers are also used for passing arguments to a function
  3880. and for the return value. In particular, the first six arguments of a
  3881. function are passed in the following six registers, in this order.
  3882. \index{subject}{argument-passing registers}
  3883. \index{subject}{parameter-passing registers}
  3884. \begin{lstlisting}
  3885. rdi rsi rdx rcx r8 r9
  3886. \end{lstlisting}
  3887. If there are more than six arguments, then the convention is to use
  3888. space on the frame of the caller for the rest of the
  3889. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3890. need more than six arguments.
  3891. %
  3892. \racket{For now, the only function we care about is \code{read\_int}
  3893. and it takes zero arguments.}
  3894. %
  3895. \python{For now, the only functions we care about are \code{read\_int}
  3896. and \code{print\_int}, which take zero and one argument, respectively.}
  3897. %
  3898. The register \code{rax} is used for the return value of a function.
  3899. The next question is how these calling conventions impact register
  3900. allocation. Consider the \LangVar{} program in
  3901. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3902. example from the caller point of view and then from the callee point
  3903. of view. We refer to a variable that is in-use during a function call
  3904. as being a \emph{call-live variable}\index{subject}{call-live
  3905. variable}.
  3906. The program makes two calls to \READOP{}. The variable \code{x} is
  3907. call-live because it is in-use during the second call to \READOP{}; we
  3908. must ensure that the value in \code{x} does not get overwritten during
  3909. the call to \READOP{}. One obvious approach is to save all the values
  3910. that reside in caller-saved registers to the stack prior to each
  3911. function call, and restore them after each call. That way, if the
  3912. register allocator chooses to assign \code{x} to a caller-saved
  3913. register, its value will be preserved across the call to \READOP{}.
  3914. However, saving and restoring to the stack is relatively slow. If
  3915. \code{x} is not used many times, it may be better to assign \code{x}
  3916. to a stack location in the first place. Or better yet, if we can
  3917. arrange for \code{x} to be placed in a callee-saved register, then it
  3918. won't need to be saved and restored during function calls.
  3919. The approach that we recommend for call-live variables is to either
  3920. assign them to callee-saved registers or to spill them to the
  3921. stack. On the other hand, for variables that are not call-live, we try
  3922. the following alternatives in order 1) look for an available
  3923. caller-saved register (to leave room for other variables in the
  3924. callee-saved register), 2) look for a callee-saved register, and 3)
  3925. spill the variable to the stack.
  3926. It is straightforward to implement this approach in a graph coloring
  3927. register allocator. First, we know which variables are call-live
  3928. because we already need to compute which variables are in-use at every
  3929. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3930. we build the interference graph
  3931. (Section~\ref{sec:build-interference}), we can place an edge between
  3932. each of the call-live variables and the caller-saved registers in the
  3933. interference graph. This will prevent the graph coloring algorithm
  3934. from assigning them to caller-saved registers.
  3935. Returning to the example in
  3936. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3937. generated x86 code on the right-hand side. Notice that variable
  3938. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3939. is already in a safe place during the second call to
  3940. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3941. \code{rcx}, a caller-saved register, because \code{y} is not a
  3942. call-live variable.
  3943. Next we analyze the example from the callee point of view, focusing on
  3944. the prelude and conclusion of the \code{main} function. As usual the
  3945. prelude begins with saving the \code{rbp} register to the stack and
  3946. setting the \code{rbp} to the current stack pointer. We now know why
  3947. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3948. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3949. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3950. (\code{x}). The other callee-saved registers are not saved in the
  3951. prelude because they are not used. The prelude subtracts 8 bytes from
  3952. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3953. conclusion, we see that \code{rbx} is restored from the stack with a
  3954. \code{popq} instruction.
  3955. \index{subject}{prelude}\index{subject}{conclusion}
  3956. \begin{figure}[tp]
  3957. \begin{tcolorbox}[colback=white]
  3958. \begin{minipage}{0.45\textwidth}
  3959. Example \LangVar{} program:
  3960. %var_test_14.rkt
  3961. {\if\edition\racketEd
  3962. \begin{lstlisting}
  3963. (let ([x (read)])
  3964. (let ([y (read)])
  3965. (+ (+ x y) 42)))
  3966. \end{lstlisting}
  3967. \fi}
  3968. {\if\edition\pythonEd
  3969. \begin{lstlisting}
  3970. x = input_int()
  3971. y = input_int()
  3972. print((x + y) + 42)
  3973. \end{lstlisting}
  3974. \fi}
  3975. \end{minipage}
  3976. \begin{minipage}{0.45\textwidth}
  3977. Generated x86 assembly:
  3978. {\if\edition\racketEd
  3979. \begin{lstlisting}
  3980. start:
  3981. callq read_int
  3982. movq %rax, %rbx
  3983. callq read_int
  3984. movq %rax, %rcx
  3985. addq %rcx, %rbx
  3986. movq %rbx, %rax
  3987. addq $42, %rax
  3988. jmp _conclusion
  3989. .globl main
  3990. main:
  3991. pushq %rbp
  3992. movq %rsp, %rbp
  3993. pushq %rbx
  3994. subq $8, %rsp
  3995. jmp start
  3996. conclusion:
  3997. addq $8, %rsp
  3998. popq %rbx
  3999. popq %rbp
  4000. retq
  4001. \end{lstlisting}
  4002. \fi}
  4003. {\if\edition\pythonEd
  4004. \begin{lstlisting}
  4005. .globl main
  4006. main:
  4007. pushq %rbp
  4008. movq %rsp, %rbp
  4009. pushq %rbx
  4010. subq $8, %rsp
  4011. callq read_int
  4012. movq %rax, %rbx
  4013. callq read_int
  4014. movq %rax, %rcx
  4015. movq %rbx, %rdx
  4016. addq %rcx, %rdx
  4017. movq %rdx, %rcx
  4018. addq $42, %rcx
  4019. movq %rcx, %rdi
  4020. callq print_int
  4021. addq $8, %rsp
  4022. popq %rbx
  4023. popq %rbp
  4024. retq
  4025. \end{lstlisting}
  4026. \fi}
  4027. \end{minipage}
  4028. \end{tcolorbox}
  4029. \caption{An example with function calls.}
  4030. \label{fig:example-calling-conventions}
  4031. \end{figure}
  4032. %\clearpage
  4033. \section{Liveness Analysis}
  4034. \label{sec:liveness-analysis-Lvar}
  4035. \index{subject}{liveness analysis}
  4036. The \code{uncover\_live} \racket{pass}\python{function} performs
  4037. \emph{liveness analysis}, that is, it discovers which variables are
  4038. in-use in different regions of a program.
  4039. %
  4040. A variable or register is \emph{live} at a program point if its
  4041. current value is used at some later point in the program. We refer to
  4042. variables, stack locations, and registers collectively as
  4043. \emph{locations}.
  4044. %
  4045. Consider the following code fragment in which there are two writes to
  4046. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4047. time?
  4048. \begin{center}
  4049. \begin{minipage}{0.96\textwidth}
  4050. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4051. movq $5, a
  4052. movq $30, b
  4053. movq a, c
  4054. movq $10, b
  4055. addq b, c
  4056. \end{lstlisting}
  4057. \end{minipage}
  4058. \end{center}
  4059. The answer is no because \code{a} is live from line 1 to 3 and
  4060. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4061. line 2 is never used because it is overwritten (line 4) before the
  4062. next read (line 5).
  4063. The live locations for each instruction can be computed by traversing
  4064. the instruction sequence back to front (i.e., backwards in execution
  4065. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4066. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4067. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4068. locations before instruction $I_k$. \racket{We recommend representing
  4069. these sets with the Racket \code{set} data structure described in
  4070. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4071. with the Python
  4072. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4073. data structure.}
  4074. {\if\edition\racketEd
  4075. \begin{figure}[tp]
  4076. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4077. \small
  4078. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4079. A \emph{set} is an unordered collection of elements without duplicates.
  4080. Here are some of the operations defined on sets.
  4081. \index{subject}{set}
  4082. \begin{description}
  4083. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4084. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4085. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4086. difference of the two sets.
  4087. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4088. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4089. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4090. \end{description}
  4091. \end{tcolorbox}
  4092. %\end{wrapfigure}
  4093. \caption{The \code{set} data structure.}
  4094. \label{fig:set}
  4095. \end{figure}
  4096. \fi}
  4097. The live locations after an instruction are always the same as the
  4098. live locations before the next instruction.
  4099. \index{subject}{live-after} \index{subject}{live-before}
  4100. \begin{equation} \label{eq:live-after-before-next}
  4101. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4102. \end{equation}
  4103. To start things off, there are no live locations after the last
  4104. instruction, so
  4105. \begin{equation}\label{eq:live-last-empty}
  4106. L_{\mathsf{after}}(n) = \emptyset
  4107. \end{equation}
  4108. We then apply the following rule repeatedly, traversing the
  4109. instruction sequence back to front.
  4110. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4111. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4112. \end{equation}
  4113. where $W(k)$ are the locations written to by instruction $I_k$ and
  4114. $R(k)$ are the locations read by instruction $I_k$.
  4115. {\if\edition\racketEd
  4116. %
  4117. There is a special case for \code{jmp} instructions. The locations
  4118. that are live before a \code{jmp} should be the locations in
  4119. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4120. maintaining an alist named \code{label->live} that maps each label to
  4121. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4122. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4123. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4124. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4125. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4126. %
  4127. \fi}
  4128. Let us walk through the above example, applying these formulas
  4129. starting with the instruction on line 5. We collect the answers in
  4130. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4131. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4132. instruction (formula~\ref{eq:live-last-empty}). The
  4133. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4134. because it reads from variables \code{b} and \code{c}
  4135. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4136. \[
  4137. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4138. \]
  4139. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4140. the live-before set from line 5 to be the live-after set for this
  4141. instruction (formula~\ref{eq:live-after-before-next}).
  4142. \[
  4143. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4144. \]
  4145. This move instruction writes to \code{b} and does not read from any
  4146. variables, so we have the following live-before set
  4147. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4148. \[
  4149. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4150. \]
  4151. The live-before for instruction \code{movq a, c}
  4152. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4153. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4154. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4155. variable that is not live and does not read from a variable.
  4156. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4157. because it writes to variable \code{a}.
  4158. \begin{figure}[tbp]
  4159. \centering
  4160. \begin{tcolorbox}[colback=white]
  4161. \hspace{10pt}
  4162. \begin{minipage}{0.4\textwidth}
  4163. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4164. movq $5, a
  4165. movq $30, b
  4166. movq a, c
  4167. movq $10, b
  4168. addq b, c
  4169. \end{lstlisting}
  4170. \end{minipage}
  4171. \vrule\hspace{10pt}
  4172. \begin{minipage}{0.45\textwidth}
  4173. \begin{align*}
  4174. L_{\mathsf{before}}(1)= \emptyset,
  4175. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4176. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4177. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4178. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4179. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4180. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4181. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4182. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4183. L_{\mathsf{after}}(5)= \emptyset
  4184. \end{align*}
  4185. \end{minipage}
  4186. \end{tcolorbox}
  4187. \caption{Example output of liveness analysis on a short example.}
  4188. \label{fig:liveness-example-0}
  4189. \end{figure}
  4190. \begin{exercise}\normalfont\normalsize
  4191. Perform liveness analysis by hand on the running example in
  4192. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4193. sets for each instruction. Compare your answers to the solution
  4194. shown in Figure~\ref{fig:live-eg}.
  4195. \end{exercise}
  4196. \begin{figure}[tp]
  4197. \hspace{20pt}
  4198. \begin{minipage}{0.55\textwidth}
  4199. \begin{tcolorbox}[colback=white]
  4200. {\if\edition\racketEd
  4201. \begin{lstlisting}
  4202. |$\{\ttm{rsp}\}$|
  4203. movq $1, v
  4204. |$\{\ttm{v},\ttm{rsp}\}$|
  4205. movq $42, w
  4206. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4207. movq v, x
  4208. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4209. addq $7, x
  4210. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4211. movq x, y
  4212. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4213. movq x, z
  4214. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4215. addq w, z
  4216. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4217. movq y, t
  4218. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4219. negq t
  4220. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4221. movq z, %rax
  4222. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4223. addq t, %rax
  4224. |$\{\ttm{rax},\ttm{rsp}\}$|
  4225. jmp conclusion
  4226. \end{lstlisting}
  4227. \fi}
  4228. {\if\edition\pythonEd
  4229. \begin{lstlisting}
  4230. movq $1, v
  4231. |$\{\ttm{v}\}$|
  4232. movq $42, w
  4233. |$\{\ttm{w}, \ttm{v}\}$|
  4234. movq v, x
  4235. |$\{\ttm{w}, \ttm{x}\}$|
  4236. addq $7, x
  4237. |$\{\ttm{w}, \ttm{x}\}$|
  4238. movq x, y
  4239. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4240. movq x, z
  4241. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4242. addq w, z
  4243. |$\{\ttm{y}, \ttm{z}\}$|
  4244. movq y, tmp_0
  4245. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4246. negq tmp_0
  4247. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4248. movq z, tmp_1
  4249. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4250. addq tmp_0, tmp_1
  4251. |$\{\ttm{tmp\_1}\}$|
  4252. movq tmp_1, %rdi
  4253. |$\{\ttm{rdi}\}$|
  4254. callq print_int
  4255. |$\{\}$|
  4256. \end{lstlisting}
  4257. \fi}
  4258. \end{tcolorbox}
  4259. \end{minipage}
  4260. \caption{The running example annotated with live-after sets.}
  4261. \label{fig:live-eg}
  4262. \end{figure}
  4263. \begin{exercise}\normalfont\normalsize
  4264. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4265. %
  4266. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4267. field of the \code{Block} structure.}
  4268. %
  4269. \python{Return a dictionary that maps each instruction to its
  4270. live-after set.}
  4271. %
  4272. \racket{We recommend creating an auxiliary function that takes a list
  4273. of instructions and an initial live-after set (typically empty) and
  4274. returns the list of live-after sets.}
  4275. %
  4276. We recommend creating auxiliary functions to 1) compute the set
  4277. of locations that appear in an \Arg{}, 2) compute the locations read
  4278. by an instruction (the $R$ function), and 3) the locations written by
  4279. an instruction (the $W$ function). The \code{callq} instruction should
  4280. include all of the caller-saved registers in its write-set $W$ because
  4281. the calling convention says that those registers may be written to
  4282. during the function call. Likewise, the \code{callq} instruction
  4283. should include the appropriate argument-passing registers in its
  4284. read-set $R$, depending on the arity of the function being
  4285. called. (This is why the abstract syntax for \code{callq} includes the
  4286. arity.)
  4287. \end{exercise}
  4288. %\clearpage
  4289. \section{Build the Interference Graph}
  4290. \label{sec:build-interference}
  4291. {\if\edition\racketEd
  4292. \begin{figure}[tp]
  4293. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4294. \small
  4295. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4296. A \emph{graph} is a collection of vertices and edges where each
  4297. edge connects two vertices. A graph is \emph{directed} if each
  4298. edge points from a source to a target. Otherwise the graph is
  4299. \emph{undirected}.
  4300. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4301. \begin{description}
  4302. %% We currently don't use directed graphs. We instead use
  4303. %% directed multi-graphs. -Jeremy
  4304. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4305. directed graph from a list of edges. Each edge is a list
  4306. containing the source and target vertex.
  4307. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4308. undirected graph from a list of edges. Each edge is represented by
  4309. a list containing two vertices.
  4310. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4311. inserts a vertex into the graph.
  4312. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4313. inserts an edge between the two vertices.
  4314. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4315. returns a sequence of vertices adjacent to the vertex.
  4316. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4317. returns a sequence of all vertices in the graph.
  4318. \end{description}
  4319. \end{tcolorbox}
  4320. %\end{wrapfigure}
  4321. \caption{The Racket \code{graph} package.}
  4322. \label{fig:graph}
  4323. \end{figure}
  4324. \fi}
  4325. Based on the liveness analysis, we know where each location is live.
  4326. However, during register allocation, we need to answer questions of
  4327. the specific form: are locations $u$ and $v$ live at the same time?
  4328. (And therefore cannot be assigned to the same register.) To make this
  4329. question more efficient to answer, we create an explicit data
  4330. structure, an \emph{interference graph}\index{subject}{interference
  4331. graph}. An interference graph is an undirected graph that has an
  4332. edge between two locations if they are live at the same time, that is,
  4333. if they interfere with each other.
  4334. %
  4335. \racket{We recommend using the Racket \code{graph} package
  4336. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4337. %
  4338. \python{We provide implementations of directed and undirected graph
  4339. data structures in the file \code{graph.py} of the support code.}
  4340. A straightforward way to compute the interference graph is to look at
  4341. the set of live locations between each instruction and add an edge to
  4342. the graph for every pair of variables in the same set. This approach
  4343. is less than ideal for two reasons. First, it can be expensive because
  4344. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4345. locations. Second, in the special case where two locations hold the
  4346. same value (because one was assigned to the other), they can be live
  4347. at the same time without interfering with each other.
  4348. A better way to compute the interference graph is to focus on
  4349. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4350. must not overwrite something in a live location. So for each
  4351. instruction, we create an edge between the locations being written to
  4352. and the live locations. (Except that a location never interferes with
  4353. itself.) For the \key{callq} instruction, we consider all of the
  4354. caller-saved registers as being written to, so an edge is added
  4355. between every live variable and every caller-saved register. Also, for
  4356. \key{movq} there is the special case of two variables holding the same
  4357. value. If a live variable $v$ is the same as the source of the
  4358. \key{movq}, then there is no need to add an edge between $v$ and the
  4359. destination, because they both hold the same value.
  4360. %
  4361. So we have the following two rules.
  4362. \begin{enumerate}
  4363. \item If instruction $I_k$ is a move instruction of the form
  4364. \key{movq} $s$\key{,} $d$, then for every $v \in
  4365. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4366. $(d,v)$.
  4367. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4368. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4369. $(d,v)$.
  4370. \end{enumerate}
  4371. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4372. the above rules to each instruction. We highlight a few of the
  4373. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4374. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4375. so \code{v} interferes with \code{rsp}.}
  4376. %
  4377. \python{The first instruction is \lstinline{movq $1, v} and the
  4378. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4379. no interference because $\ttm{v}$ is the destination of the move.}
  4380. %
  4381. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4382. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4383. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4384. %
  4385. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4386. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4387. $\ttm{x}$ interferes with \ttm{w}.}
  4388. %
  4389. \racket{The next instruction is \lstinline{movq x, y} and the
  4390. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4391. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4392. \ttm{x} because \ttm{x} is the source of the move and therefore
  4393. \ttm{x} and \ttm{y} hold the same value.}
  4394. %
  4395. \python{The next instruction is \lstinline{movq x, y} and the
  4396. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4397. applies, so \ttm{y} interferes with \ttm{w} but not
  4398. \ttm{x} because \ttm{x} is the source of the move and therefore
  4399. \ttm{x} and \ttm{y} hold the same value.}
  4400. %
  4401. Figure~\ref{fig:interference-results} lists the interference results
  4402. for all of the instructions and the resulting interference graph is
  4403. shown in Figure~\ref{fig:interfere}.
  4404. \begin{figure}[tbp]
  4405. \begin{tcolorbox}[colback=white]
  4406. \begin{quote}
  4407. {\if\edition\racketEd
  4408. \begin{tabular}{ll}
  4409. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4410. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4411. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4412. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4413. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4414. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4415. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4416. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4417. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4418. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4419. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4420. \lstinline!jmp conclusion!& no interference.
  4421. \end{tabular}
  4422. \fi}
  4423. {\if\edition\pythonEd
  4424. \begin{tabular}{ll}
  4425. \lstinline!movq $1, v!& no interference\\
  4426. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4427. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4428. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4429. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4430. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4431. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4432. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4433. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4434. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4435. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4436. \lstinline!movq tmp_1, %rdi! & no interference \\
  4437. \lstinline!callq print_int!& no interference.
  4438. \end{tabular}
  4439. \fi}
  4440. \end{quote}
  4441. \end{tcolorbox}
  4442. \caption{Interference results for the running example.}
  4443. \label{fig:interference-results}
  4444. \end{figure}
  4445. \begin{figure}[tbp]
  4446. \begin{tcolorbox}[colback=white]
  4447. \large
  4448. {\if\edition\racketEd
  4449. \[
  4450. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4451. \node (rax) at (0,0) {$\ttm{rax}$};
  4452. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4453. \node (t1) at (0,2) {$\ttm{t}$};
  4454. \node (z) at (3,2) {$\ttm{z}$};
  4455. \node (x) at (6,2) {$\ttm{x}$};
  4456. \node (y) at (3,0) {$\ttm{y}$};
  4457. \node (w) at (6,0) {$\ttm{w}$};
  4458. \node (v) at (9,0) {$\ttm{v}$};
  4459. \draw (t1) to (rax);
  4460. \draw (t1) to (z);
  4461. \draw (z) to (y);
  4462. \draw (z) to (w);
  4463. \draw (x) to (w);
  4464. \draw (y) to (w);
  4465. \draw (v) to (w);
  4466. \draw (v) to (rsp);
  4467. \draw (w) to (rsp);
  4468. \draw (x) to (rsp);
  4469. \draw (y) to (rsp);
  4470. \path[-.,bend left=15] (z) edge node {} (rsp);
  4471. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4472. \draw (rax) to (rsp);
  4473. \end{tikzpicture}
  4474. \]
  4475. \fi}
  4476. {\if\edition\pythonEd
  4477. \[
  4478. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4479. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4480. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4481. \node (z) at (3,2) {$\ttm{z}$};
  4482. \node (x) at (6,2) {$\ttm{x}$};
  4483. \node (y) at (3,0) {$\ttm{y}$};
  4484. \node (w) at (6,0) {$\ttm{w}$};
  4485. \node (v) at (9,0) {$\ttm{v}$};
  4486. \draw (t0) to (t1);
  4487. \draw (t0) to (z);
  4488. \draw (z) to (y);
  4489. \draw (z) to (w);
  4490. \draw (x) to (w);
  4491. \draw (y) to (w);
  4492. \draw (v) to (w);
  4493. \end{tikzpicture}
  4494. \]
  4495. \fi}
  4496. \end{tcolorbox}
  4497. \caption{The interference graph of the example program.}
  4498. \label{fig:interfere}
  4499. \end{figure}
  4500. %% Our next concern is to choose a data structure for representing the
  4501. %% interference graph. There are many choices for how to represent a
  4502. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4503. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4504. %% data structure is to study the algorithm that uses the data structure,
  4505. %% determine what operations need to be performed, and then choose the
  4506. %% data structure that provide the most efficient implementations of
  4507. %% those operations. Often times the choice of data structure can have an
  4508. %% effect on the time complexity of the algorithm, as it does here. If
  4509. %% you skim the next section, you will see that the register allocation
  4510. %% algorithm needs to ask the graph for all of its vertices and, given a
  4511. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4512. %% correct choice of graph representation is that of an adjacency
  4513. %% list. There are helper functions in \code{utilities.rkt} for
  4514. %% representing graphs using the adjacency list representation:
  4515. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4516. %% (Appendix~\ref{appendix:utilities}).
  4517. %% %
  4518. %% \margincomment{\footnotesize To do: change to use the
  4519. %% Racket graph library. \\ --Jeremy}
  4520. %% %
  4521. %% In particular, those functions use a hash table to map each vertex to
  4522. %% the set of adjacent vertices, and the sets are represented using
  4523. %% Racket's \key{set}, which is also a hash table.
  4524. \begin{exercise}\normalfont\normalsize
  4525. \racket{Implement the compiler pass named \code{build\_interference} according
  4526. to the algorithm suggested above. We recommend using the Racket
  4527. \code{graph} package to create and inspect the interference graph.
  4528. The output graph of this pass should be stored in the $\itm{info}$ field of
  4529. the program, under the key \code{conflicts}.}
  4530. %
  4531. \python{Implement a function named \code{build\_interference}
  4532. according to the algorithm suggested above that
  4533. returns the interference graph.}
  4534. \end{exercise}
  4535. \section{Graph Coloring via Sudoku}
  4536. \label{sec:graph-coloring}
  4537. \index{subject}{graph coloring}
  4538. \index{subject}{Sudoku}
  4539. \index{subject}{color}
  4540. We come to the main event of this chapter, mapping variables to
  4541. registers and stack locations. Variables that interfere with each
  4542. other must be mapped to different locations. In terms of the
  4543. interference graph, this means that adjacent vertices must be mapped
  4544. to different locations. If we think of locations as colors, the
  4545. register allocation problem becomes the graph coloring
  4546. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4547. The reader may be more familiar with the graph coloring problem than he
  4548. or she realizes; the popular game of Sudoku is an instance of the
  4549. graph coloring problem. The following describes how to build a graph
  4550. out of an initial Sudoku board.
  4551. \begin{itemize}
  4552. \item There is one vertex in the graph for each Sudoku square.
  4553. \item There is an edge between two vertices if the corresponding squares
  4554. are in the same row, in the same column, or if the squares are in
  4555. the same $3\times 3$ region.
  4556. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4557. \item Based on the initial assignment of numbers to squares in the
  4558. Sudoku board, assign the corresponding colors to the corresponding
  4559. vertices in the graph.
  4560. \end{itemize}
  4561. If you can color the remaining vertices in the graph with the nine
  4562. colors, then you have also solved the corresponding game of Sudoku.
  4563. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4564. the corresponding graph with colored vertices. We map the Sudoku
  4565. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4566. sampling of the vertices (the colored ones) because showing edges for
  4567. all of the vertices would make the graph unreadable.
  4568. \begin{figure}[tbp]
  4569. \begin{tcolorbox}[colback=white]
  4570. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4571. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4572. \end{tcolorbox}
  4573. \caption{A Sudoku game board and the corresponding colored graph.}
  4574. \label{fig:sudoku-graph}
  4575. \end{figure}
  4576. Some techniques for playing Sudoku correspond to heuristics used in
  4577. graph coloring algorithms. For example, one of the basic techniques
  4578. for Sudoku is called Pencil Marks. The idea is to use a process of
  4579. elimination to determine what numbers are no longer available for a
  4580. square and write down those numbers in the square (writing very
  4581. small). For example, if the number $1$ is assigned to a square, then
  4582. write the pencil mark $1$ in all the squares in the same row, column,
  4583. and region to indicate that $1$ is no longer an option for those other
  4584. squares.
  4585. %
  4586. The Pencil Marks technique corresponds to the notion of
  4587. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4588. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4589. are no longer available. In graph terminology, we have the following
  4590. definition:
  4591. \begin{equation*}
  4592. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4593. \text{ and } \mathrm{color}(v) = c \}
  4594. \end{equation*}
  4595. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4596. edge with $u$.
  4597. The Pencil Marks technique leads to a simple strategy for filling in
  4598. numbers: if there is a square with only one possible number left, then
  4599. choose that number! But what if there are no squares with only one
  4600. possibility left? One brute-force approach is to try them all: choose
  4601. the first one and if that ultimately leads to a solution, great. If
  4602. not, backtrack and choose the next possibility. One good thing about
  4603. Pencil Marks is that it reduces the degree of branching in the search
  4604. tree. Nevertheless, backtracking can be terribly time consuming. One
  4605. way to reduce the amount of backtracking is to use the
  4606. most-constrained-first heuristic (aka. minimum remaining
  4607. values)~\citep{Russell2003}. That is, when choosing a square, always
  4608. choose one with the fewest possibilities left (the vertex with the
  4609. highest saturation). The idea is that choosing highly constrained
  4610. squares earlier rather than later is better because later on there may
  4611. not be any possibilities left in the highly saturated squares.
  4612. However, register allocation is easier than Sudoku because the
  4613. register allocator can fall back to assigning variables to stack
  4614. locations when the registers run out. Thus, it makes sense to replace
  4615. backtracking with greedy search: make the best choice at the time and
  4616. keep going. We still wish to minimize the number of colors needed, so
  4617. we use the most-constrained-first heuristic in the greedy search.
  4618. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4619. algorithm for register allocation based on saturation and the
  4620. most-constrained-first heuristic. It is roughly equivalent to the
  4621. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4622. %,Gebremedhin:1999fk,Omari:2006uq
  4623. Just as in Sudoku, the algorithm represents colors with integers. The
  4624. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4625. for register allocation. The integers $k$ and larger correspond to
  4626. stack locations. The registers that are not used for register
  4627. allocation, such as \code{rax}, are assigned to negative integers. In
  4628. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4629. %% One might wonder why we include registers at all in the liveness
  4630. %% analysis and interference graph. For example, we never allocate a
  4631. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4632. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4633. %% to use register for passing arguments to functions, it will be
  4634. %% necessary for those registers to appear in the interference graph
  4635. %% because those registers will also be assigned to variables, and we
  4636. %% don't want those two uses to encroach on each other. Regarding
  4637. %% registers such as \code{rax} and \code{rsp} that are not used for
  4638. %% variables, we could omit them from the interference graph but that
  4639. %% would require adding special cases to our algorithm, which would
  4640. %% complicate the logic for little gain.
  4641. \begin{figure}[btp]
  4642. \begin{tcolorbox}[colback=white]
  4643. \centering
  4644. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4645. Algorithm: DSATUR
  4646. Input: a graph |$G$|
  4647. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4648. |$W \gets \mathrm{vertices}(G)$|
  4649. while |$W \neq \emptyset$| do
  4650. pick a vertex |$u$| from |$W$| with the highest saturation,
  4651. breaking ties randomly
  4652. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4653. |$\mathrm{color}[u] \gets c$|
  4654. |$W \gets W - \{u\}$|
  4655. \end{lstlisting}
  4656. \end{tcolorbox}
  4657. \caption{The saturation-based greedy graph coloring algorithm.}
  4658. \label{fig:satur-algo}
  4659. \end{figure}
  4660. {\if\edition\racketEd
  4661. With the DSATUR algorithm in hand, let us return to the running
  4662. example and consider how to color the interference graph in
  4663. Figure~\ref{fig:interfere}.
  4664. %
  4665. We start by assigning the register nodes to their own color. For
  4666. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4667. assigned $-2$. The variables are not yet colored, so they are
  4668. annotated with a dash. We then update the saturation for vertices that
  4669. are adjacent to a register, obtaining the following annotated
  4670. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4671. it interferes with both \code{rax} and \code{rsp}.
  4672. \[
  4673. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4674. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4675. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4676. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4677. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4678. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4679. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4680. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4681. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4682. \draw (t1) to (rax);
  4683. \draw (t1) to (z);
  4684. \draw (z) to (y);
  4685. \draw (z) to (w);
  4686. \draw (x) to (w);
  4687. \draw (y) to (w);
  4688. \draw (v) to (w);
  4689. \draw (v) to (rsp);
  4690. \draw (w) to (rsp);
  4691. \draw (x) to (rsp);
  4692. \draw (y) to (rsp);
  4693. \path[-.,bend left=15] (z) edge node {} (rsp);
  4694. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4695. \draw (rax) to (rsp);
  4696. \end{tikzpicture}
  4697. \]
  4698. The algorithm says to select a maximally saturated vertex. So we pick
  4699. $\ttm{t}$ and color it with the first available integer, which is
  4700. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4701. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4702. \[
  4703. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4704. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4705. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4706. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4707. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4708. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4709. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4710. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4711. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4712. \draw (t1) to (rax);
  4713. \draw (t1) to (z);
  4714. \draw (z) to (y);
  4715. \draw (z) to (w);
  4716. \draw (x) to (w);
  4717. \draw (y) to (w);
  4718. \draw (v) to (w);
  4719. \draw (v) to (rsp);
  4720. \draw (w) to (rsp);
  4721. \draw (x) to (rsp);
  4722. \draw (y) to (rsp);
  4723. \path[-.,bend left=15] (z) edge node {} (rsp);
  4724. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4725. \draw (rax) to (rsp);
  4726. \end{tikzpicture}
  4727. \]
  4728. We repeat the process, selecting a maximally saturated vertex,
  4729. choosing is \code{z}, and color it with the first available number, which
  4730. is $1$. We add $1$ to the saturation for the neighboring vertices
  4731. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4732. \[
  4733. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4734. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4735. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4736. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4737. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4738. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4739. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4740. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4741. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4742. \draw (t1) to (rax);
  4743. \draw (t1) to (z);
  4744. \draw (z) to (y);
  4745. \draw (z) to (w);
  4746. \draw (x) to (w);
  4747. \draw (y) to (w);
  4748. \draw (v) to (w);
  4749. \draw (v) to (rsp);
  4750. \draw (w) to (rsp);
  4751. \draw (x) to (rsp);
  4752. \draw (y) to (rsp);
  4753. \path[-.,bend left=15] (z) edge node {} (rsp);
  4754. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4755. \draw (rax) to (rsp);
  4756. \end{tikzpicture}
  4757. \]
  4758. The most saturated vertices are now \code{w} and \code{y}. We color
  4759. \code{w} with the first available color, which is $0$.
  4760. \[
  4761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4762. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4763. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4764. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4765. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4766. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4767. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4768. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4769. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4770. \draw (t1) to (rax);
  4771. \draw (t1) to (z);
  4772. \draw (z) to (y);
  4773. \draw (z) to (w);
  4774. \draw (x) to (w);
  4775. \draw (y) to (w);
  4776. \draw (v) to (w);
  4777. \draw (v) to (rsp);
  4778. \draw (w) to (rsp);
  4779. \draw (x) to (rsp);
  4780. \draw (y) to (rsp);
  4781. \path[-.,bend left=15] (z) edge node {} (rsp);
  4782. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4783. \draw (rax) to (rsp);
  4784. \end{tikzpicture}
  4785. \]
  4786. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4787. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4788. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4789. and \code{z}, whose colors are $0$ and $1$ respectively.
  4790. \[
  4791. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4792. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4793. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4794. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4795. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4796. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4797. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4798. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4799. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4800. \draw (t1) to (rax);
  4801. \draw (t1) to (z);
  4802. \draw (z) to (y);
  4803. \draw (z) to (w);
  4804. \draw (x) to (w);
  4805. \draw (y) to (w);
  4806. \draw (v) to (w);
  4807. \draw (v) to (rsp);
  4808. \draw (w) to (rsp);
  4809. \draw (x) to (rsp);
  4810. \draw (y) to (rsp);
  4811. \path[-.,bend left=15] (z) edge node {} (rsp);
  4812. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4813. \draw (rax) to (rsp);
  4814. \end{tikzpicture}
  4815. \]
  4816. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4817. \[
  4818. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4819. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4820. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4821. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4822. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4823. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4824. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4825. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4826. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4827. \draw (t1) to (rax);
  4828. \draw (t1) to (z);
  4829. \draw (z) to (y);
  4830. \draw (z) to (w);
  4831. \draw (x) to (w);
  4832. \draw (y) to (w);
  4833. \draw (v) to (w);
  4834. \draw (v) to (rsp);
  4835. \draw (w) to (rsp);
  4836. \draw (x) to (rsp);
  4837. \draw (y) to (rsp);
  4838. \path[-.,bend left=15] (z) edge node {} (rsp);
  4839. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4840. \draw (rax) to (rsp);
  4841. \end{tikzpicture}
  4842. \]
  4843. In the last step of the algorithm, we color \code{x} with $1$.
  4844. \[
  4845. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4846. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4847. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4848. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4849. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4850. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4851. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4852. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4853. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4854. \draw (t1) to (rax);
  4855. \draw (t1) 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. \draw (v) to (rsp);
  4862. \draw (w) to (rsp);
  4863. \draw (x) to (rsp);
  4864. \draw (y) to (rsp);
  4865. \path[-.,bend left=15] (z) edge node {} (rsp);
  4866. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4867. \draw (rax) to (rsp);
  4868. \end{tikzpicture}
  4869. \]
  4870. So we obtain the following coloring:
  4871. \[
  4872. \{
  4873. \ttm{rax} \mapsto -1,
  4874. \ttm{rsp} \mapsto -2,
  4875. \ttm{t} \mapsto 0,
  4876. \ttm{z} \mapsto 1,
  4877. \ttm{x} \mapsto 1,
  4878. \ttm{y} \mapsto 2,
  4879. \ttm{w} \mapsto 0,
  4880. \ttm{v} \mapsto 1
  4881. \}
  4882. \]
  4883. \fi}
  4884. %
  4885. {\if\edition\pythonEd
  4886. %
  4887. With the DSATUR algorithm in hand, let us return to the running
  4888. example and consider how to color the interference graph in
  4889. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4890. to indicate that it has not yet been assigned a color. The saturation
  4891. sets are also shown for each node; all of them start as the empty set.
  4892. (We do not include the register nodes in the graph below because there
  4893. were no interference edges involving registers in this program, but in
  4894. general there can be.)
  4895. %
  4896. \[
  4897. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4898. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4899. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4900. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4901. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4902. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4903. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4904. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4905. \draw (t0) to (t1);
  4906. \draw (t0) to (z);
  4907. \draw (z) to (y);
  4908. \draw (z) to (w);
  4909. \draw (x) to (w);
  4910. \draw (y) to (w);
  4911. \draw (v) to (w);
  4912. \end{tikzpicture}
  4913. \]
  4914. The algorithm says to select a maximally saturated vertex, but they
  4915. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4916. then color it with the first available integer, which is $0$. We mark
  4917. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4918. they interfere with $\ttm{tmp\_0}$.
  4919. \[
  4920. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4921. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4922. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4923. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4924. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4925. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4926. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4927. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4928. \draw (t0) to (t1);
  4929. \draw (t0) to (z);
  4930. \draw (z) to (y);
  4931. \draw (z) to (w);
  4932. \draw (x) to (w);
  4933. \draw (y) to (w);
  4934. \draw (v) to (w);
  4935. \end{tikzpicture}
  4936. \]
  4937. We repeat the process. The most saturated vertices are \code{z} and
  4938. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4939. available number, which is $1$. We add $1$ to the saturation for the
  4940. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4941. \[
  4942. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4943. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4944. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4945. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4946. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4947. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4948. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4949. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4950. \draw (t0) to (t1);
  4951. \draw (t0) to (z);
  4952. \draw (z) to (y);
  4953. \draw (z) to (w);
  4954. \draw (x) to (w);
  4955. \draw (y) to (w);
  4956. \draw (v) to (w);
  4957. \end{tikzpicture}
  4958. \]
  4959. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4960. \code{y}. We color \code{w} with the first available color, which
  4961. is $0$.
  4962. \[
  4963. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4964. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4965. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4966. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4967. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4968. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4969. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4970. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4971. \draw (t0) to (t1);
  4972. \draw (t0) to (z);
  4973. \draw (z) to (y);
  4974. \draw (z) to (w);
  4975. \draw (x) to (w);
  4976. \draw (y) to (w);
  4977. \draw (v) to (w);
  4978. \end{tikzpicture}
  4979. \]
  4980. Now \code{y} is the most saturated, so we color it with $2$.
  4981. \[
  4982. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4983. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4984. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4985. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4986. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4987. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4988. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4989. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4990. \draw (t0) to (t1);
  4991. \draw (t0) to (z);
  4992. \draw (z) to (y);
  4993. \draw (z) to (w);
  4994. \draw (x) to (w);
  4995. \draw (y) to (w);
  4996. \draw (v) to (w);
  4997. \end{tikzpicture}
  4998. \]
  4999. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5000. We choose to color \code{v} with $1$.
  5001. \[
  5002. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5003. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5004. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5005. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5006. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5007. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5008. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5009. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5010. \draw (t0) to (t1);
  5011. \draw (t0) to (z);
  5012. \draw (z) to (y);
  5013. \draw (z) to (w);
  5014. \draw (x) to (w);
  5015. \draw (y) to (w);
  5016. \draw (v) to (w);
  5017. \end{tikzpicture}
  5018. \]
  5019. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5020. \[
  5021. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5022. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5023. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5024. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5025. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5026. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5027. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5028. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5029. \draw (t0) to (t1);
  5030. \draw (t0) to (z);
  5031. \draw (z) to (y);
  5032. \draw (z) to (w);
  5033. \draw (x) to (w);
  5034. \draw (y) to (w);
  5035. \draw (v) to (w);
  5036. \end{tikzpicture}
  5037. \]
  5038. So we obtain the following coloring:
  5039. \[
  5040. \{ \ttm{tmp\_0} \mapsto 0,
  5041. \ttm{tmp\_1} \mapsto 1,
  5042. \ttm{z} \mapsto 1,
  5043. \ttm{x} \mapsto 1,
  5044. \ttm{y} \mapsto 2,
  5045. \ttm{w} \mapsto 0,
  5046. \ttm{v} \mapsto 1 \}
  5047. \]
  5048. \fi}
  5049. We recommend creating an auxiliary function named \code{color\_graph}
  5050. that takes an interference graph and a list of all the variables in
  5051. the program. This function should return a mapping of variables to
  5052. their colors (represented as natural numbers). By creating this helper
  5053. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  5054. when we add support for functions.
  5055. To prioritize the processing of highly saturated nodes inside the
  5056. \code{color\_graph} function, we recommend using the priority queue
  5057. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5058. addition, you will need to maintain a mapping from variables to their
  5059. ``handles'' in the priority queue so that you can notify the priority
  5060. queue when their saturation changes.}
  5061. {\if\edition\racketEd
  5062. \begin{figure}[tp]
  5063. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5064. \small
  5065. \begin{tcolorbox}[title=Priority Queue]
  5066. A \emph{priority queue} is a collection of items in which the
  5067. removal of items is governed by priority. In a ``min'' queue,
  5068. lower priority items are removed first. An implementation is in
  5069. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5070. queue} \index{subject}{minimum priority queue}
  5071. \begin{description}
  5072. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5073. priority queue that uses the $\itm{cmp}$ predicate to determine
  5074. whether its first argument has lower or equal priority to its
  5075. second argument.
  5076. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5077. items in the queue.
  5078. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5079. the item into the queue and returns a handle for the item in the
  5080. queue.
  5081. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5082. the lowest priority.
  5083. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5084. notifies the queue that the priority has decreased for the item
  5085. associated with the given handle.
  5086. \end{description}
  5087. \end{tcolorbox}
  5088. %\end{wrapfigure}
  5089. \caption{The priority queue data structure.}
  5090. \label{fig:priority-queue}
  5091. \end{figure}
  5092. \fi}
  5093. With the coloring complete, we finalize the assignment of variables to
  5094. registers and stack locations. We map the first $k$ colors to the $k$
  5095. registers and the rest of the colors to stack locations. Suppose for
  5096. the moment that we have just one register to use for register
  5097. allocation, \key{rcx}. Then we have the following map from colors to
  5098. locations.
  5099. \[
  5100. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5101. \]
  5102. Composing this mapping with the coloring, we arrive at the following
  5103. assignment of variables to locations.
  5104. {\if\edition\racketEd
  5105. \begin{gather*}
  5106. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5107. \ttm{w} \mapsto \key{\%rcx}, \,
  5108. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5109. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5110. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5111. \ttm{t} \mapsto \key{\%rcx} \}
  5112. \end{gather*}
  5113. \fi}
  5114. {\if\edition\pythonEd
  5115. \begin{gather*}
  5116. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5117. \ttm{w} \mapsto \key{\%rcx}, \,
  5118. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5119. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5120. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5121. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5122. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5123. \end{gather*}
  5124. \fi}
  5125. Adapt the code from the \code{assign\_homes} pass
  5126. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5127. assigned location. Applying the above assignment to our running
  5128. example, on the left, yields the program on the right.
  5129. % why frame size of 32? -JGS
  5130. \begin{center}
  5131. {\if\edition\racketEd
  5132. \begin{minipage}{0.3\textwidth}
  5133. \begin{lstlisting}
  5134. movq $1, v
  5135. movq $42, w
  5136. movq v, x
  5137. addq $7, x
  5138. movq x, y
  5139. movq x, z
  5140. addq w, z
  5141. movq y, t
  5142. negq t
  5143. movq z, %rax
  5144. addq t, %rax
  5145. jmp conclusion
  5146. \end{lstlisting}
  5147. \end{minipage}
  5148. $\Rightarrow\qquad$
  5149. \begin{minipage}{0.45\textwidth}
  5150. \begin{lstlisting}
  5151. movq $1, -8(%rbp)
  5152. movq $42, %rcx
  5153. movq -8(%rbp), -8(%rbp)
  5154. addq $7, -8(%rbp)
  5155. movq -8(%rbp), -16(%rbp)
  5156. movq -8(%rbp), -8(%rbp)
  5157. addq %rcx, -8(%rbp)
  5158. movq -16(%rbp), %rcx
  5159. negq %rcx
  5160. movq -8(%rbp), %rax
  5161. addq %rcx, %rax
  5162. jmp conclusion
  5163. \end{lstlisting}
  5164. \end{minipage}
  5165. \fi}
  5166. {\if\edition\pythonEd
  5167. \begin{minipage}{0.3\textwidth}
  5168. \begin{lstlisting}
  5169. movq $1, v
  5170. movq $42, w
  5171. movq v, x
  5172. addq $7, x
  5173. movq x, y
  5174. movq x, z
  5175. addq w, z
  5176. movq y, tmp_0
  5177. negq tmp_0
  5178. movq z, tmp_1
  5179. addq tmp_0, tmp_1
  5180. movq tmp_1, %rdi
  5181. callq print_int
  5182. \end{lstlisting}
  5183. \end{minipage}
  5184. $\Rightarrow\qquad$
  5185. \begin{minipage}{0.45\textwidth}
  5186. \begin{lstlisting}
  5187. movq $1, -8(%rbp)
  5188. movq $42, %rcx
  5189. movq -8(%rbp), -8(%rbp)
  5190. addq $7, -8(%rbp)
  5191. movq -8(%rbp), -16(%rbp)
  5192. movq -8(%rbp), -8(%rbp)
  5193. addq %rcx, -8(%rbp)
  5194. movq -16(%rbp), %rcx
  5195. negq %rcx
  5196. movq -8(%rbp), -8(%rbp)
  5197. addq %rcx, -8(%rbp)
  5198. movq -8(%rbp), %rdi
  5199. callq print_int
  5200. \end{lstlisting}
  5201. \end{minipage}
  5202. \fi}
  5203. \end{center}
  5204. \begin{exercise}\normalfont\normalsize
  5205. Implement the \code{allocate\_registers} pass.
  5206. Create five programs that exercise all aspects of the register
  5207. allocation algorithm, including spilling variables to the stack.
  5208. %
  5209. {\if\edition\racketEd
  5210. Replace \code{assign\_homes} in the list of \code{passes} in the
  5211. \code{run-tests.rkt} script with the three new passes:
  5212. \code{uncover\_live}, \code{build\_interference}, and
  5213. \code{allocate\_registers}.
  5214. Temporarily remove the call to \code{compiler-tests}.
  5215. Run the script to test the register allocator.
  5216. \fi}
  5217. %
  5218. {\if\edition\pythonEd
  5219. Run the \code{run-tests.py} script to to check whether the
  5220. output programs produce the same result as the input programs.
  5221. \fi}
  5222. \end{exercise}
  5223. \section{Patch Instructions}
  5224. \label{sec:patch-instructions}
  5225. The remaining step in the compilation to x86 is to ensure that the
  5226. instructions have at most one argument that is a memory access.
  5227. %
  5228. In the running example, the instruction \code{movq -8(\%rbp),
  5229. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5230. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5231. then move \code{rax} into \code{-16(\%rbp)}.
  5232. %
  5233. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5234. problematic, but they can simply be deleted. In general, we recommend
  5235. deleting all the trivial moves whose source and destination are the
  5236. same location.
  5237. %
  5238. The following is the output of \code{patch\_instructions} on the
  5239. running example.
  5240. \begin{center}
  5241. {\if\edition\racketEd
  5242. \begin{minipage}{0.4\textwidth}
  5243. \begin{lstlisting}
  5244. movq $1, -8(%rbp)
  5245. movq $42, %rcx
  5246. movq -8(%rbp), -8(%rbp)
  5247. addq $7, -8(%rbp)
  5248. movq -8(%rbp), -16(%rbp)
  5249. movq -8(%rbp), -8(%rbp)
  5250. addq %rcx, -8(%rbp)
  5251. movq -16(%rbp), %rcx
  5252. negq %rcx
  5253. movq -8(%rbp), %rax
  5254. addq %rcx, %rax
  5255. jmp conclusion
  5256. \end{lstlisting}
  5257. \end{minipage}
  5258. $\Rightarrow\qquad$
  5259. \begin{minipage}{0.45\textwidth}
  5260. \begin{lstlisting}
  5261. movq $1, -8(%rbp)
  5262. movq $42, %rcx
  5263. addq $7, -8(%rbp)
  5264. movq -8(%rbp), %rax
  5265. movq %rax, -16(%rbp)
  5266. addq %rcx, -8(%rbp)
  5267. movq -16(%rbp), %rcx
  5268. negq %rcx
  5269. movq -8(%rbp), %rax
  5270. addq %rcx, %rax
  5271. jmp conclusion
  5272. \end{lstlisting}
  5273. \end{minipage}
  5274. \fi}
  5275. {\if\edition\pythonEd
  5276. \begin{minipage}{0.4\textwidth}
  5277. \begin{lstlisting}
  5278. movq $1, -8(%rbp)
  5279. movq $42, %rcx
  5280. movq -8(%rbp), -8(%rbp)
  5281. addq $7, -8(%rbp)
  5282. movq -8(%rbp), -16(%rbp)
  5283. movq -8(%rbp), -8(%rbp)
  5284. addq %rcx, -8(%rbp)
  5285. movq -16(%rbp), %rcx
  5286. negq %rcx
  5287. movq -8(%rbp), -8(%rbp)
  5288. addq %rcx, -8(%rbp)
  5289. movq -8(%rbp), %rdi
  5290. callq print_int
  5291. \end{lstlisting}
  5292. \end{minipage}
  5293. $\Rightarrow\qquad$
  5294. \begin{minipage}{0.45\textwidth}
  5295. \begin{lstlisting}
  5296. movq $1, -8(%rbp)
  5297. movq $42, %rcx
  5298. addq $7, -8(%rbp)
  5299. movq -8(%rbp), %rax
  5300. movq %rax, -16(%rbp)
  5301. addq %rcx, -8(%rbp)
  5302. movq -16(%rbp), %rcx
  5303. negq %rcx
  5304. addq %rcx, -8(%rbp)
  5305. movq -8(%rbp), %rdi
  5306. callq print_int
  5307. \end{lstlisting}
  5308. \end{minipage}
  5309. \fi}
  5310. \end{center}
  5311. \begin{exercise}\normalfont\normalsize
  5312. %
  5313. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5314. %
  5315. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5316. %in the \code{run-tests.rkt} script.
  5317. %
  5318. Run the script to test the \code{patch\_instructions} pass.
  5319. \end{exercise}
  5320. \section{Prelude and Conclusion}
  5321. \label{sec:print-x86-reg-alloc}
  5322. \index{subject}{calling conventions}
  5323. \index{subject}{prelude}\index{subject}{conclusion}
  5324. Recall that this pass generates the prelude and conclusion
  5325. instructions to satisfy the x86 calling conventions
  5326. (Section~\ref{sec:calling-conventions}). With the addition of the
  5327. register allocator, the callee-saved registers used by the register
  5328. allocator must be saved in the prelude and restored in the conclusion.
  5329. In the \code{allocate\_registers} pass,
  5330. %
  5331. \racket{add an entry to the \itm{info}
  5332. of \code{X86Program} named \code{used\_callee}}
  5333. %
  5334. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5335. %
  5336. that stores the set of callee-saved registers that were assigned to
  5337. variables. The \code{prelude\_and\_conclusion} pass can then access
  5338. this information to decide which callee-saved registers need to be
  5339. saved and restored.
  5340. %
  5341. When calculating the amount to adjust the \code{rsp} in the prelude,
  5342. make sure to take into account the space used for saving the
  5343. callee-saved registers. Also, don't forget that the frame needs to be
  5344. a multiple of 16 bytes! We recommend using the following equation for
  5345. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5346. of spilled variables and $C$ be the number of callee-saved registers
  5347. that were allocated to variables. The $\itm{align}$ function rounds a
  5348. number up to the nearest 16 bytes.
  5349. \[
  5350. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5351. \]
  5352. The reason we subtract $8\itm{C}$ in the above equation is because the
  5353. prelude uses \code{pushq} to save each of the callee-saved registers,
  5354. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5355. \racket{An overview of all of the passes involved in register
  5356. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5357. {\if\edition\racketEd
  5358. \begin{figure}[tbp]
  5359. \begin{tcolorbox}[colback=white]
  5360. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5361. \node (Lvar) at (0,2) {\large \LangVar{}};
  5362. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5363. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5364. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5365. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5366. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5367. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5368. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5369. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5370. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5371. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5372. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5373. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5374. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5375. \path[->,bend left=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5376. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5377. \path[->,bend right=15] (x86-2-2) edge [left] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5378. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5379. \path[->,bend left=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5380. \end{tikzpicture}
  5381. \end{tcolorbox}
  5382. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5383. \label{fig:reg-alloc-passes}
  5384. \end{figure}
  5385. \fi}
  5386. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5387. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5388. use of registers and the stack, we limit the register allocator for
  5389. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5390. the prelude\index{subject}{prelude} of the \code{main} function, we
  5391. push \code{rbx} onto the stack because it is a callee-saved register
  5392. and it was assigned to a variable by the register allocator. We
  5393. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5394. reserve space for the one spilled variable. After that subtraction,
  5395. the \code{rsp} is aligned to 16 bytes.
  5396. Moving on to the program proper, we see how the registers were
  5397. allocated.
  5398. %
  5399. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5400. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5401. %
  5402. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5403. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5404. were assigned to \code{rbx}.}
  5405. %
  5406. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5407. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5408. callee-save register \code{rbx} onto the stack. The spilled variables
  5409. must be placed lower on the stack than the saved callee-save
  5410. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5411. \code{-16(\%rbp)}.
  5412. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5413. done in the prelude. We move the stack pointer up by \code{8} bytes
  5414. (the room for spilled variables), then we pop the old values of
  5415. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5416. \code{retq} to return control to the operating system.
  5417. \begin{figure}[tbp]
  5418. \begin{minipage}{0.55\textwidth}
  5419. \begin{tcolorbox}[colback=white]
  5420. % var_test_28.rkt
  5421. % (use-minimal-set-of-registers! #t)
  5422. % and only rbx rcx
  5423. % tmp 0 rbx
  5424. % z 1 rcx
  5425. % y 0 rbx
  5426. % w 2 16(%rbp)
  5427. % v 0 rbx
  5428. % x 0 rbx
  5429. {\if\edition\racketEd
  5430. \begin{lstlisting}
  5431. start:
  5432. movq $1, %rbx
  5433. movq $42, -16(%rbp)
  5434. addq $7, %rbx
  5435. movq %rbx, %rcx
  5436. addq -16(%rbp), %rcx
  5437. negq %rbx
  5438. movq %rcx, %rax
  5439. addq %rbx, %rax
  5440. jmp conclusion
  5441. .globl main
  5442. main:
  5443. pushq %rbp
  5444. movq %rsp, %rbp
  5445. pushq %rbx
  5446. subq $8, %rsp
  5447. jmp start
  5448. conclusion:
  5449. addq $8, %rsp
  5450. popq %rbx
  5451. popq %rbp
  5452. retq
  5453. \end{lstlisting}
  5454. \fi}
  5455. {\if\edition\pythonEd
  5456. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5457. \begin{lstlisting}
  5458. .globl main
  5459. main:
  5460. pushq %rbp
  5461. movq %rsp, %rbp
  5462. pushq %rbx
  5463. subq $8, %rsp
  5464. movq $1, %rcx
  5465. movq $42, %rbx
  5466. addq $7, %rcx
  5467. movq %rcx, -16(%rbp)
  5468. addq %rbx, -16(%rbp)
  5469. negq %rcx
  5470. movq -16(%rbp), %rbx
  5471. addq %rcx, %rbx
  5472. movq %rbx, %rdi
  5473. callq print_int
  5474. addq $8, %rsp
  5475. popq %rbx
  5476. popq %rbp
  5477. retq
  5478. \end{lstlisting}
  5479. \fi}
  5480. \end{tcolorbox}
  5481. \end{minipage}
  5482. \caption{The x86 output from the running example
  5483. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5484. and \code{rcx}.}
  5485. \label{fig:running-example-x86}
  5486. \end{figure}
  5487. \begin{exercise}\normalfont\normalsize
  5488. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5489. %
  5490. \racket{
  5491. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5492. list of passes and the call to \code{compiler-tests}.}
  5493. %
  5494. Run the script to test the complete compiler for \LangVar{} that
  5495. performs register allocation.
  5496. \end{exercise}
  5497. \section{Challenge: Move Biasing}
  5498. \label{sec:move-biasing}
  5499. \index{subject}{move biasing}
  5500. This section describes an enhancement to the register allocator,
  5501. called move biasing, for students who are looking for an extra
  5502. challenge.
  5503. {\if\edition\racketEd
  5504. To motivate the need for move biasing we return to the running example
  5505. but this time we use all of the general purpose registers. So we have
  5506. the following mapping of color numbers to registers.
  5507. \[
  5508. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5509. \]
  5510. Using the same assignment of variables to color numbers that was
  5511. produced by the register allocator described in the last section, we
  5512. get the following program.
  5513. \begin{center}
  5514. \begin{minipage}{0.3\textwidth}
  5515. \begin{lstlisting}
  5516. movq $1, v
  5517. movq $42, w
  5518. movq v, x
  5519. addq $7, x
  5520. movq x, y
  5521. movq x, z
  5522. addq w, z
  5523. movq y, t
  5524. negq t
  5525. movq z, %rax
  5526. addq t, %rax
  5527. jmp conclusion
  5528. \end{lstlisting}
  5529. \end{minipage}
  5530. $\Rightarrow\qquad$
  5531. \begin{minipage}{0.45\textwidth}
  5532. \begin{lstlisting}
  5533. movq $1, %rdx
  5534. movq $42, %rcx
  5535. movq %rdx, %rdx
  5536. addq $7, %rdx
  5537. movq %rdx, %rsi
  5538. movq %rdx, %rdx
  5539. addq %rcx, %rdx
  5540. movq %rsi, %rcx
  5541. negq %rcx
  5542. movq %rdx, %rax
  5543. addq %rcx, %rax
  5544. jmp conclusion
  5545. \end{lstlisting}
  5546. \end{minipage}
  5547. \end{center}
  5548. In the above output code there are two \key{movq} instructions that
  5549. can be removed because their source and target are the same. However,
  5550. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5551. register, we could instead remove three \key{movq} instructions. We
  5552. can accomplish this by taking into account which variables appear in
  5553. \key{movq} instructions with which other variables.
  5554. \fi}
  5555. {\if\edition\pythonEd
  5556. %
  5557. To motivate the need for move biasing we return to the running example
  5558. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5559. remove three trivial move instructions from the running
  5560. example. However, we could remove another trivial move if we were able
  5561. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5562. We say that two variables $p$ and $q$ are \emph{move
  5563. related}\index{subject}{move related} if they participate together in
  5564. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5565. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5566. when there are multiple variables with the same saturation, prefer
  5567. variables that can be assigned to a color that is the same as the
  5568. color of a move related variable. Furthermore, when the register
  5569. allocator chooses a color for a variable, it should prefer a color
  5570. that has already been used for a move-related variable (assuming that
  5571. they do not interfere). Of course, this preference should not override
  5572. the preference for registers over stack locations. So this preference
  5573. should be used as a tie breaker when choosing between registers or
  5574. when choosing between stack locations.
  5575. We recommend representing the move relationships in a graph, similar
  5576. to how we represented interference. The following is the \emph{move
  5577. graph} for our running example.
  5578. {\if\edition\racketEd
  5579. \[
  5580. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5581. \node (rax) at (0,0) {$\ttm{rax}$};
  5582. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5583. \node (t) at (0,2) {$\ttm{t}$};
  5584. \node (z) at (3,2) {$\ttm{z}$};
  5585. \node (x) at (6,2) {$\ttm{x}$};
  5586. \node (y) at (3,0) {$\ttm{y}$};
  5587. \node (w) at (6,0) {$\ttm{w}$};
  5588. \node (v) at (9,0) {$\ttm{v}$};
  5589. \draw (v) to (x);
  5590. \draw (x) to (y);
  5591. \draw (x) to (z);
  5592. \draw (y) to (t);
  5593. \end{tikzpicture}
  5594. \]
  5595. \fi}
  5596. %
  5597. {\if\edition\pythonEd
  5598. \[
  5599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5600. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5601. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5602. \node (z) at (3,2) {$\ttm{z}$};
  5603. \node (x) at (6,2) {$\ttm{x}$};
  5604. \node (y) at (3,0) {$\ttm{y}$};
  5605. \node (w) at (6,0) {$\ttm{w}$};
  5606. \node (v) at (9,0) {$\ttm{v}$};
  5607. \draw (y) to (t0);
  5608. \draw (z) to (x);
  5609. \draw (z) to (t1);
  5610. \draw (x) to (y);
  5611. \draw (x) to (v);
  5612. \end{tikzpicture}
  5613. \]
  5614. \fi}
  5615. {\if\edition\racketEd
  5616. Now we replay the graph coloring, pausing to see the coloring of
  5617. \code{y}. Recall the following configuration. The most saturated vertices
  5618. were \code{w} and \code{y}.
  5619. \[
  5620. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5621. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5622. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5623. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5624. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5625. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5626. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5627. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5628. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5629. \draw (t1) to (rax);
  5630. \draw (t1) to (z);
  5631. \draw (z) to (y);
  5632. \draw (z) to (w);
  5633. \draw (x) to (w);
  5634. \draw (y) to (w);
  5635. \draw (v) to (w);
  5636. \draw (v) to (rsp);
  5637. \draw (w) to (rsp);
  5638. \draw (x) to (rsp);
  5639. \draw (y) to (rsp);
  5640. \path[-.,bend left=15] (z) edge node {} (rsp);
  5641. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5642. \draw (rax) to (rsp);
  5643. \end{tikzpicture}
  5644. \]
  5645. %
  5646. Last time we chose to color \code{w} with $0$. But this time we see
  5647. that \code{w} is not move related to any vertex, but \code{y} is move
  5648. related to \code{t}. So we choose to color \code{y} with $0$, the
  5649. same color as \code{t}.
  5650. \[
  5651. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5652. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5653. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5654. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5655. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5656. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5657. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5658. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5659. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5660. \draw (t1) to (rax);
  5661. \draw (t1) to (z);
  5662. \draw (z) to (y);
  5663. \draw (z) to (w);
  5664. \draw (x) to (w);
  5665. \draw (y) to (w);
  5666. \draw (v) to (w);
  5667. \draw (v) to (rsp);
  5668. \draw (w) to (rsp);
  5669. \draw (x) to (rsp);
  5670. \draw (y) to (rsp);
  5671. \path[-.,bend left=15] (z) edge node {} (rsp);
  5672. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5673. \draw (rax) to (rsp);
  5674. \end{tikzpicture}
  5675. \]
  5676. Now \code{w} is the most saturated, so we color it $2$.
  5677. \[
  5678. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5679. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5680. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5681. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5682. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5683. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5684. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5685. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5686. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5687. \draw (t1) to (rax);
  5688. \draw (t1) to (z);
  5689. \draw (z) to (y);
  5690. \draw (z) to (w);
  5691. \draw (x) to (w);
  5692. \draw (y) to (w);
  5693. \draw (v) to (w);
  5694. \draw (v) to (rsp);
  5695. \draw (w) to (rsp);
  5696. \draw (x) to (rsp);
  5697. \draw (y) to (rsp);
  5698. \path[-.,bend left=15] (z) edge node {} (rsp);
  5699. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5700. \draw (rax) to (rsp);
  5701. \end{tikzpicture}
  5702. \]
  5703. At this point, vertices \code{x} and \code{v} are most saturated, but
  5704. \code{x} is move related to \code{y} and \code{z}, so we color
  5705. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5706. \[
  5707. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5708. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5709. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5710. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5711. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5712. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5713. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5714. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5715. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5716. \draw (t1) to (rax);
  5717. \draw (t) to (z);
  5718. \draw (z) to (y);
  5719. \draw (z) to (w);
  5720. \draw (x) to (w);
  5721. \draw (y) to (w);
  5722. \draw (v) to (w);
  5723. \draw (v) to (rsp);
  5724. \draw (w) to (rsp);
  5725. \draw (x) to (rsp);
  5726. \draw (y) to (rsp);
  5727. \path[-.,bend left=15] (z) edge node {} (rsp);
  5728. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5729. \draw (rax) to (rsp);
  5730. \end{tikzpicture}
  5731. \]
  5732. \fi}
  5733. %
  5734. {\if\edition\pythonEd
  5735. Now we replay the graph coloring, pausing before the coloring of
  5736. \code{w}. Recall the following configuration. The most saturated vertices
  5737. were \code{tmp\_1}, \code{w}, and \code{y}.
  5738. \[
  5739. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5740. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5741. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5742. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5743. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5744. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5745. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5746. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5747. \draw (t0) to (t1);
  5748. \draw (t0) to (z);
  5749. \draw (z) to (y);
  5750. \draw (z) to (w);
  5751. \draw (x) to (w);
  5752. \draw (y) to (w);
  5753. \draw (v) to (w);
  5754. \end{tikzpicture}
  5755. \]
  5756. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5757. or \code{y}, but note that \code{w} is not move related to any
  5758. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5759. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5760. \code{y} and color it $0$, we can delete another move instruction.
  5761. \[
  5762. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5763. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5764. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5765. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5766. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5767. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5768. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5769. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5770. \draw (t0) to (t1);
  5771. \draw (t0) to (z);
  5772. \draw (z) to (y);
  5773. \draw (z) to (w);
  5774. \draw (x) to (w);
  5775. \draw (y) to (w);
  5776. \draw (v) to (w);
  5777. \end{tikzpicture}
  5778. \]
  5779. Now \code{w} is the most saturated, so we color it $2$.
  5780. \[
  5781. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5782. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5783. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5784. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5785. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5786. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5787. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5788. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5789. \draw (t0) to (t1);
  5790. \draw (t0) to (z);
  5791. \draw (z) to (y);
  5792. \draw (z) to (w);
  5793. \draw (x) to (w);
  5794. \draw (y) to (w);
  5795. \draw (v) to (w);
  5796. \end{tikzpicture}
  5797. \]
  5798. To finish the coloring, \code{x} and \code{v} get $0$ and
  5799. \code{tmp\_1} gets $1$.
  5800. \[
  5801. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5802. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5803. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5804. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5805. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5806. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5807. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5808. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5809. \draw (t0) to (t1);
  5810. \draw (t0) to (z);
  5811. \draw (z) to (y);
  5812. \draw (z) to (w);
  5813. \draw (x) to (w);
  5814. \draw (y) to (w);
  5815. \draw (v) to (w);
  5816. \end{tikzpicture}
  5817. \]
  5818. \fi}
  5819. So we have the following assignment of variables to registers.
  5820. {\if\edition\racketEd
  5821. \begin{gather*}
  5822. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5823. \ttm{w} \mapsto \key{\%rsi}, \,
  5824. \ttm{x} \mapsto \key{\%rcx}, \,
  5825. \ttm{y} \mapsto \key{\%rcx}, \,
  5826. \ttm{z} \mapsto \key{\%rdx}, \,
  5827. \ttm{t} \mapsto \key{\%rcx} \}
  5828. \end{gather*}
  5829. \fi}
  5830. {\if\edition\pythonEd
  5831. \begin{gather*}
  5832. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5833. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5834. \ttm{x} \mapsto \key{\%rcx}, \,
  5835. \ttm{y} \mapsto \key{\%rcx}, \\
  5836. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5837. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5838. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5839. \end{gather*}
  5840. \fi}
  5841. We apply this register assignment to the running example, on the left,
  5842. to obtain the code in the middle. The \code{patch\_instructions} then
  5843. deletes the trivial moves to obtain the code on the right.
  5844. {\if\edition\racketEd
  5845. \begin{minipage}{0.25\textwidth}
  5846. \begin{lstlisting}
  5847. movq $1, v
  5848. movq $42, w
  5849. movq v, x
  5850. addq $7, x
  5851. movq x, y
  5852. movq x, z
  5853. addq w, z
  5854. movq y, t
  5855. negq t
  5856. movq z, %rax
  5857. addq t, %rax
  5858. jmp conclusion
  5859. \end{lstlisting}
  5860. \end{minipage}
  5861. $\Rightarrow\qquad$
  5862. \begin{minipage}{0.25\textwidth}
  5863. \begin{lstlisting}
  5864. movq $1, %rcx
  5865. movq $42, %rsi
  5866. movq %rcx, %rcx
  5867. addq $7, %rcx
  5868. movq %rcx, %rcx
  5869. movq %rcx, %rdx
  5870. addq %rsi, %rdx
  5871. movq %rcx, %rcx
  5872. negq %rcx
  5873. movq %rdx, %rax
  5874. addq %rcx, %rax
  5875. jmp conclusion
  5876. \end{lstlisting}
  5877. \end{minipage}
  5878. $\Rightarrow\qquad$
  5879. \begin{minipage}{0.25\textwidth}
  5880. \begin{lstlisting}
  5881. movq $1, %rcx
  5882. movq $42, %rsi
  5883. addq $7, %rcx
  5884. movq %rcx, %rdx
  5885. addq %rsi, %rdx
  5886. negq %rcx
  5887. movq %rdx, %rax
  5888. addq %rcx, %rax
  5889. jmp conclusion
  5890. \end{lstlisting}
  5891. \end{minipage}
  5892. \fi}
  5893. {\if\edition\pythonEd
  5894. \begin{minipage}{0.20\textwidth}
  5895. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5896. movq $1, v
  5897. movq $42, w
  5898. movq v, x
  5899. addq $7, x
  5900. movq x, y
  5901. movq x, z
  5902. addq w, z
  5903. movq y, tmp_0
  5904. negq tmp_0
  5905. movq z, tmp_1
  5906. addq tmp_0, tmp_1
  5907. movq tmp_1, %rdi
  5908. callq _print_int
  5909. \end{lstlisting}
  5910. \end{minipage}
  5911. ${\Rightarrow\qquad}$
  5912. \begin{minipage}{0.30\textwidth}
  5913. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5914. movq $1, %rcx
  5915. movq $42, -16(%rbp)
  5916. movq %rcx, %rcx
  5917. addq $7, %rcx
  5918. movq %rcx, %rcx
  5919. movq %rcx, -8(%rbp)
  5920. addq -16(%rbp), -8(%rbp)
  5921. movq %rcx, %rcx
  5922. negq %rcx
  5923. movq -8(%rbp), -8(%rbp)
  5924. addq %rcx, -8(%rbp)
  5925. movq -8(%rbp), %rdi
  5926. callq _print_int
  5927. \end{lstlisting}
  5928. \end{minipage}
  5929. ${\Rightarrow\qquad}$
  5930. \begin{minipage}{0.20\textwidth}
  5931. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5932. movq $1, %rcx
  5933. movq $42, -16(%rbp)
  5934. addq $7, %rcx
  5935. movq %rcx, -8(%rbp)
  5936. movq -16(%rbp), %rax
  5937. addq %rax, -8(%rbp)
  5938. negq %rcx
  5939. addq %rcx, -8(%rbp)
  5940. movq -8(%rbp), %rdi
  5941. callq print_int
  5942. \end{lstlisting}
  5943. \end{minipage}
  5944. \fi}
  5945. \begin{exercise}\normalfont\normalsize
  5946. Change your implementation of \code{allocate\_registers} to take move
  5947. biasing into account. Create two new tests that include at least one
  5948. opportunity for move biasing and visually inspect the output x86
  5949. programs to make sure that your move biasing is working properly. Make
  5950. sure that your compiler still passes all of the tests.
  5951. \end{exercise}
  5952. %To do: another neat challenge would be to do
  5953. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5954. %% \subsection{Output of the Running Example}
  5955. %% \label{sec:reg-alloc-output}
  5956. % challenge: prioritize variables based on execution frequencies
  5957. % and the number of uses of a variable
  5958. % challenge: enhance the coloring algorithm using Chaitin's
  5959. % approach of prioritizing high-degree variables
  5960. % by removing low-degree variables (coloring them later)
  5961. % from the interference graph
  5962. \section{Further Reading}
  5963. \label{sec:register-allocation-further-reading}
  5964. Early register allocation algorithms were developed for Fortran
  5965. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5966. of graph coloring began in the late 1970s and early 1980s with the
  5967. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5968. algorithm is based on the following observation of
  5969. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5970. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5971. $v$ removed is also $k$ colorable. To see why, suppose that the
  5972. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5973. different colors, but since there are less than $k$ neighbors, there
  5974. will be one or more colors left over to use for coloring $v$ in $G$.
  5975. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5976. less than $k$ from the graph and recursively colors the rest of the
  5977. graph. Upon returning from the recursion, it colors $v$ with one of
  5978. the available colors and returns. \citet{Chaitin:1982vn} augments
  5979. this algorithm to handle spilling as follows. If there are no vertices
  5980. of degree lower than $k$ then pick a vertex at random, spill it,
  5981. remove it from the graph, and proceed recursively to color the rest of
  5982. the graph.
  5983. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5984. move-related and that don't interfere with each other, a process
  5985. called \emph{coalescing}. While coalescing decreases the number of
  5986. moves, it can make the graph more difficult to
  5987. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5988. which two variables are merged only if they have fewer than $k$
  5989. neighbors of high degree. \citet{George:1996aa} observe that
  5990. conservative coalescing is sometimes too conservative and make it more
  5991. aggressive by iterating the coalescing with the removal of low-degree
  5992. vertices.
  5993. %
  5994. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5995. also propose \emph{biased coloring} in which a variable is assigned to
  5996. the same color as another move-related variable if possible, as
  5997. discussed in Section~\ref{sec:move-biasing}.
  5998. %
  5999. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6000. performs coalescing, graph coloring, and spill code insertion until
  6001. all variables have been assigned a location.
  6002. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6003. spills variables that don't have to be: a high-degree variable can be
  6004. colorable if many of its neighbors are assigned the same color.
  6005. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  6006. high-degree vertex is not immediately spilled. Instead the decision is
  6007. deferred until after the recursive call, at which point it is apparent
  6008. whether there is actually an available color or not. We observe that
  6009. this algorithm is equivalent to the smallest-last ordering
  6010. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6011. be registers and the rest to be stack locations.
  6012. %% biased coloring
  6013. Earlier editions of the compiler course at Indiana University
  6014. \citep{Dybvig:2010aa} were based on the algorithm of
  6015. \citet{Briggs:1994kx}.
  6016. The smallest-last ordering algorithm is one of many \emph{greedy}
  6017. coloring algorithms. A greedy coloring algorithm visits all the
  6018. vertices in a particular order and assigns each one the first
  6019. available color. An \emph{offline} greedy algorithm chooses the
  6020. ordering up-front, prior to assigning colors. The algorithm of
  6021. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6022. ordering does not depend on the colors assigned. Other orderings are
  6023. possible. For example, \citet{Chow:1984ys} order variables according
  6024. to an estimate of runtime cost.
  6025. An \emph{online} greedy coloring algorithm uses information about the
  6026. current assignment of colors to influence the order in which the
  6027. remaining vertices are colored. The saturation-based algorithm
  6028. described in this chapter is one such algorithm. We choose to use
  6029. saturation-based coloring because it is fun to introduce graph
  6030. coloring via Sudoku!
  6031. A register allocator may choose to map each variable to just one
  6032. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6033. variable to one or more locations. The later can be achieved by
  6034. \emph{live range splitting}, where a variable is replaced by several
  6035. variables that each handle part of its live
  6036. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6037. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6038. %% replacement algorithm, bottom-up local
  6039. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6040. %% Cooper: top-down (priority bassed), bottom-up
  6041. %% top-down
  6042. %% order variables by priority (estimated cost)
  6043. %% caveat: split variables into two groups:
  6044. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6045. %% color the constrained ones first
  6046. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6047. %% cite J. Cocke for an algorithm that colors variables
  6048. %% in a high-degree first ordering
  6049. %Register Allocation via Usage Counts, Freiburghouse CACM
  6050. \citet{Palsberg:2007si} observe that many of the interference graphs
  6051. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  6052. that is, every cycle with four or more edges has an edge which is not
  6053. part of the cycle but which connects two vertices on the cycle. Such
  6054. graphs can be optimally colored by the greedy algorithm with a vertex
  6055. ordering determined by maximum cardinality search.
  6056. In situations where compile time is of utmost importance, such as in
  6057. just-in-time compilers, graph coloring algorithms can be too expensive
  6058. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  6059. appropriate.
  6060. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6061. \chapter{Booleans and Conditionals}
  6062. \label{ch:Lif}
  6063. \index{subject}{Boolean}
  6064. \index{subject}{control flow}
  6065. \index{subject}{conditional expression}
  6066. The \LangVar{} language only has a single kind of value, the
  6067. integers. In this chapter we add a second kind of value, the Booleans,
  6068. to create the \LangIf{} language. The Boolean values \emph{true} and
  6069. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6070. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6071. several operations that involve Booleans (\key{and}, \key{not},
  6072. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6073. expression \python{and statement}. With the addition of \key{if},
  6074. programs can have non-trivial control flow which
  6075. %
  6076. \racket{impacts \code{explicate\_control} and liveness analysis}
  6077. %
  6078. \python{impacts liveness analysis and motivates a new pass named
  6079. \code{explicate\_control}}.
  6080. %
  6081. Also, because we now have two kinds of values, we need to handle
  6082. programs that apply an operation to the wrong kind of value, such as
  6083. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6084. There are two language design options for such situations. One option
  6085. is to signal an error and the other is to provide a wider
  6086. interpretation of the operation. \racket{The Racket
  6087. language}\python{Python} uses a mixture of these two options,
  6088. depending on the operation and the kind of value. For example, the
  6089. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6090. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6091. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6092. %
  6093. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6094. in Racket because \code{car} expects a pair.}
  6095. %
  6096. \python{On the other hand, \code{1[0]} results in a run-time error
  6097. in Python because an ``\code{int} object is not subscriptable''.}
  6098. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6099. design choices as \racket{Racket}\python{Python}, except much of the
  6100. error detection happens at compile time instead of run
  6101. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6102. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6103. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6104. Racket}\python{MyPy} reports a compile-time error
  6105. %
  6106. \racket{because Racket expects the type of the argument to be of the form
  6107. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6108. %
  6109. \python{stating that a ``value of type \code{int} is not indexable''.}
  6110. The \LangIf{} language performs type checking during compilation like
  6111. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6112. the alternative choice, that is, a dynamically typed language like
  6113. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6114. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6115. restrictive, for example, rejecting \racket{\code{(not
  6116. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6117. fairly simple because the focus of this book is on compilation, not
  6118. type systems, about which there are already several excellent
  6119. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6120. This chapter is organized as follows. We begin by defining the syntax
  6121. and interpreter for the \LangIf{} language
  6122. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6123. checking and define a type checker for \LangIf{}
  6124. (Section~\ref{sec:type-check-Lif}).
  6125. %
  6126. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6127. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6128. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6129. %
  6130. The remaining sections of this chapter discuss how Booleans and
  6131. conditional control flow require changes to the existing compiler
  6132. passes and the addition of new ones. We introduce the \code{shrink}
  6133. pass to translates some operators into others, thereby reducing the
  6134. number of operators that need to be handled in later passes.
  6135. %
  6136. The main event of this chapter is the \code{explicate\_control} pass
  6137. that is responsible for translating \code{if}'s into conditional
  6138. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6139. %
  6140. Regarding register allocation, there is the interesting question of
  6141. how to handle conditional \code{goto}'s during liveness analysis.
  6142. \section{The \LangIf{} Language}
  6143. \label{sec:lang-if}
  6144. The concrete and abstract syntax of the \LangIf{} language are defined in
  6145. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6146. respectively. The \LangIf{} language includes all of
  6147. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6148. \FALSE{}, \racket{and} the \code{if} expression%
  6149. \python{, and the \code{if} statement}.
  6150. We expand the set of operators to include
  6151. \begin{enumerate}
  6152. \item the logical operators \key{and}, \key{or}, and \key{not},
  6153. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6154. for comparing integers or Booleans for equality, and
  6155. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6156. comparing integers.
  6157. \end{enumerate}
  6158. \racket{We reorganize the abstract syntax for the primitive
  6159. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6160. rule for all of them. This means that the grammar no longer checks
  6161. whether the arity of an operators matches the number of
  6162. arguments. That responsibility is moved to the type checker for
  6163. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6164. \newcommand{\LifGrammarRacket}{
  6165. \begin{array}{lcl}
  6166. \Type &::=& \key{Boolean} \\
  6167. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6168. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6169. \Exp &::=& \itm{bool}
  6170. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6171. \MID (\key{not}\;\Exp) \\
  6172. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6173. \end{array}
  6174. }
  6175. \newcommand{\LifASTRacket}{
  6176. \begin{array}{lcl}
  6177. \Type &::=& \key{Boolean} \\
  6178. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6179. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6180. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6181. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6182. \end{array}
  6183. }
  6184. \newcommand{\LintOpAST}{
  6185. \begin{array}{rcl}
  6186. \Type &::=& \key{Integer} \\
  6187. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6188. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6189. \end{array}
  6190. }
  6191. \newcommand{\LifGrammarPython}{
  6192. \begin{array}{rcl}
  6193. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6194. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6195. \MID \key{not}~\Exp \\
  6196. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6197. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6198. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6199. \end{array}
  6200. }
  6201. \newcommand{\LifASTPython}{
  6202. \begin{array}{lcl}
  6203. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6204. \itm{unaryop} &::=& \code{Not()} \\
  6205. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6206. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6207. \Exp &::=& \BOOL{\itm{bool}}
  6208. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6209. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6210. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6211. \end{array}
  6212. }
  6213. \begin{figure}[tp]
  6214. \centering
  6215. \begin{tcolorbox}[colback=white]
  6216. {\if\edition\racketEd
  6217. \[
  6218. \begin{array}{l}
  6219. \gray{\LintGrammarRacket{}} \\ \hline
  6220. \gray{\LvarGrammarRacket{}} \\ \hline
  6221. \LifGrammarRacket{} \\
  6222. \begin{array}{lcl}
  6223. \LangIfM{} &::=& \Exp
  6224. \end{array}
  6225. \end{array}
  6226. \]
  6227. \fi}
  6228. {\if\edition\pythonEd
  6229. \[
  6230. \begin{array}{l}
  6231. \gray{\LintGrammarPython} \\ \hline
  6232. \gray{\LvarGrammarPython} \\ \hline
  6233. \LifGrammarPython \\
  6234. \begin{array}{rcl}
  6235. \LangIfM{} &::=& \Stmt^{*}
  6236. \end{array}
  6237. \end{array}
  6238. \]
  6239. \fi}
  6240. \end{tcolorbox}
  6241. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6242. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6243. \label{fig:Lif-concrete-syntax}
  6244. \end{figure}
  6245. \begin{figure}[tp]
  6246. %\begin{minipage}{0.66\textwidth}
  6247. \begin{tcolorbox}[colback=white]
  6248. \centering
  6249. {\if\edition\racketEd
  6250. \[
  6251. \begin{array}{l}
  6252. \gray{\LintOpAST} \\ \hline
  6253. \gray{\LvarASTRacket{}} \\ \hline
  6254. \LifASTRacket{} \\
  6255. \begin{array}{lcl}
  6256. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6257. \end{array}
  6258. \end{array}
  6259. \]
  6260. \fi}
  6261. {\if\edition\pythonEd
  6262. \[
  6263. \begin{array}{l}
  6264. \gray{\LintASTPython} \\ \hline
  6265. \gray{\LvarASTPython} \\ \hline
  6266. \LifASTPython \\
  6267. \begin{array}{lcl}
  6268. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6269. \end{array}
  6270. \end{array}
  6271. \]
  6272. \fi}
  6273. \end{tcolorbox}
  6274. %\end{minipage}
  6275. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6276. \index{subject}{IfExp@\IFNAME{}}
  6277. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6278. \index{subject}{and@\ANDNAME{}}
  6279. \index{subject}{or@\ORNAME{}}
  6280. \index{subject}{not@\NOTNAME{}}
  6281. \index{subject}{equal@\EQNAME{}}
  6282. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6283. \racket{
  6284. \index{subject}{lessthan@\texttt{<}}
  6285. \index{subject}{lessthaneq@\texttt{<=}}
  6286. \index{subject}{greaterthan@\texttt{>}}
  6287. \index{subject}{greaterthaneq@\texttt{>=}}
  6288. }
  6289. \python{
  6290. \index{subject}{BoolOp@\texttt{BoolOp}}
  6291. \index{subject}{Compare@\texttt{Compare}}
  6292. \index{subject}{Lt@\texttt{Lt}}
  6293. \index{subject}{LtE@\texttt{LtE}}
  6294. \index{subject}{Gt@\texttt{Gt}}
  6295. \index{subject}{GtE@\texttt{GtE}}
  6296. }
  6297. \caption{The abstract syntax of \LangIf{}.}
  6298. \label{fig:Lif-syntax}
  6299. \end{figure}
  6300. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6301. which inherits from the interpreter for \LangVar{}
  6302. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6303. evaluate to the corresponding Boolean values. The conditional
  6304. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6305. and then either evaluates $e_2$ or $e_3$ depending on whether
  6306. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6307. \code{and}, \code{or}, and \code{not} behave according to
  6308. propositional logic. In addition, the \code{and} and \code{or}
  6309. operations perform \emph{short-circuit evaluation}.
  6310. %
  6311. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6312. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6313. %
  6314. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6315. evaluated if $e_1$ evaluates to \TRUE{}.
  6316. \racket{With the increase in the number of primitive operations, the
  6317. interpreter would become repetitive without some care. We refactor
  6318. the case for \code{Prim}, moving the code that differs with each
  6319. operation into the \code{interp\_op} method shown in in
  6320. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6321. \code{or} operations separately because of their short-circuiting
  6322. behavior.}
  6323. \begin{figure}[tbp]
  6324. \begin{tcolorbox}[colback=white]
  6325. {\if\edition\racketEd
  6326. \begin{lstlisting}
  6327. (define interp-Lif-class
  6328. (class interp-Lvar-class
  6329. (super-new)
  6330. (define/public (interp_op op) ...)
  6331. (define/override ((interp_exp env) e)
  6332. (define recur (interp_exp env))
  6333. (match e
  6334. [(Bool b) b]
  6335. [(If cnd thn els)
  6336. (match (recur cnd)
  6337. [#t (recur thn)]
  6338. [#f (recur els)])]
  6339. [(Prim 'and (list e1 e2))
  6340. (match (recur e1)
  6341. [#t (match (recur e2) [#t #t] [#f #f])]
  6342. [#f #f])]
  6343. [(Prim 'or (list e1 e2))
  6344. (define v1 (recur e1))
  6345. (match v1
  6346. [#t #t]
  6347. [#f (match (recur e2) [#t #t] [#f #f])])]
  6348. [(Prim op args)
  6349. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6350. [else ((super interp_exp env) e)]))
  6351. ))
  6352. (define (interp_Lif p)
  6353. (send (new interp-Lif-class) interp_program p))
  6354. \end{lstlisting}
  6355. \fi}
  6356. {\if\edition\pythonEd
  6357. \begin{lstlisting}
  6358. class InterpLif(InterpLvar):
  6359. def interp_exp(self, e, env):
  6360. match e:
  6361. case IfExp(test, body, orelse):
  6362. if self.interp_exp(test, env):
  6363. return self.interp_exp(body, env)
  6364. else:
  6365. return self.interp_exp(orelse, env)
  6366. case UnaryOp(Not(), v):
  6367. return not self.interp_exp(v, env)
  6368. case BoolOp(And(), values):
  6369. if self.interp_exp(values[0], env):
  6370. return self.interp_exp(values[1], env)
  6371. else:
  6372. return False
  6373. case BoolOp(Or(), values):
  6374. if self.interp_exp(values[0], env):
  6375. return True
  6376. else:
  6377. return self.interp_exp(values[1], env)
  6378. case Compare(left, [cmp], [right]):
  6379. l = self.interp_exp(left, env)
  6380. r = self.interp_exp(right, env)
  6381. return self.interp_cmp(cmp)(l, r)
  6382. case _:
  6383. return super().interp_exp(e, env)
  6384. def interp_stmts(self, ss, env):
  6385. if len(ss) == 0:
  6386. return
  6387. match ss[0]:
  6388. case If(test, body, orelse):
  6389. if self.interp_exp(test, env):
  6390. return self.interp_stmts(body + ss[1:], env)
  6391. else:
  6392. return self.interp_stmts(orelse + ss[1:], env)
  6393. case _:
  6394. return super().interp_stmts(ss, env)
  6395. ...
  6396. \end{lstlisting}
  6397. \fi}
  6398. \end{tcolorbox}
  6399. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6400. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6401. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6402. \label{fig:interp-Lif}
  6403. \end{figure}
  6404. {\if\edition\racketEd
  6405. \begin{figure}[tbp]
  6406. \begin{tcolorbox}[colback=white]
  6407. \begin{lstlisting}
  6408. (define/public (interp_op op)
  6409. (match op
  6410. ['+ fx+]
  6411. ['- fx-]
  6412. ['read read-fixnum]
  6413. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6414. ['eq? (lambda (v1 v2)
  6415. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6416. (and (boolean? v1) (boolean? v2))
  6417. (and (vector? v1) (vector? v2)))
  6418. (eq? v1 v2)]))]
  6419. ['< (lambda (v1 v2)
  6420. (cond [(and (fixnum? v1) (fixnum? v2))
  6421. (< v1 v2)]))]
  6422. ['<= (lambda (v1 v2)
  6423. (cond [(and (fixnum? v1) (fixnum? v2))
  6424. (<= v1 v2)]))]
  6425. ['> (lambda (v1 v2)
  6426. (cond [(and (fixnum? v1) (fixnum? v2))
  6427. (> v1 v2)]))]
  6428. ['>= (lambda (v1 v2)
  6429. (cond [(and (fixnum? v1) (fixnum? v2))
  6430. (>= v1 v2)]))]
  6431. [else (error 'interp_op "unknown operator")]))
  6432. \end{lstlisting}
  6433. \end{tcolorbox}
  6434. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6435. \label{fig:interp-op-Lif}
  6436. \end{figure}
  6437. \fi}
  6438. {\if\edition\pythonEd
  6439. \begin{figure}
  6440. \begin{tcolorbox}[colback=white]
  6441. \begin{lstlisting}
  6442. class InterpLif(InterpLvar):
  6443. ...
  6444. def interp_cmp(self, cmp):
  6445. match cmp:
  6446. case Lt():
  6447. return lambda x, y: x < y
  6448. case LtE():
  6449. return lambda x, y: x <= y
  6450. case Gt():
  6451. return lambda x, y: x > y
  6452. case GtE():
  6453. return lambda x, y: x >= y
  6454. case Eq():
  6455. return lambda x, y: x == y
  6456. case NotEq():
  6457. return lambda x, y: x != y
  6458. \end{lstlisting}
  6459. \end{tcolorbox}
  6460. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6461. \label{fig:interp-cmp-Lif}
  6462. \end{figure}
  6463. \fi}
  6464. \section{Type Checking \LangIf{} Programs}
  6465. \label{sec:type-check-Lif}
  6466. \index{subject}{type checking}
  6467. \index{subject}{semantic analysis}
  6468. It is helpful to think about type checking in two complementary
  6469. ways. A type checker predicts the type of value that will be produced
  6470. by each expression in the program. For \LangIf{}, we have just two types,
  6471. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6472. {\if\edition\racketEd
  6473. \begin{lstlisting}
  6474. (+ 10 (- (+ 12 20)))
  6475. \end{lstlisting}
  6476. \fi}
  6477. {\if\edition\pythonEd
  6478. \begin{lstlisting}
  6479. 10 + -(12 + 20)
  6480. \end{lstlisting}
  6481. \fi}
  6482. \noindent produces a value of type \INTTY{} while
  6483. {\if\edition\racketEd
  6484. \begin{lstlisting}
  6485. (and (not #f) #t)
  6486. \end{lstlisting}
  6487. \fi}
  6488. {\if\edition\pythonEd
  6489. \begin{lstlisting}
  6490. (not False) and True
  6491. \end{lstlisting}
  6492. \fi}
  6493. \noindent produces a value of type \BOOLTY{}.
  6494. A second way to think about type checking is that it enforces a set of
  6495. rules about which operators can be applied to which kinds of
  6496. values. For example, our type checker for \LangIf{} signals an error
  6497. for the below expression {\if\edition\racketEd
  6498. \begin{lstlisting}
  6499. (not (+ 10 (- (+ 12 20))))
  6500. \end{lstlisting}
  6501. \fi}
  6502. {\if\edition\pythonEd
  6503. \begin{lstlisting}
  6504. not (10 + -(12 + 20))
  6505. \end{lstlisting}
  6506. \fi}
  6507. \noindent The subexpression
  6508. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6509. \python{\code{(10 + -(12 + 20))}}
  6510. has type \INTTY{} but the type checker enforces the rule that the
  6511. argument of \code{not} must be an expression of type \BOOLTY{}.
  6512. We implement type checking using classes and methods because they
  6513. provide the open recursion needed to reuse code as we extend the type
  6514. checker in later chapters, analogous to the use of classes and methods
  6515. for the interpreters (Section~\ref{sec:extensible-interp}).
  6516. We separate the type checker for the \LangVar{} subset into its own
  6517. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6518. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6519. from the type checker for \LangVar{}. These type checkers are in the
  6520. files
  6521. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6522. and
  6523. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6524. of the support code.
  6525. %
  6526. Each type checker is a structurally recursive function over the AST.
  6527. Given an input expression \code{e}, the type checker either signals an
  6528. error or returns \racket{an expression and} its type.
  6529. %
  6530. \racket{It returns an expression because there are situations in which
  6531. we want to change or update the expression.}
  6532. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6533. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6534. \INTTY{}. To handle variables, the type checker uses the environment
  6535. \code{env} to map variables to types.
  6536. %
  6537. \racket{Consider the case for \key{let}. We type check the
  6538. initializing expression to obtain its type \key{T} and then
  6539. associate type \code{T} with the variable \code{x} in the
  6540. environment used to type check the body of the \key{let}. Thus,
  6541. when the type checker encounters a use of variable \code{x}, it can
  6542. find its type in the environment.}
  6543. %
  6544. \python{Consider the case for assignment. We type check the
  6545. initializing expression to obtain its type \key{t}. If the variable
  6546. \code{lhs.id} is already in the environment because there was a
  6547. prior assignment, we check that this initializer has the same type
  6548. as the prior one. If this is the first assignment to the variable,
  6549. we associate type \code{t} with the variable \code{lhs.id} in the
  6550. environment. Thus, when the type checker encounters a use of
  6551. variable \code{x}, it can find its type in the environment.}
  6552. %
  6553. \racket{Regarding primitive operators, we recursively analyze the
  6554. arguments and then invoke \code{type\_check\_op} to check whether
  6555. the argument types are allowed.}
  6556. %
  6557. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6558. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6559. \racket{Several auxiliary methods are used in the type checker. The
  6560. method \code{operator-types} defines a dictionary that maps the
  6561. operator names to their parameter and return types. The
  6562. \code{type-equal?} method determines whether two types are equal,
  6563. which for now simply dispatches to \code{equal?} (deep
  6564. equality). The \code{check-type-equal?} method triggers an error if
  6565. the two types are not equal. The \code{type-check-op} method looks
  6566. up the operator in the \code{operator-types} dictionary and then
  6567. checks whether the argument types are equal to the parameter types.
  6568. The result is the return type of the operator.}
  6569. %
  6570. \python{The auxiliary method \code{check\_type\_equal} triggers
  6571. an error if the two types are not equal.}
  6572. \begin{figure}[tbp]
  6573. \begin{tcolorbox}[colback=white]
  6574. {\if\edition\racketEd
  6575. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6576. (define type-check-Lvar-class
  6577. (class object%
  6578. (super-new)
  6579. (define/public (operator-types)
  6580. '((+ . ((Integer Integer) . Integer))
  6581. (- . ((Integer Integer) . Integer))
  6582. (read . (() . Integer))))
  6583. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6584. (define/public (check-type-equal? t1 t2 e)
  6585. (unless (type-equal? t1 t2)
  6586. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6587. (define/public (type-check-op op arg-types e)
  6588. (match (dict-ref (operator-types) op)
  6589. [`(,param-types . ,return-type)
  6590. (for ([at arg-types] [pt param-types])
  6591. (check-type-equal? at pt e))
  6592. return-type]
  6593. [else (error 'type-check-op "unrecognized ~a" op)]))
  6594. (define/public (type-check-exp env)
  6595. (lambda (e)
  6596. (match e
  6597. [(Int n) (values (Int n) 'Integer)]
  6598. [(Var x) (values (Var x) (dict-ref env x))]
  6599. [(Let x e body)
  6600. (define-values (e^ Te) ((type-check-exp env) e))
  6601. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6602. (values (Let x e^ b) Tb)]
  6603. [(Prim op es)
  6604. (define-values (new-es ts)
  6605. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6606. (values (Prim op new-es) (type-check-op op ts e))]
  6607. [else (error 'type-check-exp "couldn't match" e)])))
  6608. (define/public (type-check-program e)
  6609. (match e
  6610. [(Program info body)
  6611. (define-values (body^ Tb) ((type-check-exp '()) body))
  6612. (check-type-equal? Tb 'Integer body)
  6613. (Program info body^)]
  6614. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6615. ))
  6616. (define (type-check-Lvar p)
  6617. (send (new type-check-Lvar-class) type-check-program p))
  6618. \end{lstlisting}
  6619. \fi}
  6620. {\if\edition\pythonEd
  6621. \begin{lstlisting}[escapechar=`]
  6622. class TypeCheckLvar:
  6623. def check_type_equal(self, t1, t2, e):
  6624. if t1 != t2:
  6625. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6626. raise Exception(msg)
  6627. def type_check_exp(self, e, env):
  6628. match e:
  6629. case BinOp(left, (Add() | Sub()), right):
  6630. l = self.type_check_exp(left, env)
  6631. check_type_equal(l, int, left)
  6632. r = self.type_check_exp(right, env)
  6633. check_type_equal(r, int, right)
  6634. return int
  6635. case UnaryOp(USub(), v):
  6636. t = self.type_check_exp(v, env)
  6637. check_type_equal(t, int, v)
  6638. return int
  6639. case Name(id):
  6640. return env[id]
  6641. case Constant(value) if isinstance(value, int):
  6642. return int
  6643. case Call(Name('input_int'), []):
  6644. return int
  6645. def type_check_stmts(self, ss, env):
  6646. if len(ss) == 0:
  6647. return
  6648. match ss[0]:
  6649. case Assign([lhs], value):
  6650. t = self.type_check_exp(value, env)
  6651. if lhs.id in env:
  6652. check_type_equal(env[lhs.id], t, value)
  6653. else:
  6654. env[lhs.id] = t
  6655. return self.type_check_stmts(ss[1:], env)
  6656. case Expr(Call(Name('print'), [arg])):
  6657. t = self.type_check_exp(arg, env)
  6658. check_type_equal(t, int, arg)
  6659. return self.type_check_stmts(ss[1:], env)
  6660. case Expr(value):
  6661. self.type_check_exp(value, env)
  6662. return self.type_check_stmts(ss[1:], env)
  6663. def type_check_P(self, p):
  6664. match p:
  6665. case Module(body):
  6666. self.type_check_stmts(body, {})
  6667. \end{lstlisting}
  6668. \fi}
  6669. \end{tcolorbox}
  6670. \caption{Type checker for the \LangVar{} language.}
  6671. \label{fig:type-check-Lvar}
  6672. \end{figure}
  6673. \begin{figure}[tbp]
  6674. \begin{tcolorbox}[colback=white]
  6675. {\if\edition\racketEd
  6676. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6677. (define type-check-Lif-class
  6678. (class type-check-Lvar-class
  6679. (super-new)
  6680. (inherit check-type-equal?)
  6681. (define/override (operator-types)
  6682. (append '((and . ((Boolean Boolean) . Boolean))
  6683. (or . ((Boolean Boolean) . Boolean))
  6684. (< . ((Integer Integer) . Boolean))
  6685. (<= . ((Integer Integer) . Boolean))
  6686. (> . ((Integer Integer) . Boolean))
  6687. (>= . ((Integer Integer) . Boolean))
  6688. (not . ((Boolean) . Boolean)))
  6689. (super operator-types)))
  6690. (define/override (type-check-exp env)
  6691. (lambda (e)
  6692. (match e
  6693. [(Bool b) (values (Bool b) 'Boolean)]
  6694. [(Prim 'eq? (list e1 e2))
  6695. (define-values (e1^ T1) ((type-check-exp env) e1))
  6696. (define-values (e2^ T2) ((type-check-exp env) e2))
  6697. (check-type-equal? T1 T2 e)
  6698. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6699. [(If cnd thn els)
  6700. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6701. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6702. (define-values (els^ Te) ((type-check-exp env) els))
  6703. (check-type-equal? Tc 'Boolean e)
  6704. (check-type-equal? Tt Te e)
  6705. (values (If cnd^ thn^ els^) Te)]
  6706. [else ((super type-check-exp env) e)])))
  6707. ))
  6708. (define (type-check-Lif p)
  6709. (send (new type-check-Lif-class) type-check-program p))
  6710. \end{lstlisting}
  6711. \fi}
  6712. {\if\edition\pythonEd
  6713. \begin{lstlisting}
  6714. class TypeCheckLif(TypeCheckLvar):
  6715. def type_check_exp(self, e, env):
  6716. match e:
  6717. case Constant(value) if isinstance(value, bool):
  6718. return bool
  6719. case BinOp(left, Sub(), right):
  6720. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6721. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6722. return int
  6723. case UnaryOp(Not(), v):
  6724. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6725. return bool
  6726. case BoolOp(op, values):
  6727. left = values[0] ; right = values[1]
  6728. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6729. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6730. return bool
  6731. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6732. or isinstance(cmp, NotEq):
  6733. l = self.type_check_exp(left, env)
  6734. r = self.type_check_exp(right, env)
  6735. check_type_equal(l, r, e)
  6736. return bool
  6737. case Compare(left, [cmp], [right]):
  6738. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6739. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6740. return bool
  6741. case IfExp(test, body, orelse):
  6742. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6743. b = self.type_check_exp(body, env)
  6744. o = self.type_check_exp(orelse, env)
  6745. check_type_equal(b, o, e)
  6746. return b
  6747. case _:
  6748. return super().type_check_exp(e, env)
  6749. def type_check_stmts(self, ss, env):
  6750. if len(ss) == 0:
  6751. return
  6752. match ss[0]:
  6753. case If(test, body, orelse):
  6754. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6755. b = self.type_check_stmts(body, env)
  6756. o = self.type_check_stmts(orelse, env)
  6757. check_type_equal(b, o, ss[0])
  6758. return self.type_check_stmts(ss[1:], env)
  6759. case _:
  6760. return super().type_check_stmts(ss, env)
  6761. \end{lstlisting}
  6762. \fi}
  6763. \end{tcolorbox}
  6764. \caption{Type checker for the \LangIf{} language.}
  6765. \label{fig:type-check-Lif}
  6766. \end{figure}
  6767. The type checker for \LangIf{} is defined in
  6768. Figure~\ref{fig:type-check-Lif}.
  6769. %
  6770. The type of a Boolean constant is \BOOLTY{}.
  6771. %
  6772. \racket{The \code{operator-types} function adds dictionary entries for
  6773. the new operators.}
  6774. %
  6775. \python{Logical not requires its argument to be a \BOOLTY{} and
  6776. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6777. %
  6778. The equality operator requires the two arguments to have the same type
  6779. and therefore we handle it separately from the other operators.
  6780. %
  6781. \python{The other comparisons (less-than, etc.) require their
  6782. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6783. %
  6784. The condition of an \code{if} must
  6785. be of \BOOLTY{} type and the two branches must have the same type.
  6786. \begin{exercise}\normalfont\normalsize
  6787. Create 10 new test programs in \LangIf{}. Half of the programs should
  6788. have a type error. For those programs, create an empty file with the
  6789. same base name but with file extension \code{.tyerr}. For example, if
  6790. the test
  6791. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6792. is expected to error, then create
  6793. an empty file named \code{cond\_test\_14.tyerr}.
  6794. %
  6795. \racket{This indicates to \code{interp-tests} and
  6796. \code{compiler-tests} that a type error is expected. }
  6797. %
  6798. The other half of the test programs should not have type errors.
  6799. %
  6800. \racket{In the \code{run-tests.rkt} script, change the second argument
  6801. of \code{interp-tests} and \code{compiler-tests} to
  6802. \code{type-check-Lif}, which causes the type checker to run prior to
  6803. the compiler passes. Temporarily change the \code{passes} to an
  6804. empty list and run the script, thereby checking that the new test
  6805. programs either type check or not as intended.}
  6806. %
  6807. Run the test script to check that these test programs type check as
  6808. expected.
  6809. \end{exercise}
  6810. \clearpage
  6811. \section{The \LangCIf{} Intermediate Language}
  6812. \label{sec:Cif}
  6813. {\if\edition\racketEd
  6814. %
  6815. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6816. comparison operators to the \Exp{} non-terminal and the literals
  6817. \TRUE{} and \FALSE{} to the \Arg{} non-terminal. Regarding control
  6818. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6819. \Tail{} non-terminal. The condition of an \code{if} statement is a
  6820. comparison operation and the branches are \code{goto} statements,
  6821. making it straightforward to compile \code{if} statements to x86. The
  6822. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6823. expressions. A \code{goto} statement transfers control to the $\Tail$
  6824. expression corresponding to its label.
  6825. %
  6826. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6827. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6828. defines its abstract syntax.
  6829. %
  6830. \fi}
  6831. %
  6832. {\if\edition\pythonEd
  6833. %
  6834. The output of \key{explicate\_control} is a language similar to the
  6835. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6836. \code{goto} statements, so we name it \LangCIf{}.
  6837. %
  6838. The \LangCIf{} language supports the same operators as \LangIf{} but
  6839. the arguments of operators are restricted to atomic expressions. The
  6840. \LangCIf{} language does not include \code{if} expressions but it does
  6841. include a restricted form of \code{if} statement. The condition must be
  6842. a comparison and the two branches may only contain \code{goto}
  6843. statements. These restrictions make it easier to translate \code{if}
  6844. statements to x86. The \LangCIf{} language also adds a \code{return}
  6845. statement to finish the program with a specified value.
  6846. %
  6847. The \key{CProgram} construct contains a dictionary mapping labels to
  6848. lists of statements that end with a \code{return} statement, a
  6849. \code{goto}, or a conditional \code{goto}.
  6850. %% Statement lists of this
  6851. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6852. %% is a control transfer at the end and control only enters at the
  6853. %% beginning of the list, which is marked by the label.
  6854. %
  6855. A \code{goto} statement transfers control to the sequence of statements
  6856. associated with its label.
  6857. %
  6858. The concrete syntax for \LangCIf{} is defined in
  6859. Figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6860. in Figure~\ref{fig:c1-syntax}.
  6861. %
  6862. \fi}
  6863. %
  6864. \newcommand{\CifGrammarRacket}{
  6865. \begin{array}{lcl}
  6866. \Atm &::=& \itm{bool} \\
  6867. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6868. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6869. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6870. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6871. \end{array}
  6872. }
  6873. \newcommand{\CifASTRacket}{
  6874. \begin{array}{lcl}
  6875. \Atm &::=& \BOOL{\itm{bool}} \\
  6876. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6877. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6878. \Tail &::= & \GOTO{\itm{label}} \\
  6879. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6880. \end{array}
  6881. }
  6882. \newcommand{\CifGrammarPython}{
  6883. \begin{array}{lcl}
  6884. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6885. \Exp &::= & \Atm \MID \CREAD{}
  6886. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6887. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6888. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6889. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6890. &\MID& \CASSIGN{\Var}{\Exp}
  6891. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6892. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6893. \end{array}
  6894. }
  6895. \newcommand{\CifASTPython}{
  6896. \begin{array}{lcl}
  6897. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6898. \Exp &::= & \Atm \MID \READ{} \\
  6899. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6900. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6901. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6902. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6903. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6904. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6905. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6906. \end{array}
  6907. }
  6908. \begin{figure}[tbp]
  6909. \begin{tcolorbox}[colback=white]
  6910. \small
  6911. {\if\edition\racketEd
  6912. \[
  6913. \begin{array}{l}
  6914. \gray{\CvarGrammarRacket} \\ \hline
  6915. \CifGrammarRacket \\
  6916. \begin{array}{lcl}
  6917. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6918. \end{array}
  6919. \end{array}
  6920. \]
  6921. \fi}
  6922. {\if\edition\pythonEd
  6923. \[
  6924. \begin{array}{l}
  6925. \CifGrammarPython \\
  6926. \begin{array}{lcl}
  6927. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6928. \end{array}
  6929. \end{array}
  6930. \]
  6931. \fi}
  6932. \end{tcolorbox}
  6933. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  6934. \racket{, an extension of \LangCVar{} (Figure~\ref{fig:c0-concrete-syntax})}.}
  6935. \label{fig:c1-concrete-syntax}
  6936. \end{figure}
  6937. \begin{figure}[tp]
  6938. \begin{tcolorbox}[colback=white]
  6939. \small
  6940. {\if\edition\racketEd
  6941. \[
  6942. \begin{array}{l}
  6943. \gray{\CvarASTRacket} \\ \hline
  6944. \CifASTRacket \\
  6945. \begin{array}{lcl}
  6946. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6947. \end{array}
  6948. \end{array}
  6949. \]
  6950. \fi}
  6951. {\if\edition\pythonEd
  6952. \[
  6953. \begin{array}{l}
  6954. \CifASTPython \\
  6955. \begin{array}{lcl}
  6956. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6957. \end{array}
  6958. \end{array}
  6959. \]
  6960. \fi}
  6961. \end{tcolorbox}
  6962. \racket{
  6963. \index{subject}{IfStmt@\IFSTMTNAME{}}
  6964. }
  6965. \index{subject}{Goto@\texttt{Goto}}
  6966. \index{subject}{Return@\texttt{Return}}
  6967. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6968. (Figure~\ref{fig:c0-syntax})}.}
  6969. \label{fig:c1-syntax}
  6970. \end{figure}
  6971. \section{The \LangXIf{} Language}
  6972. \label{sec:x86-if}
  6973. \index{subject}{x86} To implement the new logical operations, the
  6974. comparison operations, and the \key{if} expression\python{ and
  6975. statement}, we delve further into the x86
  6976. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6977. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6978. which includes instructions for logical operations, comparisons, and
  6979. \racket{conditional} jumps.
  6980. %
  6981. \python{The abstract syntax for an \LangXIf{} program contains a
  6982. dictionary mapping labels to sequences of instructions, each of
  6983. which we refer to as a \emph{basic block}\index{subject}{basic
  6984. block}.}
  6985. One challenge is that x86 does not provide an instruction that
  6986. directly implements logical negation (\code{not} in \LangIf{} and
  6987. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6988. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6989. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6990. bit of its arguments, and writes the results into its second argument.
  6991. Recall the truth table for exclusive-or:
  6992. \begin{center}
  6993. \begin{tabular}{l|cc}
  6994. & 0 & 1 \\ \hline
  6995. 0 & 0 & 1 \\
  6996. 1 & 1 & 0
  6997. \end{tabular}
  6998. \end{center}
  6999. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7000. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7001. for the bit $1$, the result is the opposite of the second bit. Thus,
  7002. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7003. the first argument as follows, where $\Arg$ is the translation of
  7004. $\Atm$ to x86.
  7005. \[
  7006. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7007. \qquad\Rightarrow\qquad
  7008. \begin{array}{l}
  7009. \key{movq}~ \Arg\key{,} \Var\\
  7010. \key{xorq}~ \key{\$1,} \Var
  7011. \end{array}
  7012. \]
  7013. \newcommand{\GrammarXIf}{
  7014. \begin{array}{lcl}
  7015. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7016. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7017. \Arg &::=& \key{\%}\itm{bytereg}\\
  7018. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7019. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7020. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7021. \MID \key{set}cc~\Arg
  7022. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7023. &\MID& \key{j}cc~\itm{label} \\
  7024. \end{array}
  7025. }
  7026. \begin{figure}[tp]
  7027. \begin{tcolorbox}[colback=white]
  7028. \[
  7029. \begin{array}{l}
  7030. \gray{\GrammarXInt} \\ \hline
  7031. \GrammarXIf \\
  7032. \begin{array}{lcl}
  7033. \LangXIfM{} &::= & \key{.globl main} \\
  7034. & & \key{main:} \; \Instr\ldots
  7035. \end{array}
  7036. \end{array}
  7037. \]
  7038. \end{tcolorbox}
  7039. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  7040. \label{fig:x86-1-concrete}
  7041. \end{figure}
  7042. \newcommand{\ASTXIfRacket}{
  7043. \begin{array}{lcl}
  7044. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7045. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7046. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7047. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7048. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7049. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7050. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7051. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7052. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7053. \end{array}
  7054. }
  7055. \begin{figure}[tp]
  7056. \begin{tcolorbox}[colback=white]
  7057. \small
  7058. {\if\edition\racketEd
  7059. \[\arraycolsep=3pt
  7060. \begin{array}{l}
  7061. \gray{\ASTXIntRacket} \\ \hline
  7062. \ASTXIfRacket \\
  7063. \begin{array}{lcl}
  7064. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7065. \end{array}
  7066. \end{array}
  7067. \]
  7068. \fi}
  7069. %
  7070. {\if\edition\pythonEd
  7071. \[
  7072. \begin{array}{lcl}
  7073. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7074. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7075. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7076. \MID \BYTEREG{\itm{bytereg}} \\
  7077. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7078. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7079. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7080. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7081. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7082. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7083. \MID \PUSHQ{\Arg}} \\
  7084. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7085. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7086. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7087. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7088. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7089. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7090. \Block &::= & \Instr^{+} \\
  7091. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7092. \end{array}
  7093. \]
  7094. \fi}
  7095. \end{tcolorbox}
  7096. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  7097. \label{fig:x86-1}
  7098. \end{figure}
  7099. Next we consider the x86 instructions that are relevant for compiling
  7100. the comparison operations. The \key{cmpq} instruction compares its two
  7101. arguments to determine whether one argument is less than, equal, or
  7102. greater than the other argument. The \key{cmpq} instruction is unusual
  7103. regarding the order of its arguments and where the result is
  7104. placed. The argument order is backwards: if you want to test whether
  7105. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7106. \key{cmpq} is placed in the special EFLAGS register. This register
  7107. cannot be accessed directly but it can be queried by a number of
  7108. instructions, including the \key{set} instruction. The instruction
  7109. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7110. depending on whether the contents of the EFLAGS register matches the
  7111. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7112. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7113. The \key{set} instruction has a quirk in that its destination argument
  7114. must be single byte register, such as \code{al} (L for lower bits) or
  7115. \code{ah} (H for higher bits), which are part of the \code{rax}
  7116. register. Thankfully, the \key{movzbq} instruction can be used to
  7117. move from a single byte register to a normal 64-bit register. The
  7118. abstract syntax for the \code{set} instruction differs from the
  7119. concrete syntax in that it separates the instruction name from the
  7120. condition code.
  7121. \python{The x86 instructions for jumping are relevant to the
  7122. compilation of \key{if} expressions.}
  7123. %
  7124. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7125. counter to the address of the instruction after the specified
  7126. label.}
  7127. %
  7128. \racket{The x86 instruction for conditional jump is relevant to the
  7129. compilation of \key{if} expressions.}
  7130. %
  7131. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7132. counter to point to the instruction after \itm{label} depending on
  7133. whether the result in the EFLAGS register matches the condition code
  7134. \itm{cc}, otherwise the jump instruction falls through to the next
  7135. instruction. Like the abstract syntax for \code{set}, the abstract
  7136. syntax for conditional jump separates the instruction name from the
  7137. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7138. corresponds to \code{jle foo}. Because the conditional jump instruction
  7139. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7140. a \key{cmpq} instruction to set the EFLAGS register.
  7141. \section{Shrink the \LangIf{} Language}
  7142. \label{sec:shrink-Lif}
  7143. The \LangIf{} language includes several features that are easily
  7144. expressible with other features. For example, \code{and} and \code{or}
  7145. are expressible using \code{if} as follows.
  7146. \begin{align*}
  7147. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7148. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7149. \end{align*}
  7150. By performing these translations in the front-end of the compiler,
  7151. subsequent passes of the compiler do not need to deal with these features,
  7152. making the passes shorter.
  7153. On the other hand, sometimes translations reduce the efficiency of the
  7154. generated code by increasing the number of instructions. For example,
  7155. expressing subtraction in terms of negation
  7156. \[
  7157. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7158. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7159. \]
  7160. produces code with two x86 instructions (\code{negq} and \code{addq})
  7161. instead of just one (\code{subq}).
  7162. \begin{exercise}\normalfont\normalsize
  7163. %
  7164. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7165. the language by translating them to \code{if} expressions in \LangIf{}.
  7166. %
  7167. Create four test programs that involve these operators.
  7168. %
  7169. {\if\edition\racketEd
  7170. In the \code{run-tests.rkt} script, add the following entry for
  7171. \code{shrink} to the list of passes (it should be the only pass at
  7172. this point).
  7173. \begin{lstlisting}
  7174. (list "shrink" shrink interp_Lif type-check-Lif)
  7175. \end{lstlisting}
  7176. This instructs \code{interp-tests} to run the interpreter
  7177. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7178. output of \code{shrink}.
  7179. \fi}
  7180. %
  7181. Run the script to test your compiler on all the test programs.
  7182. \end{exercise}
  7183. {\if\edition\racketEd
  7184. \section{Uniquify Variables}
  7185. \label{sec:uniquify-Lif}
  7186. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7187. \code{if} expressions.
  7188. \begin{exercise}\normalfont\normalsize
  7189. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7190. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7191. \begin{lstlisting}
  7192. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7193. \end{lstlisting}
  7194. Run the script to test your compiler.
  7195. \end{exercise}
  7196. \fi}
  7197. \section{Remove Complex Operands}
  7198. \label{sec:remove-complex-opera-Lif}
  7199. The output language of \code{remove\_complex\_operands} is
  7200. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the monadic
  7201. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7202. but the \code{if} expression is not. All three sub-expressions of an
  7203. \code{if} are allowed to be complex expressions but the operands of
  7204. \code{not} and the comparisons must be atomic.
  7205. %
  7206. \python{We add a new language form, the \code{Begin} expression, to aid
  7207. in the translation of \code{if} expressions. When we recursively
  7208. process the two branches of the \code{if}, we generate temporary
  7209. variables and their initializing expressions. However, these
  7210. expressions may contain side effects and should only be executed
  7211. when the condition of the \code{if} is true (for the ``then''
  7212. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7213. a way to initialize the temporary variables within the two branches
  7214. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7215. form execute the statements $ss$ and then returns the result of
  7216. expression $e$.}
  7217. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7218. the new features in \LangIf{}. When recursively processing
  7219. subexpressions, recall that you should invoke \code{rco\_atom} when
  7220. the output needs to be an \Atm{} (as specified in the grammar for
  7221. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7222. \Exp{}. Regarding \code{if}, it is particularly important to
  7223. \textbf{not} replace its condition with a temporary variable because
  7224. that would interfere with the generation of high-quality output in the
  7225. upcoming \code{explicate\_control} pass.
  7226. \newcommand{\LifMonadASTRacket}{
  7227. \begin{array}{rcl}
  7228. \Atm &::=& \BOOL{\itm{bool}}\\
  7229. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7230. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7231. \MID \IF{\Exp}{\Exp}{\Exp}
  7232. \end{array}
  7233. }
  7234. \newcommand{\LifMonadASTPython}{
  7235. \begin{array}{rcl}
  7236. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7237. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7238. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7239. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7240. \Atm &::=& \BOOL{\itm{bool}}\\
  7241. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7242. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7243. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7244. \end{array}
  7245. }
  7246. \begin{figure}[tp]
  7247. \centering
  7248. \begin{tcolorbox}[colback=white]
  7249. {\if\edition\racketEd
  7250. \[
  7251. \begin{array}{l}
  7252. \gray{\LvarMonadASTRacket} \\ \hline
  7253. \LifMonadASTRacket \\
  7254. \begin{array}{rcl}
  7255. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7256. \end{array}
  7257. \end{array}
  7258. \]
  7259. \fi}
  7260. {\if\edition\pythonEd
  7261. \[
  7262. \begin{array}{l}
  7263. \gray{\LvarMonadASTPython} \\ \hline
  7264. \LifMonadASTPython \\
  7265. \begin{array}{rcl}
  7266. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7267. \end{array}
  7268. \end{array}
  7269. \]
  7270. \fi}
  7271. \end{tcolorbox}
  7272. \python{\index{subject}{Begin@\texttt{Begin}}}
  7273. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7274. (extends \LangVarANF in Figure~\ref{fig:Lvar-anf-syntax}).}
  7275. \label{fig:Lif-anf-syntax}
  7276. \end{figure}
  7277. \begin{exercise}\normalfont\normalsize
  7278. %
  7279. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7280. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7281. %
  7282. Create three new \LangIf{} programs that exercise the interesting
  7283. code in this pass.
  7284. %
  7285. {\if\edition\racketEd
  7286. In the \code{run-tests.rkt} script, add the following entry to the
  7287. list of \code{passes} and then run the script to test your compiler.
  7288. \begin{lstlisting}
  7289. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7290. \end{lstlisting}
  7291. \fi}
  7292. \end{exercise}
  7293. \section{Explicate Control}
  7294. \label{sec:explicate-control-Lif}
  7295. \racket{Recall that the purpose of \code{explicate\_control} is to
  7296. make the order of evaluation explicit in the syntax of the program.
  7297. With the addition of \key{if} this gets more interesting.}
  7298. %
  7299. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7300. %
  7301. The main challenge to overcome is that the condition of an \key{if}
  7302. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7303. condition must be a comparison.
  7304. As a motivating example, consider the following program that has an
  7305. \key{if} expression nested in the condition of another \key{if}.%
  7306. \python{\footnote{Programmers rarely write nested \code{if}
  7307. expressions, but it is not uncommon for the condition of an
  7308. \code{if} statement to be a call of a function that also contains an
  7309. \code{if} statement. When such a function is inlined, the result is
  7310. a nested \code{if} that requires the techniques discussed in this
  7311. section.}}
  7312. % cond_test_41.rkt, if_lt_eq.py
  7313. \begin{center}
  7314. \begin{minipage}{0.96\textwidth}
  7315. {\if\edition\racketEd
  7316. \begin{lstlisting}
  7317. (let ([x (read)])
  7318. (let ([y (read)])
  7319. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7320. (+ y 2)
  7321. (+ y 10))))
  7322. \end{lstlisting}
  7323. \fi}
  7324. {\if\edition\pythonEd
  7325. \begin{lstlisting}
  7326. x = input_int()
  7327. y = input_int()
  7328. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7329. \end{lstlisting}
  7330. \fi}
  7331. \end{minipage}
  7332. \end{center}
  7333. %
  7334. The naive way to compile \key{if} and the comparison operations would
  7335. be to handle each of them in isolation, regardless of their context.
  7336. Each comparison would be translated into a \key{cmpq} instruction
  7337. followed by several instructions to move the result from the EFLAGS
  7338. register into a general purpose register or stack location. Each
  7339. \key{if} would be translated into a \key{cmpq} instruction followed by
  7340. a conditional jump. The generated code for the inner \key{if} in the
  7341. above example would be as follows.
  7342. \begin{center}
  7343. \begin{minipage}{0.96\textwidth}
  7344. \begin{lstlisting}
  7345. cmpq $1, x
  7346. setl %al
  7347. movzbq %al, tmp
  7348. cmpq $1, tmp
  7349. je then_branch_1
  7350. jmp else_branch_1
  7351. \end{lstlisting}
  7352. \end{minipage}
  7353. \end{center}
  7354. Notice that the three instructions starting with \code{setl} are
  7355. redundant: the conditional jump could come immediately after the first
  7356. \code{cmpq}.
  7357. Our goal will be to compile \key{if} expressions so that the relevant
  7358. comparison instruction appears directly before the conditional jump.
  7359. For example, we want to generate the following code for the inner
  7360. \code{if}.
  7361. \begin{center}
  7362. \begin{minipage}{0.96\textwidth}
  7363. \begin{lstlisting}
  7364. cmpq $1, x
  7365. jl then_branch_1
  7366. jmp else_branch_1
  7367. \end{lstlisting}
  7368. \end{minipage}
  7369. \end{center}
  7370. One way to achieve this goal is to reorganize the code at the level of
  7371. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7372. the following code.
  7373. \begin{center}
  7374. \begin{minipage}{0.96\textwidth}
  7375. {\if\edition\racketEd
  7376. \begin{lstlisting}
  7377. (let ([x (read)])
  7378. (let ([y (read)])
  7379. (if (< x 1)
  7380. (if (eq? x 0)
  7381. (+ y 2)
  7382. (+ y 10))
  7383. (if (eq? x 2)
  7384. (+ y 2)
  7385. (+ y 10)))))
  7386. \end{lstlisting}
  7387. \fi}
  7388. {\if\edition\pythonEd
  7389. \begin{lstlisting}
  7390. x = input_int()
  7391. y = input_int()
  7392. print(((y + 2) if x == 0 else (y + 10)) \
  7393. if (x < 1) \
  7394. else ((y + 2) if (x == 2) else (y + 10)))
  7395. \end{lstlisting}
  7396. \fi}
  7397. \end{minipage}
  7398. \end{center}
  7399. Unfortunately, this approach duplicates the two branches from the
  7400. outer \code{if} and a compiler must never duplicate code! After all,
  7401. the two branches could be very large expressions.
  7402. How can we apply the above transformation but without duplicating
  7403. code? In other words, how can two different parts of a program refer
  7404. to one piece of code.
  7405. %
  7406. The answer is that we must move away from abstract syntax \emph{trees}
  7407. and instead use \emph{graphs}.
  7408. %
  7409. At the level of x86 assembly this is straightforward because we can
  7410. label the code for each branch and insert jumps in all the places that
  7411. need to execute the branch. In this way, jump instructions are edges
  7412. in the graph and the basic blocks are the nodes.
  7413. %
  7414. Likewise, our language \LangCIf{} provides the ability to label a
  7415. sequence of statements and to jump to a label via \code{goto}.
  7416. As a preview of what \code{explicate\_control} will do,
  7417. Figure~\ref{fig:explicate-control-s1-38} shows the output of
  7418. \code{explicate\_control} on the above example. Note how the condition
  7419. of every \code{if} is a comparison operation and that we have not
  7420. duplicated any code, but instead used labels and \code{goto} to enable
  7421. sharing of code.
  7422. \begin{figure}[tbp]
  7423. \begin{tcolorbox}[colback=white]
  7424. {\if\edition\racketEd
  7425. \begin{tabular}{lll}
  7426. \begin{minipage}{0.4\textwidth}
  7427. % cond_test_41.rkt
  7428. \begin{lstlisting}
  7429. (let ([x (read)])
  7430. (let ([y (read)])
  7431. (if (if (< x 1)
  7432. (eq? x 0)
  7433. (eq? x 2))
  7434. (+ y 2)
  7435. (+ y 10))))
  7436. \end{lstlisting}
  7437. \end{minipage}
  7438. &
  7439. $\Rightarrow$
  7440. &
  7441. \begin{minipage}{0.55\textwidth}
  7442. \begin{lstlisting}
  7443. start:
  7444. x = (read);
  7445. y = (read);
  7446. if (< x 1)
  7447. goto block_4;
  7448. else
  7449. goto block_5;
  7450. block_4:
  7451. if (eq? x 0)
  7452. goto block_2;
  7453. else
  7454. goto block_3;
  7455. block_5:
  7456. if (eq? x 2)
  7457. goto block_2;
  7458. else
  7459. goto block_3;
  7460. block_2:
  7461. return (+ y 2);
  7462. block_3:
  7463. return (+ y 10);
  7464. \end{lstlisting}
  7465. \end{minipage}
  7466. \end{tabular}
  7467. \fi}
  7468. {\if\edition\pythonEd
  7469. \begin{tabular}{lll}
  7470. \begin{minipage}{0.4\textwidth}
  7471. % cond_test_41.rkt
  7472. \begin{lstlisting}
  7473. x = input_int()
  7474. y = input_int()
  7475. print(y + 2 \
  7476. if (x == 0 \
  7477. if x < 1 \
  7478. else x == 2) \
  7479. else y + 10)
  7480. \end{lstlisting}
  7481. \end{minipage}
  7482. &
  7483. $\Rightarrow$
  7484. &
  7485. \begin{minipage}{0.55\textwidth}
  7486. \begin{lstlisting}
  7487. start:
  7488. x = input_int()
  7489. y = input_int()
  7490. if x < 1:
  7491. goto block_8
  7492. else:
  7493. goto block_9
  7494. block_8:
  7495. if x == 0:
  7496. goto block_4
  7497. else:
  7498. goto block_5
  7499. block_9:
  7500. if x == 2:
  7501. goto block_6
  7502. else:
  7503. goto block_7
  7504. block_4:
  7505. goto block_2
  7506. block_5:
  7507. goto block_3
  7508. block_6:
  7509. goto block_2
  7510. block_7:
  7511. goto block_3
  7512. block_2:
  7513. tmp_0 = y + 2
  7514. goto block_1
  7515. block_3:
  7516. tmp_0 = y + 10
  7517. goto block_1
  7518. block_1:
  7519. print(tmp_0)
  7520. return 0
  7521. \end{lstlisting}
  7522. \end{minipage}
  7523. \end{tabular}
  7524. \fi}
  7525. \end{tcolorbox}
  7526. \caption{Translation from \LangIf{} to \LangCIf{}
  7527. via the \code{explicate\_control}.}
  7528. \label{fig:explicate-control-s1-38}
  7529. \end{figure}
  7530. {\if\edition\racketEd
  7531. %
  7532. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7533. \code{explicate\_control} for \LangVar{} using two recursive
  7534. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7535. former function translates expressions in tail position whereas the
  7536. later function translates expressions on the right-hand-side of a
  7537. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7538. have a new kind of position to deal with: the predicate position of
  7539. the \key{if}. We need another function, \code{explicate\_pred}, that
  7540. decides how to compile an \key{if} by analyzing its condition. So
  7541. \code{explicate\_pred} takes an \LangIf{} expression and two
  7542. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7543. tail. In the following paragraphs we discuss specific cases in the
  7544. \code{explicate\_tail}, \code{explicate\_assign}, and
  7545. \code{explicate\_pred} functions.
  7546. %
  7547. \fi}
  7548. %
  7549. {\if\edition\pythonEd
  7550. %
  7551. We recommend implementing \code{explicate\_control} using the
  7552. following four auxiliary functions.
  7553. \begin{description}
  7554. \item[\code{explicate\_effect}] generates code for expressions as
  7555. statements, so their result is ignored and only their side effects
  7556. matter.
  7557. \item[\code{explicate\_assign}] generates code for expressions
  7558. on the right-hand side of an assignment.
  7559. \item[\code{explicate\_pred}] generates code for an \code{if}
  7560. expression or statement by analyzing the condition expression.
  7561. \item[\code{explicate\_stmt}] generates code for statements.
  7562. \end{description}
  7563. These four functions should build the dictionary of basic blocks. The
  7564. following auxiliary function can be used to create a new basic block
  7565. from a list of statements. It returns a \code{goto} statement that
  7566. jumps to the new basic block.
  7567. \begin{center}
  7568. \begin{minipage}{\textwidth}
  7569. \begin{lstlisting}
  7570. def create_block(stmts, basic_blocks):
  7571. label = label_name(generate_name('block'))
  7572. basic_blocks[label] = stmts
  7573. return Goto(label)
  7574. \end{lstlisting}
  7575. \end{minipage}
  7576. \end{center}
  7577. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7578. \code{explicate\_control} pass.
  7579. The \code{explicate\_effect} function has three parameters: 1) the
  7580. expression to be compiled, 2) the already-compiled code for this
  7581. expression's \emph{continuation}, that is, the list of statements that
  7582. should execute after this expression, and 3) the dictionary of
  7583. generated basic blocks. The \code{explicate\_effect} function returns
  7584. a list of \LangCIf{} statements and it may add to the dictionary of
  7585. basic blocks.
  7586. %
  7587. Let's consider a few of the cases for the expression to be compiled.
  7588. If the expression to be compiled is a constant, then it can be
  7589. discarded because it has no side effects. If it's a \CREAD{}, then it
  7590. has a side-effect and should be preserved. So the expression should be
  7591. translated into a statement using the \code{Expr} AST class. If the
  7592. expression to be compiled is an \code{if} expression, we translate the
  7593. two branches using \code{explicate\_effect} and then translate the
  7594. condition expression using \code{explicate\_pred}, which generates
  7595. code for the entire \code{if}.
  7596. The \code{explicate\_assign} function has four parameters: 1) the
  7597. right-hand-side of the assignment, 2) the left-hand-side of the
  7598. assignment (the variable), 3) the continuation, and 4) the dictionary
  7599. of basic blocks. The \code{explicate\_assign} function returns a list
  7600. of \LangCIf{} statements and it may add to the dictionary of basic
  7601. blocks.
  7602. When the right-hand-side is an \code{if} expression, there is some
  7603. work to do. In particular, the two branches should be translated using
  7604. \code{explicate\_assign} and the condition expression should be
  7605. translated using \code{explicate\_pred}. Otherwise we can simply
  7606. generate an assignment statement, with the given left and right-hand
  7607. sides, concatenated with its continuation.
  7608. \begin{figure}[tbp]
  7609. \begin{tcolorbox}[colback=white]
  7610. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7611. def explicate_effect(e, cont, basic_blocks):
  7612. match e:
  7613. case IfExp(test, body, orelse):
  7614. ...
  7615. case Call(func, args):
  7616. ...
  7617. case Begin(body, result):
  7618. ...
  7619. case _:
  7620. ...
  7621. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7622. match rhs:
  7623. case IfExp(test, body, orelse):
  7624. ...
  7625. case Begin(body, result):
  7626. ...
  7627. case _:
  7628. return [Assign([lhs], rhs)] + cont
  7629. def explicate_pred(cnd, thn, els, basic_blocks):
  7630. match cnd:
  7631. case Compare(left, [op], [right]):
  7632. goto_thn = create_block(thn, basic_blocks)
  7633. goto_els = create_block(els, basic_blocks)
  7634. return [If(cnd, [goto_thn], [goto_els])]
  7635. case Constant(True):
  7636. return thn;
  7637. case Constant(False):
  7638. return els;
  7639. case UnaryOp(Not(), operand):
  7640. ...
  7641. case IfExp(test, body, orelse):
  7642. ...
  7643. case Begin(body, result):
  7644. ...
  7645. case _:
  7646. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7647. [create_block(els, basic_blocks)],
  7648. [create_block(thn, basic_blocks)])]
  7649. def explicate_stmt(s, cont, basic_blocks):
  7650. match s:
  7651. case Assign([lhs], rhs):
  7652. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7653. case Expr(value):
  7654. return explicate_effect(value, cont, basic_blocks)
  7655. case If(test, body, orelse):
  7656. ...
  7657. def explicate_control(p):
  7658. match p:
  7659. case Module(body):
  7660. new_body = [Return(Constant(0))]
  7661. basic_blocks = {}
  7662. for s in reversed(body):
  7663. new_body = explicate_stmt(s, new_body, basic_blocks)
  7664. basic_blocks[label_name('start')] = new_body
  7665. return CProgram(basic_blocks)
  7666. \end{lstlisting}
  7667. \end{tcolorbox}
  7668. \caption{Skeleton for the \code{explicate\_control} pass.}
  7669. \label{fig:explicate-control-Lif}
  7670. \end{figure}
  7671. \fi}
  7672. {\if\edition\racketEd
  7673. \subsection{Explicate Tail and Assign}
  7674. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7675. additional cases for Boolean constants and \key{if}. The cases for
  7676. \code{if} should recursively compile the two branches using either
  7677. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7678. cases should then invoke \code{explicate\_pred} on the condition
  7679. expression, passing in the generated code for the two branches. For
  7680. example, consider the following program with an \code{if} in tail
  7681. position.
  7682. % cond_test_6.rkt
  7683. \begin{lstlisting}
  7684. (let ([x (read)])
  7685. (if (eq? x 0) 42 777))
  7686. \end{lstlisting}
  7687. The two branches are recursively compiled to return statements. We
  7688. then delegate to \code{explicate\_pred}, passing the condition
  7689. \code{(eq? x 0)} and the two return statements. We return to this
  7690. example shortly when we discuss \code{explicate\_pred}.
  7691. Next let us consider a program with an \code{if} on the right-hand
  7692. side of a \code{let}.
  7693. \begin{lstlisting}
  7694. (let ([y (read)])
  7695. (let ([x (if (eq? y 0) 40 777)])
  7696. (+ x 2)))
  7697. \end{lstlisting}
  7698. Note that the body of the inner \code{let} will have already been
  7699. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7700. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7701. to recursively process both branches of the \code{if}, and we do not
  7702. want to duplicate code, so we generate the following block using an
  7703. auxiliary function named \code{create\_block} that we discuss below.
  7704. \begin{lstlisting}
  7705. block_6:
  7706. return (+ x 2)
  7707. \end{lstlisting}
  7708. We then use \code{goto block\_6;} as the \code{cont} argument for
  7709. compiling the branches. So the two branches compile to
  7710. \begin{center}
  7711. \begin{minipage}{0.2\textwidth}
  7712. \begin{lstlisting}
  7713. x = 40;
  7714. goto block_6;
  7715. \end{lstlisting}
  7716. \end{minipage}
  7717. \hspace{0.5in} and \hspace{0.5in}
  7718. \begin{minipage}{0.2\textwidth}
  7719. \begin{lstlisting}
  7720. x = 777;
  7721. goto block_6;
  7722. \end{lstlisting}
  7723. \end{minipage}
  7724. \end{center}
  7725. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7726. \code{(eq? y 0)} and the above code for the branches.
  7727. \subsection{Create Block}
  7728. We recommend implementing the \code{create\_block} auxiliary function
  7729. as follows, using a global variable \code{basic-blocks} to store a
  7730. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7731. that \code{create\_block} generates a new label and then associates
  7732. the given \code{tail} with the new label in the \code{basic-blocks}
  7733. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7734. new label. However, if the given \code{tail} is already a \code{Goto},
  7735. then there is no need to generate a new label and entry in
  7736. \code{basic-blocks}; we can simply return that \code{Goto}.
  7737. %
  7738. \begin{lstlisting}
  7739. (define (create_block tail)
  7740. (match tail
  7741. [(Goto label) (Goto label)]
  7742. [else
  7743. (let ([label (gensym 'block)])
  7744. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7745. (Goto label))]))
  7746. \end{lstlisting}
  7747. \fi}
  7748. {\if\edition\racketEd
  7749. \subsection{Explicate Predicate}
  7750. \begin{figure}[tbp]
  7751. \begin{tcolorbox}[colback=white]
  7752. \begin{lstlisting}
  7753. (define (explicate_pred cnd thn els)
  7754. (match cnd
  7755. [(Var x) ___]
  7756. [(Let x rhs body) ___]
  7757. [(Prim 'not (list e)) ___]
  7758. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7759. (IfStmt (Prim op es) (create_block thn)
  7760. (create_block els))]
  7761. [(Bool b) (if b thn els)]
  7762. [(If cnd^ thn^ els^) ___]
  7763. [else (error "explicate_pred unhandled case" cnd)]))
  7764. \end{lstlisting}
  7765. \end{tcolorbox}
  7766. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7767. \label{fig:explicate-pred}
  7768. \end{figure}
  7769. \fi}
  7770. \racket{The skeleton for the \code{explicate\_pred} function is given
  7771. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7772. 1) \code{cnd}, the condition expression of the \code{if},
  7773. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7774. and 3) \code{els}, the code generated by
  7775. explicate for the ``else'' branch. The \code{explicate\_pred}
  7776. function should match on \code{cnd} with a case for
  7777. every kind of expression that can have type \BOOLTY{}.}
  7778. %
  7779. \python{The \code{explicate\_pred} function has four parameters: 1)
  7780. the condition expression, 2) the generated statements for the
  7781. ``then'' branch, 3) the generated statements for the ``else''
  7782. branch, and 4) the dictionary of basic blocks. The
  7783. \code{explicate\_pred} function returns a list of \LangCIf{}
  7784. statements and it may add to the dictionary of basic blocks.}
  7785. Consider the case for comparison operators. We translate the
  7786. comparison to an \code{if} statement whose branches are \code{goto}
  7787. statements created by applying \code{create\_block} to the code
  7788. generated for the \code{thn} and \code{els} branches. Let us
  7789. illustrate this translation by returning to the program with an
  7790. \code{if} expression in tail position, shown again below. We invoke
  7791. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7792. \python{\code{x == 0}}.
  7793. %
  7794. {\if\edition\racketEd
  7795. \begin{lstlisting}
  7796. (let ([x (read)])
  7797. (if (eq? x 0) 42 777))
  7798. \end{lstlisting}
  7799. \fi}
  7800. %
  7801. {\if\edition\pythonEd
  7802. \begin{lstlisting}
  7803. x = input_int()
  7804. 42 if x == 0 else 777
  7805. \end{lstlisting}
  7806. \fi}
  7807. %
  7808. \noindent The two branches \code{42} and \code{777} were already
  7809. compiled to \code{return} statements, from which we now create the
  7810. following blocks.
  7811. %
  7812. \begin{center}
  7813. \begin{minipage}{\textwidth}
  7814. \begin{lstlisting}
  7815. block_1:
  7816. return 42;
  7817. block_2:
  7818. return 777;
  7819. \end{lstlisting}
  7820. \end{minipage}
  7821. \end{center}
  7822. %
  7823. After that, \code{explicate\_pred} compiles the comparison
  7824. \racket{\code{(eq? x 0)}}
  7825. \python{\code{x == 0}}
  7826. to the following \code{if} statement.
  7827. %
  7828. {\if\edition\racketEd
  7829. \begin{center}
  7830. \begin{minipage}{\textwidth}
  7831. \begin{lstlisting}
  7832. if (eq? x 0)
  7833. goto block_1;
  7834. else
  7835. goto block_2;
  7836. \end{lstlisting}
  7837. \end{minipage}
  7838. \end{center}
  7839. \fi}
  7840. {\if\edition\pythonEd
  7841. \begin{center}
  7842. \begin{minipage}{\textwidth}
  7843. \begin{lstlisting}
  7844. if x == 0:
  7845. goto block_1;
  7846. else
  7847. goto block_2;
  7848. \end{lstlisting}
  7849. \end{minipage}
  7850. \end{center}
  7851. \fi}
  7852. Next consider the case for Boolean constants. We perform a kind of
  7853. partial evaluation\index{subject}{partial evaluation} and output
  7854. either the \code{thn} or \code{els} branch depending on whether the
  7855. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7856. following program.
  7857. {\if\edition\racketEd
  7858. \begin{lstlisting}
  7859. (if #t 42 777)
  7860. \end{lstlisting}
  7861. \fi}
  7862. {\if\edition\pythonEd
  7863. \begin{lstlisting}
  7864. 42 if True else 777
  7865. \end{lstlisting}
  7866. \fi}
  7867. %
  7868. \noindent Again, the two branches \code{42} and \code{777} were
  7869. compiled to \code{return} statements, so \code{explicate\_pred}
  7870. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7871. code for the ``then'' branch.
  7872. \begin{lstlisting}
  7873. return 42;
  7874. \end{lstlisting}
  7875. This case demonstrates that we sometimes discard the \code{thn} or
  7876. \code{els} blocks that are input to \code{explicate\_pred}.
  7877. The case for \key{if} expressions in \code{explicate\_pred} is
  7878. particularly illuminating because it deals with the challenges we
  7879. discussed above regarding nested \key{if} expressions
  7880. (Figure~\ref{fig:explicate-control-s1-38}). The
  7881. \racket{\lstinline{thn^}}\python{\code{body}} and
  7882. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7883. \key{if} inherit their context from the current one, that is,
  7884. predicate context. So you should recursively apply
  7885. \code{explicate\_pred} to the
  7886. \racket{\lstinline{thn^}}\python{\code{body}} and
  7887. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7888. those recursive calls, pass \code{thn} and \code{els} as the extra
  7889. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7890. inside each recursive call. As discussed above, to avoid duplicating
  7891. code, we need to add them to the dictionary of basic blocks so that we
  7892. can instead refer to them by name and execute them with a \key{goto}.
  7893. {\if\edition\pythonEd
  7894. %
  7895. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7896. three parameters: 1) the statement to be compiled, 2) the code for its
  7897. continuation, and 3) the dictionary of basic blocks. The
  7898. \code{explicate\_stmt} returns a list of statements and it may add to
  7899. the dictionary of basic blocks. The cases for assignment and an
  7900. expression-statement are given in full in the skeleton code: they
  7901. simply dispatch to \code{explicate\_assign} and
  7902. \code{explicate\_effect}, respectively. The case for \code{if}
  7903. statements is not given, and is similar to the case for \code{if}
  7904. expressions.
  7905. The \code{explicate\_control} function itself is given in
  7906. Figure~\ref{fig:explicate-control-Lif}. It applies
  7907. \code{explicate\_stmt} to each statement in the program, from back to
  7908. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7909. used as the continuation parameter in the next call to
  7910. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7911. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7912. the dictionary of basic blocks, labeling it as the ``start'' block.
  7913. %
  7914. \fi}
  7915. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7916. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7917. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7918. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7919. %% results from the two recursive calls. We complete the case for
  7920. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7921. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7922. %% the result $B_5$.
  7923. %% \[
  7924. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7925. %% \quad\Rightarrow\quad
  7926. %% B_5
  7927. %% \]
  7928. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7929. %% inherit the current context, so they are in tail position. Thus, the
  7930. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7931. %% \code{explicate\_tail}.
  7932. %% %
  7933. %% We need to pass $B_0$ as the accumulator argument for both of these
  7934. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7935. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7936. %% to the control-flow graph and obtain a promised goto $G_0$.
  7937. %% %
  7938. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7939. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7940. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7941. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7942. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7943. %% \[
  7944. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7945. %% \]
  7946. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7947. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7948. %% should not be confused with the labels for the blocks that appear in
  7949. %% the generated code. We initially construct unlabeled blocks; we only
  7950. %% attach labels to blocks when we add them to the control-flow graph, as
  7951. %% we see in the next case.
  7952. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7953. %% function. The context of the \key{if} is an assignment to some
  7954. %% variable $x$ and then the control continues to some promised block
  7955. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7956. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7957. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7958. %% branches of the \key{if} inherit the current context, so they are in
  7959. %% assignment positions. Let $B_2$ be the result of applying
  7960. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7961. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7962. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7963. %% the result of applying \code{explicate\_pred} to the predicate
  7964. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7965. %% translates to the promise $B_4$.
  7966. %% \[
  7967. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7968. %% \]
  7969. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7970. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7971. \code{remove\_complex\_operands} pass and then the
  7972. \code{explicate\_control} pass on the example program. We walk through
  7973. the output program.
  7974. %
  7975. Following the order of evaluation in the output of
  7976. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7977. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7978. in the predicate of the inner \key{if}. In the output of
  7979. \code{explicate\_control}, in the
  7980. block labeled \code{start}, are two assignment statements followed by a
  7981. \code{if} statement that branches to \code{block\_4} or
  7982. \code{block\_5}. The blocks associated with those labels contain the
  7983. translations of the code
  7984. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7985. and
  7986. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7987. respectively. In particular, we start \code{block\_4} with the
  7988. comparison
  7989. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7990. and then branch to \code{block\_2} or \code{block\_3},
  7991. which correspond to the two branches of the outer \key{if}, i.e.,
  7992. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7993. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7994. %
  7995. The story for \code{block\_5} is similar to that of \code{block\_4}.
  7996. %
  7997. \python{The \code{block\_1} corresponds to the \code{print} statement
  7998. at the end of the program.}
  7999. {\if\edition\racketEd
  8000. \subsection{Interactions between Explicate and Shrink}
  8001. The way in which the \code{shrink} pass transforms logical operations
  8002. such as \code{and} and \code{or} can impact the quality of code
  8003. generated by \code{explicate\_control}. For example, consider the
  8004. following program.
  8005. % cond_test_21.rkt, and_eq_input.py
  8006. \begin{lstlisting}
  8007. (if (and (eq? (read) 0) (eq? (read) 1))
  8008. 0
  8009. 42)
  8010. \end{lstlisting}
  8011. The \code{and} operation should transform into something that the
  8012. \code{explicate\_pred} function can still analyze and descend through to
  8013. reach the underlying \code{eq?} conditions. Ideally, your
  8014. \code{explicate\_control} pass should generate code similar to the
  8015. following for the above program.
  8016. \begin{center}
  8017. \begin{lstlisting}
  8018. start:
  8019. tmp1 = (read);
  8020. if (eq? tmp1 0) goto block40;
  8021. else goto block39;
  8022. block40:
  8023. tmp2 = (read);
  8024. if (eq? tmp2 1) goto block38;
  8025. else goto block39;
  8026. block38:
  8027. return 0;
  8028. block39:
  8029. return 42;
  8030. \end{lstlisting}
  8031. \end{center}
  8032. \fi}
  8033. \begin{exercise}\normalfont\normalsize
  8034. \racket{
  8035. Implement the pass \code{explicate\_control} by adding the cases for
  8036. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8037. \code{explicate\_assign} functions. Implement the auxiliary function
  8038. \code{explicate\_pred} for predicate contexts.}
  8039. \python{Implement \code{explicate\_control} pass with its
  8040. four auxiliary functions.}
  8041. %
  8042. Create test cases that exercise all of the new cases in the code for
  8043. this pass.
  8044. %
  8045. {\if\edition\racketEd
  8046. Add the following entry to the list of \code{passes} in
  8047. \code{run-tests.rkt} and then run this script to test your compiler.
  8048. \begin{lstlisting}
  8049. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8050. \end{lstlisting}
  8051. \fi}
  8052. \end{exercise}
  8053. \clearpage
  8054. \section{Select Instructions}
  8055. \label{sec:select-Lif}
  8056. \index{subject}{instruction selection}
  8057. The \code{select\_instructions} pass translates \LangCIf{} to
  8058. \LangXIfVar{}.
  8059. %
  8060. \racket{Recall that we implement this pass using three auxiliary
  8061. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  8062. $\Tail$ in \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  8063. %
  8064. \racket{For $\Atm$, we have new cases for the Booleans.}
  8065. %
  8066. \python{We begin with the Boolean constants.}
  8067. We take the usual approach of encoding them as integers.
  8068. \[
  8069. \TRUE{} \quad\Rightarrow\quad \key{1}
  8070. \qquad\qquad
  8071. \FALSE{} \quad\Rightarrow\quad \key{0}
  8072. \]
  8073. For translating statements, we discuss some of the cases. The
  8074. \code{not} operation can be implemented in terms of \code{xorq} as we
  8075. discussed at the beginning of this section. Given an assignment, if
  8076. the left-hand side variable is the same as the argument of \code{not},
  8077. then just the \code{xorq} instruction suffices.
  8078. \[
  8079. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8080. \quad\Rightarrow\quad
  8081. \key{xorq}~\key{\$}1\key{,}~\Var
  8082. \]
  8083. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8084. semantics of x86. In the following translation, let $\Arg$ be the
  8085. result of translating $\Atm$ to x86.
  8086. \[
  8087. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8088. \quad\Rightarrow\quad
  8089. \begin{array}{l}
  8090. \key{movq}~\Arg\key{,}~\Var\\
  8091. \key{xorq}~\key{\$}1\key{,}~\Var
  8092. \end{array}
  8093. \]
  8094. Next consider the cases for equality comparisons. Translating this
  8095. operation to x86 is slightly involved due to the unusual nature of the
  8096. \key{cmpq} instruction that we discussed in Section~\ref{sec:x86-if}.
  8097. We recommend translating an assignment with an equality on the
  8098. right-hand side into a sequence of three instructions. \\
  8099. \begin{tabular}{lll}
  8100. \begin{minipage}{0.4\textwidth}
  8101. \begin{lstlisting}
  8102. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8103. \end{lstlisting}
  8104. \end{minipage}
  8105. &
  8106. $\Rightarrow$
  8107. &
  8108. \begin{minipage}{0.4\textwidth}
  8109. \begin{lstlisting}
  8110. cmpq |$\Arg_2$|, |$\Arg_1$|
  8111. sete %al
  8112. movzbq %al, |$\Var$|
  8113. \end{lstlisting}
  8114. \end{minipage}
  8115. \end{tabular} \\
  8116. The translations for the other comparison operators are similar to the
  8117. above but use different condition codes for the \code{set} instruction.
  8118. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8119. \key{goto} and \key{if} statements. Both are straightforward to
  8120. translate to x86.}
  8121. %
  8122. A \key{goto} statement becomes a jump instruction.
  8123. \[
  8124. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8125. \]
  8126. %
  8127. An \key{if} statement becomes a compare instruction followed by a
  8128. conditional jump (for the ``then'' branch) and the fall-through is to
  8129. a regular jump (for the ``else'' branch).\\
  8130. \begin{tabular}{lll}
  8131. \begin{minipage}{0.4\textwidth}
  8132. \begin{lstlisting}
  8133. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8134. goto |$\ell_1$||$\racket{\key{;}}$|
  8135. else|$\python{\key{:}}$|
  8136. goto |$\ell_2$||$\racket{\key{;}}$|
  8137. \end{lstlisting}
  8138. \end{minipage}
  8139. &
  8140. $\Rightarrow$
  8141. &
  8142. \begin{minipage}{0.4\textwidth}
  8143. \begin{lstlisting}
  8144. cmpq |$\Arg_2$|, |$\Arg_1$|
  8145. je |$\ell_1$|
  8146. jmp |$\ell_2$|
  8147. \end{lstlisting}
  8148. \end{minipage}
  8149. \end{tabular} \\
  8150. Again, the translations for the other comparison operators are similar to the
  8151. above but use different condition codes for the conditional jump instruction.
  8152. \python{Regarding the \key{return} statement, we recommend treating it
  8153. as an assignment to the \key{rax} register followed by a jump to the
  8154. conclusion of the \code{main} function.}
  8155. \begin{exercise}\normalfont\normalsize
  8156. Expand your \code{select\_instructions} pass to handle the new
  8157. features of the \LangCIf{} language.
  8158. %
  8159. {\if\edition\racketEd
  8160. Add the following entry to the list of \code{passes} in
  8161. \code{run-tests.rkt}
  8162. \begin{lstlisting}
  8163. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8164. \end{lstlisting}
  8165. \fi}
  8166. %
  8167. Run the script to test your compiler on all the test programs.
  8168. \end{exercise}
  8169. \section{Register Allocation}
  8170. \label{sec:register-allocation-Lif}
  8171. \index{subject}{register allocation}
  8172. The changes required for compiling \LangIf{} affect liveness analysis,
  8173. building the interference graph, and assigning homes, but the graph
  8174. coloring algorithm itself does not change.
  8175. \subsection{Liveness Analysis}
  8176. \label{sec:liveness-analysis-Lif}
  8177. \index{subject}{liveness analysis}
  8178. Recall that for \LangVar{} we implemented liveness analysis for a
  8179. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8180. the addition of \key{if} expressions to \LangIf{},
  8181. \code{explicate\_control} produces many basic blocks.
  8182. %% We recommend that you create a new auxiliary function named
  8183. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8184. %% control-flow graph.
  8185. The first question is: in what order should we process the basic blocks?
  8186. Recall that to perform liveness analysis on a basic block we need to
  8187. know the live-after set for the last instruction in the block. If a
  8188. basic block has no successors (i.e. contains no jumps to other
  8189. blocks), then it has an empty live-after set and we can immediately
  8190. apply liveness analysis to it. If a basic block has some successors,
  8191. then we need to complete liveness analysis on those blocks
  8192. first. These ordering constraints are the reverse of a
  8193. \emph{topological order}\index{subject}{topological order} on a graph
  8194. representation of the program. In particular, the \emph{control flow
  8195. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8196. of a program has a node for each basic block and an edge for each jump
  8197. from one block to another. It is straightforward to generate a CFG
  8198. from the dictionary of basic blocks. One then transposes the CFG and
  8199. applies the topological sort algorithm.
  8200. %
  8201. %
  8202. \racket{We recommend using the \code{tsort} and \code{transpose}
  8203. functions of the Racket \code{graph} package to accomplish this.}
  8204. %
  8205. \python{We provide implementations of \code{topological\_sort} and
  8206. \code{transpose} in the file \code{graph.py} of the support code.}
  8207. %
  8208. As an aside, a topological ordering is only guaranteed to exist if the
  8209. graph does not contain any cycles. This is the case for the
  8210. control-flow graphs that we generate from \LangIf{} programs.
  8211. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8212. and learn how to handle cycles in the control-flow graph.
  8213. \racket{You'll need to construct a directed graph to represent the
  8214. control-flow graph. Do not use the \code{directed-graph} of the
  8215. \code{graph} package because that only allows at most one edge
  8216. between each pair of vertices, but a control-flow graph may have
  8217. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8218. file in the support code implements a graph representation that
  8219. allows multiple edges between a pair of vertices.}
  8220. {\if\edition\racketEd
  8221. The next question is how to analyze jump instructions. Recall that in
  8222. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8223. \code{label->live} that maps each label to the set of live locations
  8224. at the beginning of its block. We use \code{label->live} to determine
  8225. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8226. that we have many basic blocks, \code{label->live} needs to be updated
  8227. as we process the blocks. In particular, after performing liveness
  8228. analysis on a block, we take the live-before set of its first
  8229. instruction and associate that with the block's label in the
  8230. \code{label->live} alist.
  8231. \fi}
  8232. %
  8233. {\if\edition\pythonEd
  8234. %
  8235. The next question is how to analyze jump instructions. The locations
  8236. that are live before a \code{jmp} should be the locations in
  8237. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8238. maintaining a dictionary named \code{live\_before\_block} that maps each
  8239. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8240. block. After performing liveness analysis on each block, we take the
  8241. live-before set of its first instruction and associate that with the
  8242. block's label in the \code{live\_before\_block} dictionary.
  8243. %
  8244. \fi}
  8245. In \LangXIfVar{} we also have the conditional jump
  8246. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8247. this instruction is particularly interesting because, during
  8248. compilation, we do not know which way a conditional jump will go. So
  8249. we do not know whether to use the live-before set for the block
  8250. associated with the $\itm{label}$ or the live-before set for the
  8251. following instruction. However, there is no harm to the correctness
  8252. of the generated code if we classify more locations as live than the
  8253. ones that are truly live during one particular execution of the
  8254. instruction. Thus, we can take the union of the live-before sets from
  8255. the following instruction and from the mapping for $\itm{label}$ in
  8256. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8257. The auxiliary functions for computing the variables in an
  8258. instruction's argument and for computing the variables read-from ($R$)
  8259. or written-to ($W$) by an instruction need to be updated to handle the
  8260. new kinds of arguments and instructions in \LangXIfVar{}.
  8261. \begin{exercise}\normalfont\normalsize
  8262. {\if\edition\racketEd
  8263. %
  8264. Update the \code{uncover\_live} pass to apply liveness analysis to
  8265. every basic block in the program.
  8266. %
  8267. Add the following entry to the list of \code{passes} in the
  8268. \code{run-tests.rkt} script.
  8269. \begin{lstlisting}
  8270. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8271. \end{lstlisting}
  8272. \fi}
  8273. {\if\edition\pythonEd
  8274. %
  8275. Update the \code{uncover\_live} function to perform liveness analysis,
  8276. in reverse topological order, on all of the basic blocks in the
  8277. program.
  8278. %
  8279. \fi}
  8280. % Check that the live-after sets that you generate for
  8281. % example X matches the following... -Jeremy
  8282. \end{exercise}
  8283. \subsection{Build the Interference Graph}
  8284. \label{sec:build-interference-Lif}
  8285. Many of the new instructions in \LangXIfVar{} can be handled in the
  8286. same way as the instructions in \LangXVar{}.
  8287. % Thus, if your code was
  8288. % already quite general, it will not need to be changed to handle the
  8289. % new instructions. If your code is not general enough, we recommend that
  8290. % you change your code to be more general. For example, you can factor
  8291. % out the computing of the the read and write sets for each kind of
  8292. % instruction into auxiliary functions.
  8293. %
  8294. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8295. similar to the \key{movq} instruction. See rule number 1 in
  8296. Section~\ref{sec:build-interference}.
  8297. \begin{exercise}\normalfont\normalsize
  8298. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8299. {\if\edition\racketEd
  8300. Add the following entries to the list of \code{passes} in the
  8301. \code{run-tests.rkt} script.
  8302. \begin{lstlisting}
  8303. (list "build_interference" build_interference interp-pseudo-x86-1)
  8304. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8305. \end{lstlisting}
  8306. \fi}
  8307. % Check that the interference graph that you generate for
  8308. % example X matches the following graph G... -Jeremy
  8309. \end{exercise}
  8310. \section{Patch Instructions}
  8311. The new instructions \key{cmpq} and \key{movzbq} have some special
  8312. restrictions that need to be handled in the \code{patch\_instructions}
  8313. pass.
  8314. %
  8315. The second argument of the \key{cmpq} instruction must not be an
  8316. immediate value (such as an integer). So if you are comparing two
  8317. immediates, we recommend inserting a \key{movq} instruction to put the
  8318. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8319. one memory reference.
  8320. %
  8321. The second argument of the \key{movzbq} must be a register.
  8322. \begin{exercise}\normalfont\normalsize
  8323. %
  8324. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8325. %
  8326. {\if\edition\racketEd
  8327. Add the following entry to the list of \code{passes} in
  8328. \code{run-tests.rkt} and then run this script to test your compiler.
  8329. \begin{lstlisting}
  8330. (list "patch_instructions" patch_instructions interp-x86-1)
  8331. \end{lstlisting}
  8332. \fi}
  8333. \end{exercise}
  8334. {\if\edition\pythonEd
  8335. \section{Prelude and Conclusion}
  8336. \label{sec:prelude-conclusion-cond}
  8337. The generation of the \code{main} function with its prelude and
  8338. conclusion must change to accommodate how the program now consists of
  8339. one or more basic blocks. After the prelude in \code{main}, jump to
  8340. the \code{start} block. Place the conclusion in a basic block labeled
  8341. with \code{conclusion}.
  8342. \fi}
  8343. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8344. \LangIf{} translated to x86, showing the results of
  8345. \code{explicate\_control}, \code{select\_instructions}, and the final
  8346. x86 assembly.
  8347. \begin{figure}[tbp]
  8348. \begin{tcolorbox}[colback=white]
  8349. {\if\edition\racketEd
  8350. \begin{tabular}{lll}
  8351. \begin{minipage}{0.4\textwidth}
  8352. % cond_test_20.rkt, eq_input.py
  8353. \begin{lstlisting}
  8354. (if (eq? (read) 1) 42 0)
  8355. \end{lstlisting}
  8356. $\Downarrow$
  8357. \begin{lstlisting}
  8358. start:
  8359. tmp7951 = (read);
  8360. if (eq? tmp7951 1)
  8361. goto block7952;
  8362. else
  8363. goto block7953;
  8364. block7952:
  8365. return 42;
  8366. block7953:
  8367. return 0;
  8368. \end{lstlisting}
  8369. $\Downarrow$
  8370. \begin{lstlisting}
  8371. start:
  8372. callq read_int
  8373. movq %rax, tmp7951
  8374. cmpq $1, tmp7951
  8375. je block7952
  8376. jmp block7953
  8377. block7953:
  8378. movq $0, %rax
  8379. jmp conclusion
  8380. block7952:
  8381. movq $42, %rax
  8382. jmp conclusion
  8383. \end{lstlisting}
  8384. \end{minipage}
  8385. &
  8386. $\Rightarrow\qquad$
  8387. \begin{minipage}{0.4\textwidth}
  8388. \begin{lstlisting}
  8389. start:
  8390. callq read_int
  8391. movq %rax, %rcx
  8392. cmpq $1, %rcx
  8393. je block7952
  8394. jmp block7953
  8395. block7953:
  8396. movq $0, %rax
  8397. jmp conclusion
  8398. block7952:
  8399. movq $42, %rax
  8400. jmp conclusion
  8401. .globl main
  8402. main:
  8403. pushq %rbp
  8404. movq %rsp, %rbp
  8405. pushq %r13
  8406. pushq %r12
  8407. pushq %rbx
  8408. pushq %r14
  8409. subq $0, %rsp
  8410. jmp start
  8411. conclusion:
  8412. addq $0, %rsp
  8413. popq %r14
  8414. popq %rbx
  8415. popq %r12
  8416. popq %r13
  8417. popq %rbp
  8418. retq
  8419. \end{lstlisting}
  8420. \end{minipage}
  8421. \end{tabular}
  8422. \fi}
  8423. {\if\edition\pythonEd
  8424. \begin{tabular}{lll}
  8425. \begin{minipage}{0.4\textwidth}
  8426. % cond_test_20.rkt, eq_input.py
  8427. \begin{lstlisting}
  8428. print(42 if input_int() == 1 else 0)
  8429. \end{lstlisting}
  8430. $\Downarrow$
  8431. \begin{lstlisting}
  8432. start:
  8433. tmp_0 = input_int()
  8434. if tmp_0 == 1:
  8435. goto block_3
  8436. else:
  8437. goto block_4
  8438. block_3:
  8439. tmp_1 = 42
  8440. goto block_2
  8441. block_4:
  8442. tmp_1 = 0
  8443. goto block_2
  8444. block_2:
  8445. print(tmp_1)
  8446. return 0
  8447. \end{lstlisting}
  8448. $\Downarrow$
  8449. \begin{lstlisting}
  8450. start:
  8451. callq read_int
  8452. movq %rax, tmp_0
  8453. cmpq 1, tmp_0
  8454. je block_3
  8455. jmp block_4
  8456. block_3:
  8457. movq 42, tmp_1
  8458. jmp block_2
  8459. block_4:
  8460. movq 0, tmp_1
  8461. jmp block_2
  8462. block_2:
  8463. movq tmp_1, %rdi
  8464. callq print_int
  8465. movq 0, %rax
  8466. jmp conclusion
  8467. \end{lstlisting}
  8468. \end{minipage}
  8469. &
  8470. $\Rightarrow\qquad$
  8471. \begin{minipage}{0.4\textwidth}
  8472. \begin{lstlisting}
  8473. .globl main
  8474. main:
  8475. pushq %rbp
  8476. movq %rsp, %rbp
  8477. subq $0, %rsp
  8478. jmp start
  8479. start:
  8480. callq read_int
  8481. movq %rax, %rcx
  8482. cmpq $1, %rcx
  8483. je block_3
  8484. jmp block_4
  8485. block_3:
  8486. movq $42, %rcx
  8487. jmp block_2
  8488. block_4:
  8489. movq $0, %rcx
  8490. jmp block_2
  8491. block_2:
  8492. movq %rcx, %rdi
  8493. callq print_int
  8494. movq $0, %rax
  8495. jmp conclusion
  8496. conclusion:
  8497. addq $0, %rsp
  8498. popq %rbp
  8499. retq
  8500. \end{lstlisting}
  8501. \end{minipage}
  8502. \end{tabular}
  8503. \fi}
  8504. \end{tcolorbox}
  8505. \caption{Example compilation of an \key{if} expression to x86, showing
  8506. the results of \code{explicate\_control},
  8507. \code{select\_instructions}, and the final x86 assembly code. }
  8508. \label{fig:if-example-x86}
  8509. \end{figure}
  8510. \begin{figure}[tbp]
  8511. \begin{tcolorbox}[colback=white]
  8512. {\if\edition\racketEd
  8513. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8514. \node (Lif) at (0,2) {\large \LangIf{}};
  8515. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8516. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8517. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8518. \node (Lif-5) at (9,0) {\large \LangIfANF{}};
  8519. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8520. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8521. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8522. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8523. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8524. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8525. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8526. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8527. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8528. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8529. \path[->,bend left=15] (Lif-4) edge [right] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8530. \path[->,bend right=15] (Lif-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8531. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  8532. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8533. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8534. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8535. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8536. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8537. \end{tikzpicture}
  8538. \fi}
  8539. {\if\edition\pythonEd
  8540. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8541. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8542. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8543. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8544. \node (C-1) at (3,0) {\large \LangCIf{}};
  8545. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8546. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8547. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8548. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8549. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8550. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8551. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8552. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8553. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8554. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8555. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8556. \end{tikzpicture}
  8557. \fi}
  8558. \end{tcolorbox}
  8559. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8560. \label{fig:Lif-passes}
  8561. \end{figure}
  8562. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8563. compilation of \LangIf{}.
  8564. \section{Challenge: Optimize Blocks and Remove Jumps}
  8565. \label{sec:opt-jumps}
  8566. We discuss two optional challenges that involve optimizing the
  8567. control-flow of the program.
  8568. \subsection{Optimize Blocks}
  8569. The algorithm for \code{explicate\_control} that we discussed in
  8570. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8571. blocks. It creates a basic block whenever a continuation \emph{might}
  8572. get used more than once (e.g., whenever the \code{cont} parameter is
  8573. passed into two or more recursive calls). However, some continuation
  8574. arguments may not be used at all. For example, consider the case for
  8575. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8576. \code{els} continuation.
  8577. %
  8578. {\if\edition\racketEd
  8579. The following example program falls into this
  8580. case, and it creates two unused blocks.
  8581. \begin{center}
  8582. \begin{tabular}{lll}
  8583. \begin{minipage}{0.4\textwidth}
  8584. % cond_test_82.rkt
  8585. \begin{lstlisting}
  8586. (let ([y (if #t
  8587. (read)
  8588. (if (eq? (read) 0)
  8589. 777
  8590. (let ([x (read)])
  8591. (+ 1 x))))])
  8592. (+ y 2))
  8593. \end{lstlisting}
  8594. \end{minipage}
  8595. &
  8596. $\Rightarrow$
  8597. &
  8598. \begin{minipage}{0.55\textwidth}
  8599. \begin{lstlisting}
  8600. start:
  8601. y = (read);
  8602. goto block_5;
  8603. block_5:
  8604. return (+ y 2);
  8605. block_6:
  8606. y = 777;
  8607. goto block_5;
  8608. block_7:
  8609. x = (read);
  8610. y = (+ 1 x2);
  8611. goto block_5;
  8612. \end{lstlisting}
  8613. \end{minipage}
  8614. \end{tabular}
  8615. \end{center}
  8616. \fi}
  8617. So the question is how can we decide whether to create a basic block?
  8618. \emph{Lazy evaluation}\index{subject}{lazy
  8619. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8620. delaying the creation of a basic block until the point in time where
  8621. we know it will be used.
  8622. %
  8623. {\if\edition\racketEd
  8624. %
  8625. Racket provides support for
  8626. lazy evaluation with the
  8627. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8628. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8629. \index{subject}{delay} creates a
  8630. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8631. expressions is postponed. When \key{(force}
  8632. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8633. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8634. result of $e_n$ is cached in the promise and returned. If \code{force}
  8635. is applied again to the same promise, then the cached result is
  8636. returned. If \code{force} is applied to an argument that is not a
  8637. promise, \code{force} simply returns the argument.
  8638. %
  8639. \fi}
  8640. %
  8641. {\if\edition\pythonEd
  8642. %
  8643. While Python does not provide direct support for lazy evaluation, it
  8644. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8645. by wrapping it inside a function with no parameters. We can
  8646. \emph{force} its evaluation by calling the function. However, in some
  8647. cases of \code{explicate\_pred}, etc., we will return a list of
  8648. statements and in other cases we will return a function that computes
  8649. a list of statements. We use the term \emph{promise} to refer to a
  8650. value that may be delayed. To uniformly deal with
  8651. promises, we define the following \code{force} function that checks
  8652. whether its input is delayed (i.e., whether it is a function) and then
  8653. either 1) calls the function, or 2) returns the input.
  8654. \begin{lstlisting}
  8655. def force(promise):
  8656. if isinstance(promise, types.FunctionType):
  8657. return promise()
  8658. else:
  8659. return promise
  8660. \end{lstlisting}
  8661. %
  8662. \fi}
  8663. We use promises for the input and output of the functions
  8664. \code{explicate\_pred}, \code{explicate\_assign},
  8665. %
  8666. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8667. %
  8668. So instead of taking and returning \racket{$\Tail$
  8669. expressions}\python{lists of statements}, they take and return
  8670. promises. Furthermore, when we come to a situation in which a
  8671. continuation might be used more than once, as in the case for
  8672. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8673. that creates a basic block for each continuation (if there is not
  8674. already one) and then returns a \code{goto} statement to that basic
  8675. block. When we come to a situation where we have a promise but need an
  8676. actual piece of code, e.g. to create a larger piece of code with a
  8677. constructor such as \code{Seq}, then insert a call to \code{force}.
  8678. %
  8679. {\if\edition\racketEd
  8680. %
  8681. Also we must modify the \code{create\_block} function to begin with
  8682. \code{delay} to create a promise. When forced, this promise forces the
  8683. original promise. If that returns a \code{Goto} (because the block was
  8684. already added to \code{basic-blocks}), then we return the
  8685. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8686. return a \code{Goto} to the new label.
  8687. \begin{center}
  8688. \begin{minipage}{\textwidth}
  8689. \begin{lstlisting}
  8690. (define (create_block tail)
  8691. (delay
  8692. (define t (force tail))
  8693. (match t
  8694. [(Goto label) (Goto label)]
  8695. [else
  8696. (let ([label (gensym 'block)])
  8697. (set! basic-blocks (cons (cons label t) basic-blocks))
  8698. (Goto label))]))
  8699. \end{lstlisting}
  8700. \end{minipage}
  8701. \end{center}
  8702. \fi}
  8703. {\if\edition\pythonEd
  8704. %
  8705. Here is the new version of the \code{create\_block} auxiliary function
  8706. that works on promises and that checks whether the block consists of a
  8707. solitary \code{goto} statement.\\
  8708. \begin{minipage}{\textwidth}
  8709. \begin{lstlisting}
  8710. def create_block(promise, basic_blocks):
  8711. stmts = force(promise)
  8712. match stmts:
  8713. case [Goto(l)]:
  8714. return Goto(l)
  8715. case _:
  8716. label = label_name(generate_name('block'))
  8717. basic_blocks[label] = stmts
  8718. return Goto(label)
  8719. \end{lstlisting}
  8720. \end{minipage}
  8721. \fi}
  8722. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8723. improved \code{explicate\_control} on the above example. As you can
  8724. see, the number of basic blocks has been reduced from 4 blocks (see
  8725. Figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8726. \begin{figure}[tbp]
  8727. \begin{tcolorbox}[colback=white]
  8728. {\if\edition\racketEd
  8729. \begin{tabular}{lll}
  8730. \begin{minipage}{0.4\textwidth}
  8731. % cond_test_82.rkt
  8732. \begin{lstlisting}
  8733. (let ([y (if #t
  8734. (read)
  8735. (if (eq? (read) 0)
  8736. 777
  8737. (let ([x (read)])
  8738. (+ 1 x))))])
  8739. (+ y 2))
  8740. \end{lstlisting}
  8741. \end{minipage}
  8742. &
  8743. $\Rightarrow$
  8744. &
  8745. \begin{minipage}{0.55\textwidth}
  8746. \begin{lstlisting}
  8747. start:
  8748. y = (read);
  8749. goto block_5;
  8750. block_5:
  8751. return (+ y 2);
  8752. \end{lstlisting}
  8753. \end{minipage}
  8754. \end{tabular}
  8755. \fi}
  8756. {\if\edition\pythonEd
  8757. \begin{tabular}{lll}
  8758. \begin{minipage}{0.4\textwidth}
  8759. % cond_test_41.rkt
  8760. \begin{lstlisting}
  8761. x = input_int()
  8762. y = input_int()
  8763. print(y + 2 \
  8764. if (x == 0 \
  8765. if x < 1 \
  8766. else x == 2) \
  8767. else y + 10)
  8768. \end{lstlisting}
  8769. \end{minipage}
  8770. &
  8771. $\Rightarrow$
  8772. &
  8773. \begin{minipage}{0.55\textwidth}
  8774. \begin{lstlisting}
  8775. start:
  8776. x = input_int()
  8777. y = input_int()
  8778. if x < 1:
  8779. goto block_4
  8780. else:
  8781. goto block_5
  8782. block_4:
  8783. if x == 0:
  8784. goto block_2
  8785. else:
  8786. goto block_3
  8787. block_5:
  8788. if x == 2:
  8789. goto block_2
  8790. else:
  8791. goto block_3
  8792. block_2:
  8793. tmp_0 = y + 2
  8794. goto block_1
  8795. block_3:
  8796. tmp_0 = y + 10
  8797. goto block_1
  8798. block_1:
  8799. print(tmp_0)
  8800. return 0
  8801. \end{lstlisting}
  8802. \end{minipage}
  8803. \end{tabular}
  8804. \fi}
  8805. \end{tcolorbox}
  8806. \caption{Translation from \LangIf{} to \LangCIf{}
  8807. via the improved \code{explicate\_control}.}
  8808. \label{fig:explicate-control-challenge}
  8809. \end{figure}
  8810. %% Recall that in the example output of \code{explicate\_control} in
  8811. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8812. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8813. %% block. The first goal of this challenge assignment is to remove those
  8814. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8815. %% \code{explicate\_control} on the left and shows the result of bypassing
  8816. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8817. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8818. %% \code{block55}. The optimized code on the right of
  8819. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8820. %% \code{then} branch jumping directly to \code{block55}. The story is
  8821. %% similar for the \code{else} branch, as well as for the two branches in
  8822. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8823. %% have been optimized in this way, there are no longer any jumps to
  8824. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8825. %% \begin{figure}[tbp]
  8826. %% \begin{tabular}{lll}
  8827. %% \begin{minipage}{0.4\textwidth}
  8828. %% \begin{lstlisting}
  8829. %% block62:
  8830. %% tmp54 = (read);
  8831. %% if (eq? tmp54 2) then
  8832. %% goto block59;
  8833. %% else
  8834. %% goto block60;
  8835. %% block61:
  8836. %% tmp53 = (read);
  8837. %% if (eq? tmp53 0) then
  8838. %% goto block57;
  8839. %% else
  8840. %% goto block58;
  8841. %% block60:
  8842. %% goto block56;
  8843. %% block59:
  8844. %% goto block55;
  8845. %% block58:
  8846. %% goto block56;
  8847. %% block57:
  8848. %% goto block55;
  8849. %% block56:
  8850. %% return (+ 700 77);
  8851. %% block55:
  8852. %% return (+ 10 32);
  8853. %% start:
  8854. %% tmp52 = (read);
  8855. %% if (eq? tmp52 1) then
  8856. %% goto block61;
  8857. %% else
  8858. %% goto block62;
  8859. %% \end{lstlisting}
  8860. %% \end{minipage}
  8861. %% &
  8862. %% $\Rightarrow$
  8863. %% &
  8864. %% \begin{minipage}{0.55\textwidth}
  8865. %% \begin{lstlisting}
  8866. %% block62:
  8867. %% tmp54 = (read);
  8868. %% if (eq? tmp54 2) then
  8869. %% goto block55;
  8870. %% else
  8871. %% goto block56;
  8872. %% block61:
  8873. %% tmp53 = (read);
  8874. %% if (eq? tmp53 0) then
  8875. %% goto block55;
  8876. %% else
  8877. %% goto block56;
  8878. %% block56:
  8879. %% return (+ 700 77);
  8880. %% block55:
  8881. %% return (+ 10 32);
  8882. %% start:
  8883. %% tmp52 = (read);
  8884. %% if (eq? tmp52 1) then
  8885. %% goto block61;
  8886. %% else
  8887. %% goto block62;
  8888. %% \end{lstlisting}
  8889. %% \end{minipage}
  8890. %% \end{tabular}
  8891. %% \caption{Optimize jumps by removing trivial blocks.}
  8892. %% \label{fig:optimize-jumps}
  8893. %% \end{figure}
  8894. %% The name of this pass is \code{optimize-jumps}. We recommend
  8895. %% implementing this pass in two phases. The first phrase builds a hash
  8896. %% table that maps labels to possibly improved labels. The second phase
  8897. %% changes the target of each \code{goto} to use the improved label. If
  8898. %% the label is for a trivial block, then the hash table should map the
  8899. %% label to the first non-trivial block that can be reached from this
  8900. %% label by jumping through trivial blocks. If the label is for a
  8901. %% non-trivial block, then the hash table should map the label to itself;
  8902. %% we do not want to change jumps to non-trivial blocks.
  8903. %% The first phase can be accomplished by constructing an empty hash
  8904. %% table, call it \code{short-cut}, and then iterating over the control
  8905. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8906. %% then update the hash table, mapping the block's source to the target
  8907. %% of the \code{goto}. Also, the hash table may already have mapped some
  8908. %% labels to the block's source, to you must iterate through the hash
  8909. %% table and update all of those so that they instead map to the target
  8910. %% of the \code{goto}.
  8911. %% For the second phase, we recommend iterating through the $\Tail$ of
  8912. %% each block in the program, updating the target of every \code{goto}
  8913. %% according to the mapping in \code{short-cut}.
  8914. \begin{exercise}\normalfont\normalsize
  8915. Implement the improvements to the \code{explicate\_control} pass.
  8916. Check that it removes trivial blocks in a few example programs. Then
  8917. check that your compiler still passes all of your tests.
  8918. \end{exercise}
  8919. \subsection{Remove Jumps}
  8920. There is an opportunity for removing jumps that is apparent in the
  8921. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8922. ends with a jump to \code{block\_5} and there are no other jumps to
  8923. \code{block\_5} in the rest of the program. In this situation we can
  8924. avoid the runtime overhead of this jump by merging \code{block\_5}
  8925. into the preceding block, in this case the \code{start} block.
  8926. Figure~\ref{fig:remove-jumps} shows the output of
  8927. \code{allocate\_registers} on the left and the result of this
  8928. optimization on the right.
  8929. \begin{figure}[tbp]
  8930. \begin{tcolorbox}[colback=white]
  8931. {\if\edition\racketEd
  8932. \begin{tabular}{lll}
  8933. \begin{minipage}{0.5\textwidth}
  8934. % cond_test_82.rkt
  8935. \begin{lstlisting}
  8936. start:
  8937. callq read_int
  8938. movq %rax, %rcx
  8939. jmp block_5
  8940. block_5:
  8941. movq %rcx, %rax
  8942. addq $2, %rax
  8943. jmp conclusion
  8944. \end{lstlisting}
  8945. \end{minipage}
  8946. &
  8947. $\Rightarrow\qquad$
  8948. \begin{minipage}{0.4\textwidth}
  8949. \begin{lstlisting}
  8950. start:
  8951. callq read_int
  8952. movq %rax, %rcx
  8953. movq %rcx, %rax
  8954. addq $2, %rax
  8955. jmp conclusion
  8956. \end{lstlisting}
  8957. \end{minipage}
  8958. \end{tabular}
  8959. \fi}
  8960. {\if\edition\pythonEd
  8961. \begin{tabular}{lll}
  8962. \begin{minipage}{0.5\textwidth}
  8963. % cond_test_20.rkt
  8964. \begin{lstlisting}
  8965. start:
  8966. callq read_int
  8967. movq %rax, tmp_0
  8968. cmpq 1, tmp_0
  8969. je block_3
  8970. jmp block_4
  8971. block_3:
  8972. movq 42, tmp_1
  8973. jmp block_2
  8974. block_4:
  8975. movq 0, tmp_1
  8976. jmp block_2
  8977. block_2:
  8978. movq tmp_1, %rdi
  8979. callq print_int
  8980. movq 0, %rax
  8981. jmp conclusion
  8982. \end{lstlisting}
  8983. \end{minipage}
  8984. &
  8985. $\Rightarrow\qquad$
  8986. \begin{minipage}{0.4\textwidth}
  8987. \begin{lstlisting}
  8988. start:
  8989. callq read_int
  8990. movq %rax, tmp_0
  8991. cmpq 1, tmp_0
  8992. je block_3
  8993. movq 0, tmp_1
  8994. jmp block_2
  8995. block_3:
  8996. movq 42, tmp_1
  8997. jmp block_2
  8998. block_2:
  8999. movq tmp_1, %rdi
  9000. callq print_int
  9001. movq 0, %rax
  9002. jmp conclusion
  9003. \end{lstlisting}
  9004. \end{minipage}
  9005. \end{tabular}
  9006. \fi}
  9007. \end{tcolorbox}
  9008. \caption{Merging basic blocks by removing unnecessary jumps.}
  9009. \label{fig:remove-jumps}
  9010. \end{figure}
  9011. \begin{exercise}\normalfont\normalsize
  9012. %
  9013. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9014. into their preceding basic block, when there is only one preceding
  9015. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9016. %
  9017. {\if\edition\racketEd
  9018. In the \code{run-tests.rkt} script, add the following entry to the
  9019. list of \code{passes} between \code{allocate\_registers}
  9020. and \code{patch\_instructions}.
  9021. \begin{lstlisting}
  9022. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  9023. \end{lstlisting}
  9024. \fi}
  9025. %
  9026. Run the script to test your compiler.
  9027. %
  9028. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9029. blocks on several test programs.
  9030. \end{exercise}
  9031. \section{Further Reading}
  9032. \label{sec:cond-further-reading}
  9033. The algorithm for the \code{explicate\_control} pass is based on the
  9034. \code{expose-basic-blocks} pass in the course notes of
  9035. \citet{Dybvig:2010aa}.
  9036. %
  9037. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9038. \citet{Appel:2003fk}, and is related to translations into continuation
  9039. passing
  9040. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9041. %
  9042. The treatment of conditionals in the \code{explicate\_control} pass is
  9043. similar to short-cut boolean
  9044. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9045. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9046. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9047. \chapter{Loops and Dataflow Analysis}
  9048. \label{ch:Lwhile}
  9049. % TODO: define R'_8
  9050. % TODO: multi-graph
  9051. {\if\edition\racketEd
  9052. %
  9053. In this chapter we study two features that are the hallmarks of
  9054. imperative programming languages: loops and assignments to local
  9055. variables. The following example demonstrates these new features by
  9056. computing the sum of the first five positive integers.
  9057. % similar to loop_test_1.rkt
  9058. \begin{lstlisting}
  9059. (let ([sum 0])
  9060. (let ([i 5])
  9061. (begin
  9062. (while (> i 0)
  9063. (begin
  9064. (set! sum (+ sum i))
  9065. (set! i (- i 1))))
  9066. sum)))
  9067. \end{lstlisting}
  9068. The \code{while} loop consists of a condition and a
  9069. body\footnote{The \code{while} loop is not a built-in
  9070. feature of the Racket language, but Racket includes many looping
  9071. constructs and it is straightforward to define \code{while} as a
  9072. macro.}. The body is evaluated repeatedly so long as the condition
  9073. remains true.
  9074. %
  9075. The \code{set!} consists of a variable and a right-hand-side
  9076. expression. The \code{set!} updates value of the variable to the
  9077. value of the right-hand-side.
  9078. %
  9079. The primary purpose of both the \code{while} loop and \code{set!} is
  9080. to cause side effects, so they do not have a meaningful result
  9081. value. Instead their result is the \code{\#<void>} value. The
  9082. expression \code{(void)} is an explicit way to create the
  9083. \code{\#<void>} value and it has type \code{Void}. The
  9084. \code{\#<void>} value can be passed around just like other values
  9085. inside an \LangLoop{} program and it can be compared for equality with
  9086. another \code{\#<void>} value. However, there are no other operations
  9087. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  9088. Racket defines the \code{void?} predicate that returns \code{\#t}
  9089. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9090. %
  9091. \footnote{Racket's \code{Void} type corresponds to what is often
  9092. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9093. by a single value \code{\#<void>} which corresponds to \code{unit}
  9094. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9095. %
  9096. With the addition of side-effecting features such as \code{while} loop
  9097. and \code{set!}, it is helpful to also include in a language feature
  9098. for sequencing side effects: the \code{begin} expression. It consists
  9099. of one or more subexpressions that are evaluated left-to-right.
  9100. %
  9101. \fi}
  9102. {\if\edition\pythonEd
  9103. %
  9104. In this chapter we study loops, one of the hallmarks of imperative
  9105. programming languages. The following example demonstrates the
  9106. \code{while} loop by computing the sum of the first five positive
  9107. integers.
  9108. \begin{lstlisting}
  9109. sum = 0
  9110. i = 5
  9111. while i > 0:
  9112. sum = sum + i
  9113. i = i - 1
  9114. print(sum)
  9115. \end{lstlisting}
  9116. The \code{while} loop consists of a condition expression and a body (a
  9117. sequence of statements). The body is evaluated repeatedly so long as
  9118. the condition remains true.
  9119. %
  9120. \fi}
  9121. \section{The \LangLoop{} Language}
  9122. \newcommand{\LwhileGrammarRacket}{
  9123. \begin{array}{lcl}
  9124. \Type &::=& \key{Void}\\
  9125. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9126. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9127. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9128. \end{array}
  9129. }
  9130. \newcommand{\LwhileASTRacket}{
  9131. \begin{array}{lcl}
  9132. \Type &::=& \key{Void}\\
  9133. \Exp &::=& \SETBANG{\Var}{\Exp}
  9134. \MID \BEGIN{\Exp^{*}}{\Exp}
  9135. \MID \WHILE{\Exp}{\Exp}
  9136. \MID \VOID{}
  9137. \end{array}
  9138. }
  9139. \newcommand{\LwhileGrammarPython}{
  9140. \begin{array}{rcl}
  9141. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9142. \end{array}
  9143. }
  9144. \newcommand{\LwhileASTPython}{
  9145. \begin{array}{lcl}
  9146. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9147. \end{array}
  9148. }
  9149. \begin{figure}[tp]
  9150. \centering
  9151. \begin{tcolorbox}[colback=white]
  9152. \small
  9153. {\if\edition\racketEd
  9154. \[
  9155. \begin{array}{l}
  9156. \gray{\LintGrammarRacket{}} \\ \hline
  9157. \gray{\LvarGrammarRacket{}} \\ \hline
  9158. \gray{\LifGrammarRacket{}} \\ \hline
  9159. \LwhileGrammarRacket \\
  9160. \begin{array}{lcl}
  9161. \LangLoopM{} &::=& \Exp
  9162. \end{array}
  9163. \end{array}
  9164. \]
  9165. \fi}
  9166. {\if\edition\pythonEd
  9167. \[
  9168. \begin{array}{l}
  9169. \gray{\LintGrammarPython} \\ \hline
  9170. \gray{\LvarGrammarPython} \\ \hline
  9171. \gray{\LifGrammarPython} \\ \hline
  9172. \LwhileGrammarPython \\
  9173. \begin{array}{rcl}
  9174. \LangLoopM{} &::=& \Stmt^{*}
  9175. \end{array}
  9176. \end{array}
  9177. \]
  9178. \fi}
  9179. \end{tcolorbox}
  9180. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9181. \label{fig:Lwhile-concrete-syntax}
  9182. \end{figure}
  9183. \begin{figure}[tp]
  9184. \centering
  9185. \begin{tcolorbox}[colback=white]
  9186. \small
  9187. {\if\edition\racketEd
  9188. \[
  9189. \begin{array}{l}
  9190. \gray{\LintOpAST} \\ \hline
  9191. \gray{\LvarASTRacket{}} \\ \hline
  9192. \gray{\LifASTRacket{}} \\ \hline
  9193. \LwhileASTRacket{} \\
  9194. \begin{array}{lcl}
  9195. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9196. \end{array}
  9197. \end{array}
  9198. \]
  9199. \fi}
  9200. {\if\edition\pythonEd
  9201. \[
  9202. \begin{array}{l}
  9203. \gray{\LintASTPython} \\ \hline
  9204. \gray{\LvarASTPython} \\ \hline
  9205. \gray{\LifASTPython} \\ \hline
  9206. \LwhileASTPython \\
  9207. \begin{array}{lcl}
  9208. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9209. \end{array}
  9210. \end{array}
  9211. \]
  9212. \fi}
  9213. \end{tcolorbox}
  9214. \python{
  9215. \index{subject}{While@\texttt{While}}
  9216. }
  9217. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9218. \label{fig:Lwhile-syntax}
  9219. \end{figure}
  9220. The concrete syntax of \LangLoop{} is defined in
  9221. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9222. in Figure~\ref{fig:Lwhile-syntax}.
  9223. %
  9224. The definitional interpreter for \LangLoop{} is shown in
  9225. Figure~\ref{fig:interp-Lwhile}.
  9226. %
  9227. {\if\edition\racketEd
  9228. %
  9229. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9230. and \code{Void} and we make changes to the cases for \code{Var} and
  9231. \code{Let} regarding variables. To support assignment to variables and
  9232. to make their lifetimes indefinite (see the second example in
  9233. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9234. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9235. value.
  9236. %
  9237. Now to discuss the new cases. For \code{SetBang}, we find the
  9238. variable in the environment to obtain a boxed value and then we change
  9239. it using \code{set-box!} to the result of evaluating the right-hand
  9240. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9241. %
  9242. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9243. if the result is true, 2) evaluate the body.
  9244. The result value of a \code{while} loop is also \code{\#<void>}.
  9245. %
  9246. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9247. subexpressions \itm{es} for their effects and then evaluates
  9248. and returns the result from \itm{body}.
  9249. %
  9250. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9251. %
  9252. \fi}
  9253. {\if\edition\pythonEd
  9254. %
  9255. We add a new case for \code{While} in the \code{interp\_stmts}
  9256. function, where we repeatedly interpret the \code{body} so long as the
  9257. \code{test} expression remains true.
  9258. %
  9259. \fi}
  9260. \begin{figure}[tbp]
  9261. \begin{tcolorbox}[colback=white]
  9262. {\if\edition\racketEd
  9263. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9264. (define interp-Lwhile-class
  9265. (class interp-Lif-class
  9266. (super-new)
  9267. (define/override ((interp-exp env) e)
  9268. (define recur (interp-exp env))
  9269. (match e
  9270. [(Let x e body)
  9271. (define new-env (dict-set env x (box (recur e))))
  9272. ((interp-exp new-env) body)]
  9273. [(Var x) (unbox (dict-ref env x))]
  9274. [(SetBang x rhs)
  9275. (set-box! (dict-ref env x) (recur rhs))]
  9276. [(WhileLoop cnd body)
  9277. (define (loop)
  9278. (cond [(recur cnd) (recur body) (loop)]
  9279. [else (void)]))
  9280. (loop)]
  9281. [(Begin es body)
  9282. (for ([e es]) (recur e))
  9283. (recur body)]
  9284. [(Void) (void)]
  9285. [else ((super interp-exp env) e)]))
  9286. ))
  9287. (define (interp-Lwhile p)
  9288. (send (new interp-Lwhile-class) interp-program p))
  9289. \end{lstlisting}
  9290. \fi}
  9291. {\if\edition\pythonEd
  9292. \begin{lstlisting}
  9293. class InterpLwhile(InterpLif):
  9294. def interp_stmts(self, ss, env):
  9295. if len(ss) == 0:
  9296. return
  9297. match ss[0]:
  9298. case While(test, body, []):
  9299. while self.interp_exp(test, env):
  9300. self.interp_stmts(body, env)
  9301. return self.interp_stmts(ss[1:], env)
  9302. case _:
  9303. return super().interp_stmts(ss, env)
  9304. \end{lstlisting}
  9305. \fi}
  9306. \end{tcolorbox}
  9307. \caption{Interpreter for \LangLoop{}.}
  9308. \label{fig:interp-Lwhile}
  9309. \end{figure}
  9310. The type checker for \LangLoop{} is defined in
  9311. Figure~\ref{fig:type-check-Lwhile}.
  9312. %
  9313. {\if\edition\racketEd
  9314. %
  9315. The type checking of the \code{SetBang} expression requires the type
  9316. of the variable and the right-hand-side to agree. The result type is
  9317. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9318. and the result type is \code{Void}. For \code{Begin}, the result type
  9319. is the type of its last subexpression.
  9320. %
  9321. \fi}
  9322. %
  9323. {\if\edition\pythonEd
  9324. %
  9325. A \code{while} loop is well typed if the type of the \code{test}
  9326. expression is \code{bool} and the statements in the \code{body} are
  9327. well typed.
  9328. %
  9329. \fi}
  9330. \begin{figure}[tbp]
  9331. \begin{tcolorbox}[colback=white]
  9332. {\if\edition\racketEd
  9333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9334. (define type-check-Lwhile-class
  9335. (class type-check-Lif-class
  9336. (super-new)
  9337. (inherit check-type-equal?)
  9338. (define/override (type-check-exp env)
  9339. (lambda (e)
  9340. (define recur (type-check-exp env))
  9341. (match e
  9342. [(SetBang x rhs)
  9343. (define-values (rhs^ rhsT) (recur rhs))
  9344. (define varT (dict-ref env x))
  9345. (check-type-equal? rhsT varT e)
  9346. (values (SetBang x rhs^) 'Void)]
  9347. [(WhileLoop cnd body)
  9348. (define-values (cnd^ Tc) (recur cnd))
  9349. (check-type-equal? Tc 'Boolean e)
  9350. (define-values (body^ Tbody) ((type-check-exp env) body))
  9351. (values (WhileLoop cnd^ body^) 'Void)]
  9352. [(Begin es body)
  9353. (define-values (es^ ts)
  9354. (for/lists (l1 l2) ([e es]) (recur e)))
  9355. (define-values (body^ Tbody) (recur body))
  9356. (values (Begin es^ body^) Tbody)]
  9357. [else ((super type-check-exp env) e)])))
  9358. ))
  9359. (define (type-check-Lwhile p)
  9360. (send (new type-check-Lwhile-class) type-check-program p))
  9361. \end{lstlisting}
  9362. \fi}
  9363. {\if\edition\pythonEd
  9364. \begin{lstlisting}
  9365. class TypeCheckLwhile(TypeCheckLif):
  9366. def type_check_stmts(self, ss, env):
  9367. if len(ss) == 0:
  9368. return
  9369. match ss[0]:
  9370. case While(test, body, []):
  9371. test_t = self.type_check_exp(test, env)
  9372. check_type_equal(bool, test_t, test)
  9373. body_t = self.type_check_stmts(body, env)
  9374. return self.type_check_stmts(ss[1:], env)
  9375. case _:
  9376. return super().type_check_stmts(ss, env)
  9377. \end{lstlisting}
  9378. \fi}
  9379. \end{tcolorbox}
  9380. \caption{Type checker for the \LangLoop{} language.}
  9381. \label{fig:type-check-Lwhile}
  9382. \end{figure}
  9383. {\if\edition\racketEd
  9384. %
  9385. At first glance, the translation of these language features to x86
  9386. seems straightforward because the \LangCIf{} intermediate language
  9387. already supports all of the ingredients that we need: assignment,
  9388. \code{goto}, conditional branching, and sequencing. However, there are
  9389. complications that arise which we discuss in the next section. After
  9390. that we introduce the changes necessary to the existing passes.
  9391. %
  9392. \fi}
  9393. {\if\edition\pythonEd
  9394. %
  9395. At first glance, the translation of \code{while} loops to x86 seems
  9396. straightforward because the \LangCIf{} intermediate language already
  9397. supports \code{goto} and conditional branching. However, there are
  9398. complications that arise which we discuss in the next section. After
  9399. that we introduce the changes necessary to the existing passes.
  9400. %
  9401. \fi}
  9402. \section{Cyclic Control Flow and Dataflow Analysis}
  9403. \label{sec:dataflow-analysis}
  9404. Up until this point the programs generated in
  9405. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9406. \code{while} loop introduces a cycle. But does that matter?
  9407. %
  9408. Indeed it does. Recall that for register allocation, the compiler
  9409. performs liveness analysis to determine which variables can share the
  9410. same register. To accomplish this we analyzed the control-flow graph
  9411. in reverse topological order
  9412. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9413. only well-defined for acyclic graphs.
  9414. Let us return to the example of computing the sum of the first five
  9415. positive integers. Here is the program after instruction selection but
  9416. before register allocation.
  9417. \begin{center}
  9418. {\if\edition\racketEd
  9419. \begin{minipage}{0.45\textwidth}
  9420. \begin{lstlisting}
  9421. (define (main) : Integer
  9422. mainstart:
  9423. movq $0, sum
  9424. movq $5, i
  9425. jmp block5
  9426. block5:
  9427. movq i, tmp3
  9428. cmpq tmp3, $0
  9429. jl block7
  9430. jmp block8
  9431. \end{lstlisting}
  9432. \end{minipage}
  9433. \begin{minipage}{0.45\textwidth}
  9434. \begin{lstlisting}
  9435. block7:
  9436. addq i, sum
  9437. movq $1, tmp4
  9438. negq tmp4
  9439. addq tmp4, i
  9440. jmp block5
  9441. block8:
  9442. movq $27, %rax
  9443. addq sum, %rax
  9444. jmp mainconclusion
  9445. )
  9446. \end{lstlisting}
  9447. \end{minipage}
  9448. \fi}
  9449. {\if\edition\pythonEd
  9450. \begin{minipage}{0.45\textwidth}
  9451. \begin{lstlisting}
  9452. mainstart:
  9453. movq $0, sum
  9454. movq $5, i
  9455. jmp block5
  9456. block5:
  9457. cmpq $0, i
  9458. jg block7
  9459. jmp block8
  9460. \end{lstlisting}
  9461. \end{minipage}
  9462. \begin{minipage}{0.45\textwidth}
  9463. \begin{lstlisting}
  9464. block7:
  9465. addq i, sum
  9466. subq $1, i
  9467. jmp block5
  9468. block8:
  9469. movq sum, %rdi
  9470. callq print_int
  9471. movq $0, %rax
  9472. jmp mainconclusion
  9473. \end{lstlisting}
  9474. \end{minipage}
  9475. \fi}
  9476. \end{center}
  9477. Recall that liveness analysis works backwards, starting at the end
  9478. of each function. For this example we could start with \code{block8}
  9479. because we know what is live at the beginning of the conclusion,
  9480. just \code{rax} and \code{rsp}. So the live-before set
  9481. for \code{block8} is \code{\{rsp,sum\}}.
  9482. %
  9483. Next we might try to analyze \code{block5} or \code{block7}, but
  9484. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9485. we are stuck.
  9486. The way out of this impasse is to realize that we can compute an
  9487. under-approximation of each live-before set by starting with empty
  9488. live-after sets. By \emph{under-approximation}, we mean that the set
  9489. only contains variables that are live for some execution of the
  9490. program, but the set may be missing some variables that are live.
  9491. Next, the under-approximations for each block can be improved by 1)
  9492. updating the live-after set for each block using the approximate
  9493. live-before sets from the other blocks and 2) perform liveness
  9494. analysis again on each block. In fact, by iterating this process, the
  9495. under-approximations eventually become the correct solutions!
  9496. %
  9497. This approach of iteratively analyzing a control-flow graph is
  9498. applicable to many static analysis problems and goes by the name
  9499. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9500. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9501. Washington.
  9502. Let us apply this approach to the above example. We use the empty set
  9503. for the initial live-before set for each block. Let $m_0$ be the
  9504. following mapping from label names to sets of locations (variables and
  9505. registers).
  9506. \begin{center}
  9507. \begin{lstlisting}
  9508. mainstart: {}, block5: {}, block7: {}, block8: {}
  9509. \end{lstlisting}
  9510. \end{center}
  9511. Using the above live-before approximations, we determine the
  9512. live-after for each block and then apply liveness analysis to each
  9513. block. This produces our next approximation $m_1$ of the live-before
  9514. sets.
  9515. \begin{center}
  9516. \begin{lstlisting}
  9517. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9518. \end{lstlisting}
  9519. \end{center}
  9520. For the second round, the live-after for \code{mainstart} is the
  9521. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9522. liveness analysis for \code{mainstart} computes the empty set. The
  9523. live-after for \code{block5} is the union of the live-before sets for
  9524. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9525. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9526. sum\}}. The live-after for \code{block7} is the live-before for
  9527. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9528. So the liveness analysis for \code{block7} remains \code{\{i,
  9529. sum\}}. Together these yield the following approximation $m_2$ of
  9530. the live-before sets.
  9531. \begin{center}
  9532. \begin{lstlisting}
  9533. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9534. \end{lstlisting}
  9535. \end{center}
  9536. In the preceding iteration, only \code{block5} changed, so we can
  9537. limit our attention to \code{mainstart} and \code{block7}, the two
  9538. blocks that jump to \code{block5}. As a result, the live-before sets
  9539. for \code{mainstart} and \code{block7} are updated to include
  9540. \code{rsp}, yielding the following approximation $m_3$.
  9541. \begin{center}
  9542. \begin{lstlisting}
  9543. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9544. \end{lstlisting}
  9545. \end{center}
  9546. Because \code{block7} changed, we analyze \code{block5} once more, but
  9547. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9548. our approximations have converged, so $m_3$ is the solution.
  9549. This iteration process is guaranteed to converge to a solution by the
  9550. Kleene Fixed-Point Theorem, a general theorem about functions on
  9551. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9552. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9553. elements, a least element $\bot$ (pronounced bottom), and a join
  9554. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9555. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9556. working with join semi-lattices.} When two elements are ordered $m_i
  9557. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9558. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9559. approximation than $m_i$. The bottom element $\bot$ represents the
  9560. complete lack of information, i.e., the worst approximation. The join
  9561. operator takes two lattice elements and combines their information,
  9562. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9563. bound}
  9564. A dataflow analysis typically involves two lattices: one lattice to
  9565. represent abstract states and another lattice that aggregates the
  9566. abstract states of all the blocks in the control-flow graph. For
  9567. liveness analysis, an abstract state is a set of locations. We form
  9568. the lattice $L$ by taking its elements to be sets of locations, the
  9569. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9570. set, and the join operator to be set union.
  9571. %
  9572. We form a second lattice $M$ by taking its elements to be mappings
  9573. from the block labels to sets of locations (elements of $L$). We
  9574. order the mappings point-wise, using the ordering of $L$. So given any
  9575. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9576. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9577. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9578. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9579. We can think of one iteration of liveness analysis applied to the
  9580. whole program as being a function $f$ on the lattice $M$. It takes a
  9581. mapping as input and computes a new mapping.
  9582. \[
  9583. f(m_i) = m_{i+1}
  9584. \]
  9585. Next let us think for a moment about what a final solution $m_s$
  9586. should look like. If we perform liveness analysis using the solution
  9587. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9588. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9589. \[
  9590. f(m_s) = m_s
  9591. \]
  9592. Furthermore, the solution should only include locations that are
  9593. forced to be there by performing liveness analysis on the program, so
  9594. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9595. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9596. monotone (better inputs produce better outputs), then the least fixed
  9597. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9598. chain} obtained by starting at $\bot$ and iterating $f$ as
  9599. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9600. \[
  9601. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9602. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9603. \]
  9604. When a lattice contains only finitely-long ascending chains, then
  9605. every Kleene chain tops out at some fixed point after some number of
  9606. iterations of $f$.
  9607. \[
  9608. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9609. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9610. \]
  9611. The liveness analysis is indeed a monotone function and the lattice
  9612. $M$ only has finitely-long ascending chains because there are only a
  9613. finite number of variables and blocks in the program. Thus we are
  9614. guaranteed that iteratively applying liveness analysis to all blocks
  9615. in the program will eventually produce the least fixed point solution.
  9616. Next let us consider dataflow analysis in general and discuss the
  9617. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9618. %
  9619. The algorithm has four parameters: the control-flow graph \code{G}, a
  9620. function \code{transfer} that applies the analysis to one block, the
  9621. \code{bottom} and \code{join} operator for the lattice of abstract
  9622. states. The \code{analyze\_dataflow} function is formulated as a
  9623. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9624. function come from the predecessor nodes in the control-flow
  9625. graph. However, liveness analysis is a \emph{backward} dataflow
  9626. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9627. function with the transpose of the control-flow graph.
  9628. The algorithm begins by creating the bottom mapping, represented by a
  9629. hash table. It then pushes all of the nodes in the control-flow graph
  9630. onto the work list (a queue). The algorithm repeats the \code{while}
  9631. loop as long as there are items in the work list. In each iteration, a
  9632. node is popped from the work list and processed. The \code{input} for
  9633. the node is computed by taking the join of the abstract states of all
  9634. the predecessor nodes. The \code{transfer} function is then applied to
  9635. obtain the \code{output} abstract state. If the output differs from
  9636. the previous state for this block, the mapping for this block is
  9637. updated and its successor nodes are pushed onto the work list.
  9638. \begin{figure}[tb]
  9639. \begin{tcolorbox}[colback=white]
  9640. {\if\edition\racketEd
  9641. \begin{lstlisting}
  9642. (define (analyze_dataflow G transfer bottom join)
  9643. (define mapping (make-hash))
  9644. (for ([v (in-vertices G)])
  9645. (dict-set! mapping v bottom))
  9646. (define worklist (make-queue))
  9647. (for ([v (in-vertices G)])
  9648. (enqueue! worklist v))
  9649. (define trans-G (transpose G))
  9650. (while (not (queue-empty? worklist))
  9651. (define node (dequeue! worklist))
  9652. (define input (for/fold ([state bottom])
  9653. ([pred (in-neighbors trans-G node)])
  9654. (join state (dict-ref mapping pred))))
  9655. (define output (transfer node input))
  9656. (cond [(not (equal? output (dict-ref mapping node)))
  9657. (dict-set! mapping node output)
  9658. (for ([v (in-neighbors G node)])
  9659. (enqueue! worklist v))]))
  9660. mapping)
  9661. \end{lstlisting}
  9662. \fi}
  9663. {\if\edition\pythonEd
  9664. \begin{lstlisting}
  9665. def analyze_dataflow(G, transfer, bottom, join):
  9666. trans_G = transpose(G)
  9667. mapping = dict((v, bottom) for v in G.vertices())
  9668. worklist = deque(G.vertices)
  9669. while worklist:
  9670. node = worklist.pop()
  9671. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9672. input = reduce(join, inputs, bottom)
  9673. output = transfer(node, input)
  9674. if output != mapping[node]:
  9675. mapping[node] = output
  9676. worklist.extend(G.adjacent(node))
  9677. \end{lstlisting}
  9678. \fi}
  9679. \end{tcolorbox}
  9680. \caption{Generic work list algorithm for dataflow analysis}
  9681. \label{fig:generic-dataflow}
  9682. \end{figure}
  9683. {\if\edition\racketEd
  9684. \section{Mutable Variables \& Remove Complex Operands}
  9685. There is a subtle interaction between the
  9686. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9687. and the left-to-right order of evaluation of Racket. Consider the
  9688. following example.
  9689. \begin{lstlisting}
  9690. (let ([x 2])
  9691. (+ x (begin (set! x 40) x)))
  9692. \end{lstlisting}
  9693. The result of this program is \code{42} because the first read from
  9694. \code{x} produces \code{2} and the second produces \code{40}. However,
  9695. if we naively apply the \code{remove\_complex\_operands} pass to this
  9696. example we obtain the following program whose result is \code{80}!
  9697. \begin{lstlisting}
  9698. (let ([x 2])
  9699. (let ([tmp (begin (set! x 40) x)])
  9700. (+ x tmp)))
  9701. \end{lstlisting}
  9702. The problem is that, with mutable variables, the ordering between
  9703. reads and writes is important, and the
  9704. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9705. before the first read of \code{x}.
  9706. We recommend solving this problem by giving special treatment to reads
  9707. from mutable variables, that is, variables that occur on the left-hand
  9708. side of a \code{set!}. We mark each read from a mutable variable with
  9709. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9710. that the read operation is effectful in that it can produce different
  9711. results at different points in time. Let's apply this idea to the
  9712. following variation that also involves a variable that is not mutated.
  9713. % loop_test_24.rkt
  9714. \begin{lstlisting}
  9715. (let ([x 2])
  9716. (let ([y 0])
  9717. (+ y (+ x (begin (set! x 40) x)))))
  9718. \end{lstlisting}
  9719. We first analyze the above program to discover that variable \code{x}
  9720. is mutable but \code{y} is not. We then transform the program as
  9721. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9722. \begin{lstlisting}
  9723. (let ([x 2])
  9724. (let ([y 0])
  9725. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9726. \end{lstlisting}
  9727. Now that we have a clear distinction between reads from mutable and
  9728. immutable variables, we can apply the \code{remove\_complex\_operands}
  9729. pass, where reads from immutable variables are still classified as
  9730. atomic expressions but reads from mutable variables are classified as
  9731. complex. Thus, \code{remove\_complex\_operands} yields the following
  9732. program.\\
  9733. \begin{minipage}{\textwidth}
  9734. \begin{lstlisting}
  9735. (let ([x 2])
  9736. (let ([y 0])
  9737. (+ y (let ([t1 (get! x)])
  9738. (let ([t2 (begin (set! x 40) (get! x))])
  9739. (+ t1 t2))))))
  9740. \end{lstlisting}
  9741. \end{minipage}
  9742. The temporary variable \code{t1} gets the value of \code{x} before the
  9743. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9744. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9745. do not generate a temporary variable for the occurrence of \code{y}
  9746. because it's an immutable variable. We want to avoid such unnecessary
  9747. extra temporaries because they would needless increase the number of
  9748. variables, making it more likely for some of them to be spilled. The
  9749. result of this program is \code{42}, the same as the result prior to
  9750. \code{remove\_complex\_operands}.
  9751. The approach that we've sketched above requires only a small
  9752. modification to \code{remove\_complex\_operands} to handle
  9753. \code{get!}. However, it requires a new pass, called
  9754. \code{uncover-get!}, that we discuss in
  9755. Section~\ref{sec:uncover-get-bang}.
  9756. As an aside, this problematic interaction between \code{set!} and the
  9757. pass \code{remove\_complex\_operands} is particular to Racket and not
  9758. its predecessor, the Scheme language. The key difference is that
  9759. Scheme does not specify an order of evaluation for the arguments of an
  9760. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9761. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9762. would be correct results for the example program. Interestingly,
  9763. Racket is implemented on top of the Chez Scheme
  9764. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9765. presented in this section (using extra \code{let} bindings to control
  9766. the order of evaluation) is used in the translation from Racket to
  9767. Scheme~\citep{Flatt:2019tb}.
  9768. \fi} % racket
  9769. Having discussed the complications that arise from adding support for
  9770. assignment and loops, we turn to discussing the individual compilation
  9771. passes.
  9772. {\if\edition\racketEd
  9773. \section{Uncover \texttt{get!}}
  9774. \label{sec:uncover-get-bang}
  9775. The goal of this pass it to mark uses of mutable variables so that
  9776. \code{remove\_complex\_operands} can treat them as complex expressions
  9777. and thereby preserve their ordering relative to the side-effects in
  9778. other operands. So the first step is to collect all the mutable
  9779. variables. We recommend creating an auxiliary function for this,
  9780. named \code{collect-set!}, that recursively traverses expressions,
  9781. returning the set of all variables that occur on the left-hand side of a
  9782. \code{set!}. Here's an excerpt of its implementation.
  9783. \begin{center}
  9784. \begin{minipage}{\textwidth}
  9785. \begin{lstlisting}
  9786. (define (collect-set! e)
  9787. (match e
  9788. [(Var x) (set)]
  9789. [(Int n) (set)]
  9790. [(Let x rhs body)
  9791. (set-union (collect-set! rhs) (collect-set! body))]
  9792. [(SetBang var rhs)
  9793. (set-union (set var) (collect-set! rhs))]
  9794. ...))
  9795. \end{lstlisting}
  9796. \end{minipage}
  9797. \end{center}
  9798. By placing this pass after \code{uniquify}, we need not worry about
  9799. variable shadowing and our logic for \code{Let} can remain simple, as
  9800. in the excerpt above.
  9801. The second step is to mark the occurrences of the mutable variables
  9802. with the new \code{GetBang} AST node (\code{get!} in concrete
  9803. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9804. function, which takes two parameters: the set of mutable variables
  9805. \code{set!-vars}, and the expression \code{e} to be processed. The
  9806. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9807. mutable variable or leaves it alone if not.
  9808. \begin{center}
  9809. \begin{minipage}{\textwidth}
  9810. \begin{lstlisting}
  9811. (define ((uncover-get!-exp set!-vars) e)
  9812. (match e
  9813. [(Var x)
  9814. (if (set-member? set!-vars x)
  9815. (GetBang x)
  9816. (Var x))]
  9817. ...))
  9818. \end{lstlisting}
  9819. \end{minipage}
  9820. \end{center}
  9821. To wrap things up, define the \code{uncover-get!} function for
  9822. processing a whole program, using \code{collect-set!} to obtain the
  9823. set of mutable variables and then \code{uncover-get!-exp} to replace
  9824. their occurrences with \code{GetBang}.
  9825. \fi}
  9826. \section{Remove Complex Operands}
  9827. \label{sec:rco-loop}
  9828. {\if\edition\racketEd
  9829. %
  9830. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9831. \code{while} are all complex expressions. The subexpressions of
  9832. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9833. %
  9834. \fi}
  9835. {\if\edition\pythonEd
  9836. %
  9837. The change needed for this pass is to add a case for the \code{while}
  9838. statement. The condition of a \code{while} loop is allowed to be a
  9839. complex expression, just like the condition of the \code{if}
  9840. statement.
  9841. %
  9842. \fi}
  9843. %
  9844. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9845. \LangLoopANF{} of this pass.
  9846. \newcommand{\LwhileMonadASTRacket}{
  9847. \begin{array}{rcl}
  9848. \Atm &::=& \VOID{} \\
  9849. \Exp &::=& \GETBANG{\Var}
  9850. \MID \SETBANG{\Var}{\Exp}
  9851. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9852. &\MID& \WHILE{\Exp}{\Exp}
  9853. \end{array}
  9854. }
  9855. \newcommand{\LwhileMonadASTPython}{
  9856. \begin{array}{rcl}
  9857. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9858. \end{array}
  9859. }
  9860. \begin{figure}[tp]
  9861. \centering
  9862. \begin{tcolorbox}[colback=white]
  9863. \small
  9864. {\if\edition\racketEd
  9865. \[
  9866. \begin{array}{l}
  9867. \gray{\LvarMonadASTRacket} \\ \hline
  9868. \gray{\LifMonadASTRacket} \\ \hline
  9869. \LwhileMonadASTRacket \\
  9870. \begin{array}{rcl}
  9871. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9872. \end{array}
  9873. \end{array}
  9874. \]
  9875. \fi}
  9876. {\if\edition\pythonEd
  9877. \[
  9878. \begin{array}{l}
  9879. \gray{\LvarMonadASTPython} \\ \hline
  9880. \gray{\LifMonadASTPython} \\ \hline
  9881. \LwhileMonadASTPython \\
  9882. \begin{array}{rcl}
  9883. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9884. \end{array}
  9885. \end{array}
  9886. %% \begin{array}{rcl}
  9887. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9888. %% \Exp &::=& \Atm \MID \READ{} \\
  9889. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9890. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9891. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9892. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9893. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9894. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9895. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9896. %% \end{array}
  9897. \]
  9898. \fi}
  9899. \end{tcolorbox}
  9900. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9901. \label{fig:Lwhile-anf-syntax}
  9902. \end{figure}
  9903. {\if\edition\racketEd
  9904. %
  9905. As usual, when a complex expression appears in a grammar position that
  9906. needs to be atomic, such as the argument of a primitive operator, we
  9907. must introduce a temporary variable and bind it to the complex
  9908. expression. This approach applies, unchanged, to handle the new
  9909. language forms. For example, in the following code there are two
  9910. \code{begin} expressions appearing as arguments to the \code{+}
  9911. operator. The output of \code{rco\_exp} is shown below, in which the
  9912. \code{begin} expressions have been bound to temporary
  9913. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9914. allowed to have arbitrary expressions in their right-hand-side
  9915. expression, so it is fine to place \code{begin} there.
  9916. %
  9917. \begin{center}
  9918. \begin{tabular}{lcl}
  9919. \begin{minipage}{0.4\textwidth}
  9920. \begin{lstlisting}
  9921. (let ([x2 10])
  9922. (let ([y3 0])
  9923. (+ (+ (begin
  9924. (set! y3 (read))
  9925. (get! x2))
  9926. (begin
  9927. (set! x2 (read))
  9928. (get! y3)))
  9929. (get! x2))))
  9930. \end{lstlisting}
  9931. \end{minipage}
  9932. &
  9933. $\Rightarrow$
  9934. &
  9935. \begin{minipage}{0.4\textwidth}
  9936. \begin{lstlisting}
  9937. (let ([x2 10])
  9938. (let ([y3 0])
  9939. (let ([tmp4 (begin
  9940. (set! y3 (read))
  9941. x2)])
  9942. (let ([tmp5 (begin
  9943. (set! x2 (read))
  9944. y3)])
  9945. (let ([tmp6 (+ tmp4 tmp5)])
  9946. (let ([tmp7 x2])
  9947. (+ tmp6 tmp7)))))))
  9948. \end{lstlisting}
  9949. \end{minipage}
  9950. \end{tabular}
  9951. \end{center}
  9952. \fi}
  9953. \section{Explicate Control \racket{and \LangCLoop{}}}
  9954. \label{sec:explicate-loop}
  9955. \newcommand{\CloopASTRacket}{
  9956. \begin{array}{lcl}
  9957. \Atm &::=& \VOID \\
  9958. \Stmt &::=& \READ{}
  9959. \end{array}
  9960. }
  9961. {\if\edition\racketEd
  9962. Recall that in the \code{explicate\_control} pass we define one helper
  9963. function for each kind of position in the program. For the \LangVar{}
  9964. language of integers and variables we needed assignment and tail
  9965. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9966. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9967. another kind of position: effect position. Except for the last
  9968. subexpression, the subexpressions inside a \code{begin} are evaluated
  9969. only for their effect. Their result values are discarded. We can
  9970. generate better code by taking this fact into account.
  9971. The output language of \code{explicate\_control} is \LangCLoop{}
  9972. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9973. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9974. and that \code{read} may appear as a statement. The most significant
  9975. difference between the programs generated by \code{explicate\_control}
  9976. in Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9977. chapter is that the control-flow graphs of the later may contain
  9978. cycles.
  9979. \begin{figure}[tp]
  9980. \begin{tcolorbox}[colback=white]
  9981. \small
  9982. \[
  9983. \begin{array}{l}
  9984. \gray{\CvarASTRacket} \\ \hline
  9985. \gray{\CifASTRacket} \\ \hline
  9986. \CloopASTRacket \\
  9987. \begin{array}{lcl}
  9988. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9989. \end{array}
  9990. \end{array}
  9991. \]
  9992. \end{tcolorbox}
  9993. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9994. \label{fig:c7-syntax}
  9995. \end{figure}
  9996. The new auxiliary function \code{explicate\_effect} takes an
  9997. expression (in an effect position) and the code for its
  9998. continuation. The function returns a $\Tail$ that includes the
  9999. generated code for the input expression followed by the
  10000. continuation. If the expression is obviously pure, that is, never
  10001. causes side effects, then the expression can be removed, so the result
  10002. is just the continuation.
  10003. %
  10004. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10005. interesting; the generated code is depicted in the following diagram.
  10006. \begin{center}
  10007. \begin{minipage}{0.3\textwidth}
  10008. \xymatrix{
  10009. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10010. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10011. & *+[F]{\txt{\itm{cont}}} \\
  10012. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10013. }
  10014. \end{minipage}
  10015. \end{center}
  10016. We start by creating a fresh label $\itm{loop}$ for the top of the
  10017. loop. Next, recursively process the \itm{body} (in effect position)
  10018. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10019. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10020. \itm{body'} as the then-branch and the continuation block as the
  10021. else-branch. The result should be added to the dictionary of
  10022. \code{basic-blocks} with the label \itm{loop}. The result for the
  10023. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10024. The auxiliary functions for tail, assignment, and predicate positions
  10025. need to be updated. The three new language forms, \code{while},
  10026. \code{set!}, and \code{begin}, can appear in assignment and tail
  10027. positions. Only \code{begin} may appear in predicate positions; the
  10028. other two have result type \code{Void}.
  10029. \fi}
  10030. %
  10031. {\if\edition\pythonEd
  10032. %
  10033. The output of this pass is the language \LangCIf{}. No new language
  10034. features are needed in the output because a \code{while} loop can be
  10035. expressed in terms of \code{goto} and \code{if} statements, which are
  10036. already in \LangCIf{}.
  10037. %
  10038. Add a case for the \code{while} statement to the
  10039. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10040. the condition expression.
  10041. %
  10042. \fi}
  10043. {\if\edition\racketEd
  10044. \section{Select Instructions}
  10045. \label{sec:select-instructions-loop}
  10046. Only two small additions are needed in the \code{select\_instructions}
  10047. pass to handle the changes to \LangCLoop{}. First, to handle the
  10048. addition of \VOID{} we simply translate it to \code{0}. Second,
  10049. \code{read} may appear as a stand-alone statement instead of only
  10050. appearing on the right-hand side of an assignment statement. The code
  10051. generation is nearly identical to the one for assignment; just leave
  10052. off the instruction for moving the result into the left-hand side.
  10053. \fi}
  10054. \section{Register Allocation}
  10055. \label{sec:register-allocation-loop}
  10056. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10057. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10058. which complicates the liveness analysis needed for register
  10059. allocation.
  10060. %
  10061. We recommend using the generic \code{analyze\_dataflow} function that
  10062. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10063. perform liveness analysis, replacing the code in
  10064. \code{uncover\_live} that processed the basic blocks in topological
  10065. order (Section~\ref{sec:liveness-analysis-Lif}).
  10066. The \code{analyze\_dataflow} function has four parameters.
  10067. \begin{enumerate}
  10068. \item The first parameter \code{G} should be passed the transpose
  10069. of the control-flow graph.
  10070. \item The second parameter \code{transfer} should be passed a function
  10071. that applies liveness analysis to a basic block. It takes two
  10072. parameters: the label for the block to analyze and the live-after
  10073. set for that block. The transfer function should return the
  10074. live-before set for the block.
  10075. %
  10076. \racket{Also, as a side-effect, it should update the block's
  10077. $\itm{info}$ with the liveness information for each instruction.}
  10078. %
  10079. \python{Also, as a side-effect, it should update the live-before and
  10080. live-after sets for each instruction.}
  10081. %
  10082. To implement the \code{transfer} function, you should be able to
  10083. reuse the code you already have for analyzing basic blocks.
  10084. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10085. \code{bottom} and \code{join} for the lattice of abstract states,
  10086. i.e. sets of locations. For liveness analysis, the bottom of the
  10087. lattice is the empty set and the join operator is set union.
  10088. \end{enumerate}
  10089. \begin{figure}[p]
  10090. \begin{tcolorbox}[colback=white]
  10091. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10092. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10093. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10094. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10095. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10096. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10097. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10098. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10099. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10100. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10101. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10102. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10103. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10104. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10105. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10106. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10107. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10108. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10109. %% \path[->,bend left=15] (Lfun) edge [above] node
  10110. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10111. \path[->,bend left=15] (Lfun) edge [above] node
  10112. {\ttfamily\footnotesize shrink} (Lfun-2);
  10113. \path[->,bend left=15] (Lfun-2) edge [above] node
  10114. {\ttfamily\footnotesize uniquify} (F1-4);
  10115. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10116. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10117. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10118. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10119. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10120. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10121. %% \path[->,bend right=15] (F1-2) edge [above] node
  10122. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10123. %% \path[->,bend right=15] (F1-3) edge [above] node
  10124. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10125. \path[->,bend left=15] (F1-4) edge [above] node
  10126. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10127. \path[->,bend left=15] (F1-5) edge [right] node
  10128. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10129. \path[->,bend right=15] (F1-6) edge [above] node
  10130. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10131. \path[->,bend left=15] (C3-2) edge [left] node
  10132. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10133. \path[->,bend right=15] (x86-2) edge [left] node
  10134. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10135. \path[->,bend right=15] (x86-2-1) edge [below] node
  10136. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10137. \path[->,bend right=15] (x86-2-2) edge [left] node
  10138. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10139. \path[->,bend left=15] (x86-3) edge [above] node
  10140. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10141. \path[->,bend left=15] (x86-4) edge [right] node
  10142. {\ttfamily\footnotesize pre.\_and\_concl.} (x86-5);
  10143. \end{tikzpicture}
  10144. \end{tcolorbox}
  10145. \caption{Diagram of the passes for \LangLoop{}.}
  10146. \label{fig:Lwhile-passes}
  10147. \end{figure}
  10148. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10149. for the compilation of \LangLoop{}.
  10150. % Further Reading: dataflow analysis
  10151. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10152. \chapter{Tuples and Garbage Collection}
  10153. \label{ch:Lvec}
  10154. \index{subject}{tuple}
  10155. \index{subject}{vector}
  10156. \index{subject}{allocate}
  10157. \index{subject}{heap allocate}
  10158. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10159. %% all the IR grammars are spelled out! \\ --Jeremy}
  10160. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10161. %% the root stack. \\ --Jeremy}
  10162. In this chapter we study the implementation of tuples\racket{, called
  10163. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10164. where each element may have a different type.
  10165. %
  10166. This language feature is the first to use the computer's
  10167. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10168. indefinite, that is, a tuple lives forever from the programmer's
  10169. viewpoint. Of course, from an implementer's viewpoint, it is important
  10170. to reclaim the space associated with a tuple when it is no longer
  10171. needed, which is why we also study \emph{garbage collection}
  10172. \index{subject}{garbage collection} techniques in this chapter.
  10173. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10174. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10175. language of Chapter~\ref{ch:Lwhile} with tuples.
  10176. %
  10177. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10178. copying live tuples back and forth between two halves of the heap. The
  10179. garbage collector requires coordination with the compiler so that it
  10180. can find all of the live tuples.
  10181. %
  10182. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10183. discuss the necessary changes and additions to the compiler passes,
  10184. including a new compiler pass named \code{expose\_allocation}.
  10185. \section{The \LangVec{} Language}
  10186. \label{sec:r3}
  10187. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10188. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10189. %
  10190. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10191. creating a tuple, \code{vector-ref} for reading an element of a
  10192. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10193. \code{vector-length} for obtaining the number of elements of a
  10194. tuple.}
  10195. %
  10196. \python{The \LangVec{} language adds 1) tuple creation via a
  10197. comma-separated list of expressions, 2) accessing an element of a
  10198. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10199. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10200. operator, and 4) obtaining the number of elements (the length) of a
  10201. tuple. In this chapter, we restrict access indices to constant
  10202. integers.}
  10203. %
  10204. The program below shows an example use of tuples. It creates a tuple
  10205. \code{t} containing the elements \code{40},
  10206. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10207. contains just \code{2}. The element at index $1$ of \code{t} is
  10208. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10209. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10210. to which we add \code{2}, the element at index $0$ of the tuple. So
  10211. the result of the program is \code{42}.
  10212. %
  10213. {\if\edition\racketEd
  10214. \begin{lstlisting}
  10215. (let ([t (vector 40 #t (vector 2))])
  10216. (if (vector-ref t 1)
  10217. (+ (vector-ref t 0)
  10218. (vector-ref (vector-ref t 2) 0))
  10219. 44))
  10220. \end{lstlisting}
  10221. \fi}
  10222. {\if\edition\pythonEd
  10223. \begin{lstlisting}
  10224. t = 40, True, (2,)
  10225. print( t[0] + t[2][0] if t[1] else 44 )
  10226. \end{lstlisting}
  10227. \fi}
  10228. \newcommand{\LtupGrammarRacket}{
  10229. \begin{array}{lcl}
  10230. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10231. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10232. \MID \LP\key{vector-length}\;\Exp\RP \\
  10233. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10234. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10235. \end{array}
  10236. }
  10237. \newcommand{\LtupASTRacket}{
  10238. \begin{array}{lcl}
  10239. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10240. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10241. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10242. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10243. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10244. \end{array}
  10245. }
  10246. \newcommand{\LtupGrammarPython}{
  10247. \begin{array}{rcl}
  10248. \itm{cmp} &::= & \key{is} \\
  10249. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10250. \end{array}
  10251. }
  10252. \newcommand{\LtupASTPython}{
  10253. \begin{array}{lcl}
  10254. \itm{cmp} &::= & \code{Is()} \\
  10255. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10256. &\MID& \LEN{\Exp}
  10257. \end{array}
  10258. }
  10259. \begin{figure}[tbp]
  10260. \centering
  10261. \begin{tcolorbox}[colback=white]
  10262. \small
  10263. {\if\edition\racketEd
  10264. \[
  10265. \begin{array}{l}
  10266. \gray{\LintGrammarRacket{}} \\ \hline
  10267. \gray{\LvarGrammarRacket{}} \\ \hline
  10268. \gray{\LifGrammarRacket{}} \\ \hline
  10269. \gray{\LwhileGrammarRacket} \\ \hline
  10270. \LtupGrammarRacket \\
  10271. \begin{array}{lcl}
  10272. \LangVecM{} &::=& \Exp
  10273. \end{array}
  10274. \end{array}
  10275. \]
  10276. \fi}
  10277. {\if\edition\pythonEd
  10278. \[
  10279. \begin{array}{l}
  10280. \gray{\LintGrammarPython{}} \\ \hline
  10281. \gray{\LvarGrammarPython{}} \\ \hline
  10282. \gray{\LifGrammarPython{}} \\ \hline
  10283. \gray{\LwhileGrammarPython} \\ \hline
  10284. \LtupGrammarPython \\
  10285. \begin{array}{rcl}
  10286. \LangVecM{} &::=& \Stmt^{*}
  10287. \end{array}
  10288. \end{array}
  10289. \]
  10290. \fi}
  10291. \end{tcolorbox}
  10292. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10293. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10294. \label{fig:Lvec-concrete-syntax}
  10295. \end{figure}
  10296. \begin{figure}[tp]
  10297. \centering
  10298. \begin{tcolorbox}[colback=white]
  10299. \small
  10300. {\if\edition\racketEd
  10301. \[
  10302. \begin{array}{l}
  10303. \gray{\LintOpAST} \\ \hline
  10304. \gray{\LvarASTRacket{}} \\ \hline
  10305. \gray{\LifASTRacket{}} \\ \hline
  10306. \gray{\LwhileASTRacket{}} \\ \hline
  10307. \LtupASTRacket{} \\
  10308. \begin{array}{lcl}
  10309. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10310. \end{array}
  10311. \end{array}
  10312. \]
  10313. \fi}
  10314. {\if\edition\pythonEd
  10315. \[
  10316. \begin{array}{l}
  10317. \gray{\LintASTPython} \\ \hline
  10318. \gray{\LvarASTPython} \\ \hline
  10319. \gray{\LifASTPython} \\ \hline
  10320. \gray{\LwhileASTPython} \\ \hline
  10321. \LtupASTPython \\
  10322. \begin{array}{lcl}
  10323. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10324. \end{array}
  10325. \end{array}
  10326. \]
  10327. \fi}
  10328. \end{tcolorbox}
  10329. \caption{The abstract syntax of \LangVec{}.}
  10330. \label{fig:Lvec-syntax}
  10331. \end{figure}
  10332. Tuples raise several interesting new issues. First, variable binding
  10333. performs a shallow-copy when dealing with tuples, which means that
  10334. different variables can refer to the same tuple, that is, two
  10335. variables can be \emph{aliases}\index{subject}{alias} for the same
  10336. entity. Consider the following example in which both \code{t1} and
  10337. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10338. different tuple value but with equal elements. The result of the
  10339. program is \code{42}.
  10340. \begin{center}
  10341. \begin{minipage}{0.96\textwidth}
  10342. {\if\edition\racketEd
  10343. \begin{lstlisting}
  10344. (let ([t1 (vector 3 7)])
  10345. (let ([t2 t1])
  10346. (let ([t3 (vector 3 7)])
  10347. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10348. 42
  10349. 0))))
  10350. \end{lstlisting}
  10351. \fi}
  10352. {\if\edition\pythonEd
  10353. \begin{lstlisting}
  10354. t1 = 3, 7
  10355. t2 = t1
  10356. t3 = 3, 7
  10357. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10358. \end{lstlisting}
  10359. \fi}
  10360. \end{minipage}
  10361. \end{center}
  10362. {\if\edition\racketEd
  10363. Whether two variables are aliased or not affects what happens
  10364. when the underlying tuple is mutated\index{subject}{mutation}.
  10365. Consider the following example in which \code{t1} and \code{t2}
  10366. again refer to the same tuple value.
  10367. \begin{center}
  10368. \begin{minipage}{0.96\textwidth}
  10369. \begin{lstlisting}
  10370. (let ([t1 (vector 3 7)])
  10371. (let ([t2 t1])
  10372. (let ([_ (vector-set! t2 0 42)])
  10373. (vector-ref t1 0))))
  10374. \end{lstlisting}
  10375. \end{minipage}
  10376. \end{center}
  10377. The mutation through \code{t2} is visible when referencing the tuple
  10378. from \code{t1}, so the result of this program is \code{42}.
  10379. \fi}
  10380. The next issue concerns the lifetime of tuples. When does their
  10381. lifetime end? Notice that \LangVec{} does not include an operation
  10382. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10383. to any notion of static scoping.
  10384. %
  10385. {\if\edition\racketEd
  10386. %
  10387. For example, the following program returns \code{42} even though the
  10388. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10389. that reads from the vector it was bound to.
  10390. \begin{center}
  10391. \begin{minipage}{0.96\textwidth}
  10392. \begin{lstlisting}
  10393. (let ([v (vector (vector 44))])
  10394. (let ([x (let ([w (vector 42)])
  10395. (let ([_ (vector-set! v 0 w)])
  10396. 0))])
  10397. (+ x (vector-ref (vector-ref v 0) 0))))
  10398. \end{lstlisting}
  10399. \end{minipage}
  10400. \end{center}
  10401. \fi}
  10402. %
  10403. {\if\edition\pythonEd
  10404. %
  10405. For example, the following program returns \code{42} even though the
  10406. variable \code{x} goes out of scope when the function returns, prior
  10407. to reading the tuple element at index zero. (We study the compilation
  10408. of functions in Chapter~\ref{ch:Lfun}.)
  10409. %
  10410. \begin{center}
  10411. \begin{minipage}{0.96\textwidth}
  10412. \begin{lstlisting}
  10413. def f():
  10414. x = 42, 43
  10415. return x
  10416. t = f()
  10417. print( t[0] )
  10418. \end{lstlisting}
  10419. \end{minipage}
  10420. \end{center}
  10421. \fi}
  10422. %
  10423. From the perspective of programmer-observable behavior, tuples live
  10424. forever. However, if they really lived forever then many long-running
  10425. programs would run out of memory. To solve this problem, the
  10426. language's runtime system performs automatic garbage collection.
  10427. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10428. \LangVec{} language.
  10429. %
  10430. \racket{We define the \code{vector}, \code{vector-ref},
  10431. \code{vector-set!}, and \code{vector-length} operations for
  10432. \LangVec{} in terms of the corresponding operations in Racket. One
  10433. subtle point is that the \code{vector-set!} operation returns the
  10434. \code{\#<void>} value.}
  10435. %
  10436. \python{We represent tuples with Python lists in the interpreter
  10437. because we need to write to them
  10438. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10439. immutable.) We define element access, the \code{is} operator, and
  10440. the \code{len} operator for \LangVec{} in terms of the corresponding
  10441. operations in Python.}
  10442. \begin{figure}[tbp]
  10443. \begin{tcolorbox}[colback=white]
  10444. {\if\edition\racketEd
  10445. \begin{lstlisting}
  10446. (define interp-Lvec-class
  10447. (class interp-Lwhile-class
  10448. (super-new)
  10449. (define/override (interp-op op)
  10450. (match op
  10451. ['eq? (lambda (v1 v2)
  10452. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10453. (and (boolean? v1) (boolean? v2))
  10454. (and (vector? v1) (vector? v2))
  10455. (and (void? v1) (void? v2)))
  10456. (eq? v1 v2)]))]
  10457. ['vector vector]
  10458. ['vector-length vector-length]
  10459. ['vector-ref vector-ref]
  10460. ['vector-set! vector-set!]
  10461. [else (super interp-op op)]
  10462. ))
  10463. (define/override ((interp-exp env) e)
  10464. (match e
  10465. [(HasType e t) ((interp-exp env) e)]
  10466. [else ((super interp-exp env) e)]
  10467. ))
  10468. ))
  10469. (define (interp-Lvec p)
  10470. (send (new interp-Lvec-class) interp-program p))
  10471. \end{lstlisting}
  10472. \fi}
  10473. %
  10474. {\if\edition\pythonEd
  10475. \begin{lstlisting}
  10476. class InterpLtup(InterpLwhile):
  10477. def interp_cmp(self, cmp):
  10478. match cmp:
  10479. case Is():
  10480. return lambda x, y: x is y
  10481. case _:
  10482. return super().interp_cmp(cmp)
  10483. def interp_exp(self, e, env):
  10484. match e:
  10485. case Tuple(es, Load()):
  10486. return tuple([self.interp_exp(e, env) for e in es])
  10487. case Subscript(tup, index, Load()):
  10488. t = self.interp_exp(tup, env)
  10489. n = self.interp_exp(index, env)
  10490. return t[n]
  10491. case _:
  10492. return super().interp_exp(e, env)
  10493. \end{lstlisting}
  10494. \fi}
  10495. \end{tcolorbox}
  10496. \caption{Interpreter for the \LangVec{} language.}
  10497. \label{fig:interp-Lvec}
  10498. \end{figure}
  10499. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10500. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10501. we need to know which elements of the tuple are themselves tuples for
  10502. the purposes of garbage collection. We can obtain this information
  10503. during type checking. The type checker in
  10504. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10505. expression, it also
  10506. %
  10507. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10508. where $T$ is the tuple's type.
  10509. To create the s-expression for the \code{Vector} type in
  10510. Figure~\ref{fig:type-check-Lvec}, we use the
  10511. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10512. operator} \code{,@} to insert the list \code{t*} without its usual
  10513. start and end parentheses. \index{subject}{unquote-slicing}}
  10514. %
  10515. \python{records the type of each tuple expression in a new field
  10516. named \code{has\_type}. Because the type checker has to compute the type
  10517. of each tuple access, the index must be a constant.}
  10518. \begin{figure}[tp]
  10519. \begin{tcolorbox}[colback=white]
  10520. {\if\edition\racketEd
  10521. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10522. (define type-check-Lvec-class
  10523. (class type-check-Lif-class
  10524. (super-new)
  10525. (inherit check-type-equal?)
  10526. (define/override (type-check-exp env)
  10527. (lambda (e)
  10528. (define recur (type-check-exp env))
  10529. (match e
  10530. [(Prim 'vector es)
  10531. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10532. (define t `(Vector ,@t*))
  10533. (values (HasType (Prim 'vector e*) t) t)]
  10534. [(Prim 'vector-ref (list e1 (Int i)))
  10535. (define-values (e1^ t) (recur e1))
  10536. (match t
  10537. [`(Vector ,ts ...)
  10538. (unless (and (0 . <= . i) (i . < . (length ts)))
  10539. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10540. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10541. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10542. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10543. (define-values (e-vec t-vec) (recur e1))
  10544. (define-values (e-arg^ t-arg) (recur arg))
  10545. (match t-vec
  10546. [`(Vector ,ts ...)
  10547. (unless (and (0 . <= . i) (i . < . (length ts)))
  10548. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10549. (check-type-equal? (list-ref ts i) t-arg e)
  10550. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10551. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10552. [(Prim 'vector-length (list e))
  10553. (define-values (e^ t) (recur e))
  10554. (match t
  10555. [`(Vector ,ts ...)
  10556. (values (Prim 'vector-length (list e^)) 'Integer)]
  10557. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10558. [(Prim 'eq? (list arg1 arg2))
  10559. (define-values (e1 t1) (recur arg1))
  10560. (define-values (e2 t2) (recur arg2))
  10561. (match* (t1 t2)
  10562. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10563. [(other wise) (check-type-equal? t1 t2 e)])
  10564. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10565. [(HasType (Prim 'vector es) t)
  10566. ((type-check-exp env) (Prim 'vector es))]
  10567. [(HasType e1 t)
  10568. (define-values (e1^ t^) (recur e1))
  10569. (check-type-equal? t t^ e)
  10570. (values (HasType e1^ t) t)]
  10571. [else ((super type-check-exp env) e)]
  10572. )))
  10573. ))
  10574. (define (type-check-Lvec p)
  10575. (send (new type-check-Lvec-class) type-check-program p))
  10576. \end{lstlisting}
  10577. \fi}
  10578. {\if\edition\pythonEd
  10579. \begin{lstlisting}
  10580. class TypeCheckLtup(TypeCheckLwhile):
  10581. def type_check_exp(self, e, env):
  10582. match e:
  10583. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10584. l = self.type_check_exp(left, env)
  10585. r = self.type_check_exp(right, env)
  10586. check_type_equal(l, r, e)
  10587. return bool
  10588. case Tuple(es, Load()):
  10589. ts = [self.type_check_exp(e, env) for e in es]
  10590. e.has_type = tuple(ts)
  10591. return e.has_type
  10592. case Subscript(tup, Constant(index), Load()):
  10593. tup_ty = self.type_check_exp(tup, env)
  10594. index_ty = self.type_check_exp(Constant(index), env)
  10595. check_type_equal(index_ty, int, index)
  10596. match tup_ty:
  10597. case tuple(ts):
  10598. return ts[index]
  10599. case _:
  10600. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10601. case _:
  10602. return super().type_check_exp(e, env)
  10603. \end{lstlisting}
  10604. \fi}
  10605. \end{tcolorbox}
  10606. \caption{Type checker for the \LangVec{} language.}
  10607. \label{fig:type-check-Lvec}
  10608. \end{figure}
  10609. \section{Garbage Collection}
  10610. \label{sec:GC}
  10611. Garbage collection is a runtime technique for reclaiming space on the
  10612. heap that will not be used in the future of the running program. We
  10613. use the term \emph{object}\index{subject}{object} to refer to any
  10614. value that is stored in the heap, which for now only includes
  10615. tuples.%
  10616. %
  10617. \footnote{The term ``object'' as it is used in the context of
  10618. object-oriented programming has a more specific meaning than how we
  10619. are using the term here.}
  10620. %
  10621. Unfortunately, it is impossible to know precisely which objects will
  10622. be accessed in the future and which will not. Instead, garbage
  10623. collectors over approximate the set of objects that will be accessed by
  10624. identifying which objects can possibly be accessed. The running
  10625. program can directly access objects that are in registers and on the
  10626. procedure call stack. It can also transitively access the elements of
  10627. tuples, starting with a tuple whose address is in a register or on the
  10628. procedure call stack. We define the \emph{root
  10629. set}\index{subject}{root set} to be all the tuple addresses that are
  10630. in registers or on the procedure call stack. We define the \emph{live
  10631. objects}\index{subject}{live objects} to be the objects that are
  10632. reachable from the root set. Garbage collectors reclaim the space that
  10633. is allocated to objects that are no longer live. That means that some
  10634. objects may not get reclaimed as soon as they could be, but at least
  10635. garbage collectors do not reclaim the space dedicated to objects that
  10636. will be accessed in the future! The programmer can influence which
  10637. objects get reclaimed by causing them to become unreachable.
  10638. So the goal of the garbage collector is twofold:
  10639. \begin{enumerate}
  10640. \item preserve all the live objects, and
  10641. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10642. \end{enumerate}
  10643. \subsection{Two-Space Copying Collector}
  10644. Here we study a relatively simple algorithm for garbage collection
  10645. that is the basis of many state-of-the-art garbage
  10646. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10647. particular, we describe a two-space copying
  10648. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10649. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10650. collector} \index{subject}{two-space copying collector}
  10651. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10652. what happens in a two-space collector, showing two time steps, prior
  10653. to garbage collection (on the top) and after garbage collection (on
  10654. the bottom). In a two-space collector, the heap is divided into two
  10655. parts named the FromSpace\index{subject}{FromSpace} and the
  10656. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10657. FromSpace until there is not enough room for the next allocation
  10658. request. At that point, the garbage collector goes to work to make
  10659. room for the next allocation.
  10660. A copying collector makes more room by copying all of the live objects
  10661. from the FromSpace into the ToSpace and then performs a sleight of
  10662. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10663. as the new ToSpace. In the example of
  10664. Figure~\ref{fig:copying-collector}, the root set consists of three
  10665. pointers, one in a register and two on the stack. All of the live
  10666. objects have been copied to the ToSpace (the right-hand side of
  10667. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10668. pointer relationships. For example, the pointer in the register still
  10669. points to a tuple that in turn points to two other tuples. There are
  10670. four tuples that are not reachable from the root set and therefore do
  10671. not get copied into the ToSpace.
  10672. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10673. created by a well-typed program in \LangVec{} because it contains a
  10674. cycle. However, creating cycles will be possible once we get to
  10675. \LangDyn{} (Chapter~\ref{ch:Ldyn}). We design the garbage collector
  10676. to deal with cycles to begin with so we will not need to revisit this
  10677. issue.
  10678. \begin{figure}[tbp]
  10679. \centering
  10680. \begin{tcolorbox}[colback=white]
  10681. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10682. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10683. \\[5ex]
  10684. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10685. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10686. \end{tcolorbox}
  10687. \caption{A copying collector in action.}
  10688. \label{fig:copying-collector}
  10689. \end{figure}
  10690. \subsection{Graph Copying via Cheney's Algorithm}
  10691. \label{sec:cheney}
  10692. \index{subject}{Cheney's algorithm}
  10693. Let us take a closer look at the copying of the live objects. The
  10694. allocated objects and pointers can be viewed as a graph and we need to
  10695. copy the part of the graph that is reachable from the root set. To
  10696. make sure we copy all of the reachable vertices in the graph, we need
  10697. an exhaustive graph traversal algorithm, such as depth-first search or
  10698. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10699. such algorithms take into account the possibility of cycles by marking
  10700. which vertices have already been visited, so as to ensure termination
  10701. of the algorithm. These search algorithms also use a data structure
  10702. such as a stack or queue as a to-do list to keep track of the vertices
  10703. that need to be visited. We use breadth-first search and a trick
  10704. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10705. and copying tuples into the ToSpace.
  10706. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10707. copy progresses. The queue is represented by a chunk of contiguous
  10708. memory at the beginning of the ToSpace, using two pointers to track
  10709. the front and the back of the queue, called the \emph{free pointer}
  10710. and the \emph{scan pointer} respectively. The algorithm starts by
  10711. copying all tuples that are immediately reachable from the root set
  10712. into the ToSpace to form the initial queue. When we copy a tuple, we
  10713. mark the old tuple to indicate that it has been visited. We discuss
  10714. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10715. that any pointers inside the copied tuples in the queue still point
  10716. back to the FromSpace. Once the initial queue has been created, the
  10717. algorithm enters a loop in which it repeatedly processes the tuple at
  10718. the front of the queue and pops it off the queue. To process a tuple,
  10719. the algorithm copies all the objects that are directly reachable from it
  10720. to the ToSpace, placing them at the back of the queue. The algorithm
  10721. then updates the pointers in the popped tuple so they point to the
  10722. newly copied objects.
  10723. \begin{figure}[tbp]
  10724. \centering
  10725. \begin{tcolorbox}[colback=white]
  10726. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10727. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10728. \end{tcolorbox}
  10729. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10730. \label{fig:cheney}
  10731. \end{figure}
  10732. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10733. tuple whose second element is $42$ to the back of the queue. The other
  10734. pointer goes to a tuple that has already been copied, so we do not
  10735. need to copy it again, but we do need to update the pointer to the new
  10736. location. This can be accomplished by storing a \emph{forwarding
  10737. pointer}\index{subject}{forwarding pointer} to the new location in the
  10738. old tuple, back when we initially copied the tuple into the
  10739. ToSpace. This completes one step of the algorithm. The algorithm
  10740. continues in this way until the queue is empty, that is, when the scan
  10741. pointer catches up with the free pointer.
  10742. \subsection{Data Representation}
  10743. \label{sec:data-rep-gc}
  10744. The garbage collector places some requirements on the data
  10745. representations used by our compiler. First, the garbage collector
  10746. needs to distinguish between pointers and other kinds of data such as
  10747. integers. There are several ways to accomplish this.
  10748. \begin{enumerate}
  10749. \item Attached a tag to each object that identifies what type of
  10750. object it is~\citep{McCarthy:1960dz}.
  10751. \item Store different types of objects in different
  10752. regions~\citep{Steele:1977ab}.
  10753. \item Use type information from the program to either (a) generate
  10754. type-specific code for collecting or (b) generate tables that
  10755. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10756. \end{enumerate}
  10757. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10758. need to tag objects anyways, so option 1 is a natural choice for those
  10759. languages. However, \LangVec{} is a statically typed language, so it
  10760. would be unfortunate to require tags on every object, especially small
  10761. and pervasive objects like integers and Booleans. Option 3 is the
  10762. best-performing choice for statically typed languages, but comes with
  10763. a relatively high implementation complexity. To keep this chapter
  10764. within a reasonable time budget, we recommend a combination of options
  10765. 1 and 2, using separate strategies for the stack and the heap.
  10766. Regarding the stack, we recommend using a separate stack for pointers,
  10767. which we call the \emph{root stack}\index{subject}{root stack}
  10768. (a.k.a. ``shadow
  10769. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10770. is, when a local variable needs to be spilled and is of type
  10771. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10772. root stack instead of putting it on the procedure call
  10773. stack. Furthermore, we always spill tuple-typed variables if they are
  10774. live during a call to the collector, thereby ensuring that no pointers
  10775. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10776. reproduces the example from Figure~\ref{fig:copying-collector} and
  10777. contrasts it with the data layout using a root stack. The root stack
  10778. contains the two pointers from the regular stack and also the pointer
  10779. in the second register.
  10780. \begin{figure}[tbp]
  10781. \centering
  10782. \begin{tcolorbox}[colback=white]
  10783. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10784. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10785. \end{tcolorbox}
  10786. \caption{Maintaining a root stack to facilitate garbage collection.}
  10787. \label{fig:shadow-stack}
  10788. \end{figure}
  10789. The problem of distinguishing between pointers and other kinds of data
  10790. also arises inside of each tuple on the heap. We solve this problem by
  10791. attaching a tag, an extra 64-bits, to each
  10792. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10793. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10794. that we have drawn the bits in a big-endian way, from right-to-left,
  10795. with bit location 0 (the least significant bit) on the far right,
  10796. which corresponds to the direction of the x86 shifting instructions
  10797. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10798. is dedicated to specifying which elements of the tuple are pointers,
  10799. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10800. indicates there is a pointer and a 0 bit indicates some other kind of
  10801. data. The pointer mask starts at bit location 7. We limit tuples to a
  10802. maximum size of 50 elements, so we just need 50 bits for the pointer
  10803. mask.%
  10804. %
  10805. \footnote{A production-quality compiler would handle
  10806. arbitrary-sized tuples and use a more complex approach.}
  10807. %
  10808. The tag also contains two other pieces of information. The length of
  10809. the tuple (number of elements) is stored in bits location 1 through
  10810. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10811. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10812. has not yet been copied. If the bit has value 0 then the entire tag
  10813. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10814. zero anyways because our tuples are 8-byte aligned.)
  10815. \begin{figure}[tbp]
  10816. \centering
  10817. \begin{tcolorbox}[colback=white]
  10818. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10819. \end{tcolorbox}
  10820. \caption{Representation of tuples in the heap.}
  10821. \label{fig:tuple-rep}
  10822. \end{figure}
  10823. \subsection{Implementation of the Garbage Collector}
  10824. \label{sec:organize-gz}
  10825. \index{subject}{prelude}
  10826. An implementation of the copying collector is provided in the
  10827. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10828. interface to the garbage collector that is used by the compiler. The
  10829. \code{initialize} function creates the FromSpace, ToSpace, and root
  10830. stack and should be called in the prelude of the \code{main}
  10831. function. The arguments of \code{initialize} are the root stack size
  10832. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10833. good choice for both. The \code{initialize} function puts the address
  10834. of the beginning of the FromSpace into the global variable
  10835. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10836. the address that is 1-past the last element of the FromSpace. We use
  10837. half-open intervals to represent chunks of
  10838. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10839. points to the first element of the root stack.
  10840. As long as there is room left in the FromSpace, your generated code
  10841. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10842. %
  10843. The amount of room left in the FromSpace is the difference between the
  10844. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10845. function should be called when there is not enough room left in the
  10846. FromSpace for the next allocation. The \code{collect} function takes
  10847. a pointer to the current top of the root stack (one past the last item
  10848. that was pushed) and the number of bytes that need to be
  10849. allocated. The \code{collect} function performs the copying collection
  10850. and leaves the heap in a state such that there is enough room for the
  10851. next allocation.
  10852. \begin{figure}[tbp]
  10853. \begin{tcolorbox}[colback=white]
  10854. \begin{lstlisting}
  10855. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10856. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10857. int64_t* free_ptr;
  10858. int64_t* fromspace_begin;
  10859. int64_t* fromspace_end;
  10860. int64_t** rootstack_begin;
  10861. \end{lstlisting}
  10862. \end{tcolorbox}
  10863. \caption{The compiler's interface to the garbage collector.}
  10864. \label{fig:gc-header}
  10865. \end{figure}
  10866. %% \begin{exercise}
  10867. %% In the file \code{runtime.c} you will find the implementation of
  10868. %% \code{initialize} and a partial implementation of \code{collect}.
  10869. %% The \code{collect} function calls another function, \code{cheney},
  10870. %% to perform the actual copy, and that function is left to the reader
  10871. %% to implement. The following is the prototype for \code{cheney}.
  10872. %% \begin{lstlisting}
  10873. %% static void cheney(int64_t** rootstack_ptr);
  10874. %% \end{lstlisting}
  10875. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10876. %% rootstack (which is an array of pointers). The \code{cheney} function
  10877. %% also communicates with \code{collect} through the global
  10878. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10879. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10880. %% the ToSpace:
  10881. %% \begin{lstlisting}
  10882. %% static int64_t* tospace_begin;
  10883. %% static int64_t* tospace_end;
  10884. %% \end{lstlisting}
  10885. %% The job of the \code{cheney} function is to copy all the live
  10886. %% objects (reachable from the root stack) into the ToSpace, update
  10887. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10888. %% update the root stack so that it points to the objects in the
  10889. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10890. %% and ToSpace.
  10891. %% \end{exercise}
  10892. The introduction of garbage collection has a non-trivial impact on our
  10893. compiler passes. We introduce a new compiler pass named
  10894. \code{expose\_allocation} that elaborates the code for allocating
  10895. tuples. We also make significant changes to
  10896. \code{select\_instructions}, \code{build\_interference},
  10897. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10898. make minor changes in several more passes.
  10899. The following program will serve as our running example. It creates
  10900. two tuples, one nested inside the other. Both tuples have length
  10901. one. The program accesses the element in the inner tuple.
  10902. % tests/vectors_test_17.rkt
  10903. {\if\edition\racketEd
  10904. \begin{lstlisting}
  10905. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10906. \end{lstlisting}
  10907. \fi}
  10908. {\if\edition\pythonEd
  10909. \begin{lstlisting}
  10910. print( ((42,),)[0][0] )
  10911. \end{lstlisting}
  10912. \fi}
  10913. {\if\edition\racketEd
  10914. \section{Shrink}
  10915. \label{sec:shrink-Lvec}
  10916. Recall that the \code{shrink} pass translates the primitives operators
  10917. into a smaller set of primitives.
  10918. %
  10919. This pass comes after type checking and the type checker adds a
  10920. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10921. need to add a case for \code{HasType} to the \code{shrink} pass.
  10922. \fi}
  10923. \section{Expose Allocation}
  10924. \label{sec:expose-allocation}
  10925. The pass \code{expose\_allocation} lowers tuple creation into a
  10926. conditional call to the collector followed by allocating the
  10927. appropriate amount of memory and initializing it. We choose to place
  10928. the \code{expose\_allocation} pass before
  10929. \code{remove\_complex\_operands} because it generates
  10930. code that contains complex operands.
  10931. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10932. replaces tuple creation with new lower-level forms that we use in the
  10933. translation of tuple creation.
  10934. %
  10935. {\if\edition\racketEd
  10936. \[
  10937. \begin{array}{lcl}
  10938. \Exp &::=& \cdots
  10939. \MID (\key{collect} \,\itm{int})
  10940. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10941. \MID (\key{global-value} \,\itm{name})
  10942. \end{array}
  10943. \]
  10944. \fi}
  10945. {\if\edition\pythonEd
  10946. \[
  10947. \begin{array}{lcl}
  10948. \Exp &::=& \cdots\\
  10949. &\MID& \key{collect}(\itm{int})
  10950. \MID \key{allocate}(\itm{int},\itm{type})
  10951. \MID \key{global\_value}(\itm{name}) \\
  10952. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10953. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10954. \end{array}
  10955. \]
  10956. \fi}
  10957. %
  10958. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10959. make sure that there are $n$ bytes ready to be allocated. During
  10960. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10961. the \code{collect} function in \code{runtime.c}.
  10962. %
  10963. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10964. space at the front for the 64 bit tag), but the elements are not
  10965. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10966. of the tuple:
  10967. %
  10968. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10969. %
  10970. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10971. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10972. as \code{free\_ptr}.
  10973. %
  10974. \python{The \code{begin} form is an expression that executes a
  10975. sequence of statements and then produces the value of the expression
  10976. at the end.}
  10977. The following shows the transformation of tuple creation into 1) a
  10978. sequence of temporary variable bindings for the initializing
  10979. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10980. \code{allocate}, and 4) the initialization of the tuple. The
  10981. \itm{len} placeholder refers to the length of the tuple and
  10982. \itm{bytes} is how many total bytes need to be allocated for the
  10983. tuple, which is 8 for the tag plus \itm{len} times 8.
  10984. %
  10985. \python{The \itm{type} needed for the second argument of the
  10986. \code{allocate} form can be obtained from the \code{has\_type} field
  10987. of the tuple AST node, which is stored there by running the type
  10988. checker for \LangVec{} immediately before this pass.}
  10989. %
  10990. \begin{center}
  10991. \begin{minipage}{\textwidth}
  10992. {\if\edition\racketEd
  10993. \begin{lstlisting}
  10994. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10995. |$\Longrightarrow$|
  10996. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10997. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10998. (global-value fromspace_end))
  10999. (void)
  11000. (collect |\itm{bytes}|))])
  11001. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11002. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11003. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11004. |$v$|) ... )))) ...)
  11005. \end{lstlisting}
  11006. \fi}
  11007. {\if\edition\pythonEd
  11008. \begin{lstlisting}
  11009. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11010. |$\Longrightarrow$|
  11011. begin:
  11012. |$x_0$| = |$e_0$|
  11013. |$\vdots$|
  11014. |$x_{n-1}$| = |$e_{n-1}$|
  11015. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11016. 0
  11017. else:
  11018. collect(|\itm{bytes}|)
  11019. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11020. |$v$|[0] = |$x_0$|
  11021. |$\vdots$|
  11022. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11023. |$v$|
  11024. \end{lstlisting}
  11025. \fi}
  11026. \end{minipage}
  11027. \end{center}
  11028. %
  11029. \noindent The sequencing of the initializing expressions
  11030. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  11031. they may trigger garbage collection and we cannot have an allocated
  11032. but uninitialized tuple on the heap during a collection.
  11033. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11034. \code{expose\_allocation} pass on our running example.
  11035. \begin{figure}[tbp]
  11036. \begin{tcolorbox}[colback=white]
  11037. % tests/s2_17.rkt
  11038. {\if\edition\racketEd
  11039. \begin{lstlisting}
  11040. (vector-ref
  11041. (vector-ref
  11042. (let ([vecinit6
  11043. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11044. (global-value fromspace_end))
  11045. (void)
  11046. (collect 16))])
  11047. (let ([alloc2 (allocate 1 (Vector Integer))])
  11048. (let ([_3 (vector-set! alloc2 0 42)])
  11049. alloc2)))])
  11050. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11051. (global-value fromspace_end))
  11052. (void)
  11053. (collect 16))])
  11054. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11055. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11056. alloc5))))
  11057. 0)
  11058. 0)
  11059. \end{lstlisting}
  11060. \fi}
  11061. {\if\edition\pythonEd
  11062. \begin{lstlisting}
  11063. print( |$T_1$|[0][0] )
  11064. \end{lstlisting}
  11065. where $T_1$ is
  11066. \begin{lstlisting}
  11067. begin:
  11068. tmp.1 = |$T_2$|
  11069. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11070. 0
  11071. else:
  11072. collect(16)
  11073. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11074. tmp.2[0] = tmp.1
  11075. tmp.2
  11076. \end{lstlisting}
  11077. and $T_2$ is
  11078. \begin{lstlisting}
  11079. begin:
  11080. tmp.3 = 42
  11081. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11082. 0
  11083. else:
  11084. collect(16)
  11085. tmp.4 = allocate(1, TupleType([int]))
  11086. tmp.4[0] = tmp.3
  11087. tmp.4
  11088. \end{lstlisting}
  11089. \fi}
  11090. \end{tcolorbox}
  11091. \caption{Output of the \code{expose\_allocation} pass.}
  11092. \label{fig:expose-alloc-output}
  11093. \end{figure}
  11094. \section{Remove Complex Operands}
  11095. \label{sec:remove-complex-opera-Lvec}
  11096. {\if\edition\racketEd
  11097. %
  11098. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11099. should be treated as complex operands.
  11100. %
  11101. \fi}
  11102. %
  11103. {\if\edition\pythonEd
  11104. %
  11105. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11106. and tuple access should be treated as complex operands. The
  11107. sub-expressions of tuple access must be atomic.
  11108. %
  11109. \fi}
  11110. %% A new case for
  11111. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11112. %% handled carefully to prevent the \code{Prim} node from being separated
  11113. %% from its enclosing \code{HasType}.
  11114. Figure~\ref{fig:Lvec-anf-syntax}
  11115. shows the grammar for the output language \LangAllocANF{} of this
  11116. pass, which is \LangAlloc{} in monadic normal form.
  11117. \newcommand{\LtupMonadASTRacket}{
  11118. \begin{array}{rcl}
  11119. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11120. \MID \GLOBALVALUE{\Var}
  11121. \end{array}
  11122. }
  11123. \newcommand{\LtupMonadASTPython}{
  11124. \begin{array}{rcl}
  11125. \Exp &::=& \GET{\Atm}{\Atm} \\
  11126. &\MID& \LEN{\Atm}\\
  11127. &\MID& \ALLOCATE{\Int}{\Type}
  11128. \MID \GLOBALVALUE{\Var} \\
  11129. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11130. &\MID& \COLLECT{\Int}
  11131. \end{array}
  11132. }
  11133. \begin{figure}[tp]
  11134. \centering
  11135. \begin{tcolorbox}[colback=white]
  11136. \small
  11137. {\if\edition\racketEd
  11138. \[
  11139. \begin{array}{l}
  11140. \gray{\LvarMonadASTRacket} \\ \hline
  11141. \gray{\LifMonadASTRacket} \\ \hline
  11142. \gray{\LwhileMonadASTRacket} \\ \hline
  11143. \LtupMonadASTRacket \\
  11144. \begin{array}{rcl}
  11145. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11146. \end{array}
  11147. \end{array}
  11148. \]
  11149. \fi}
  11150. {\if\edition\pythonEd
  11151. \[
  11152. \begin{array}{l}
  11153. \gray{\LvarMonadASTPython} \\ \hline
  11154. \gray{\LifMonadASTPython} \\ \hline
  11155. \gray{\LwhileMonadASTPython} \\ \hline
  11156. \LtupMonadASTPython \\
  11157. \begin{array}{rcl}
  11158. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11159. \end{array}
  11160. \end{array}
  11161. \]
  11162. \fi}
  11163. \end{tcolorbox}
  11164. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11165. \label{fig:Lvec-anf-syntax}
  11166. \end{figure}
  11167. \section{Explicate Control and the \LangCVec{} language}
  11168. \label{sec:explicate-control-r3}
  11169. \newcommand{\CtupASTRacket}{
  11170. \begin{array}{lcl}
  11171. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11172. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11173. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11174. &\MID& \VECLEN{\Atm} \\
  11175. &\MID& \GLOBALVALUE{\Var} \\
  11176. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11177. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11178. \end{array}
  11179. }
  11180. \newcommand{\CtupASTPython}{
  11181. \begin{array}{lcl}
  11182. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11183. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11184. \Stmt &::=& \COLLECT{\Int} \\
  11185. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11186. \end{array}
  11187. }
  11188. \begin{figure}[tp]
  11189. \begin{tcolorbox}[colback=white]
  11190. \small
  11191. {\if\edition\racketEd
  11192. \[
  11193. \begin{array}{l}
  11194. \gray{\CvarASTRacket} \\ \hline
  11195. \gray{\CifASTRacket} \\ \hline
  11196. \gray{\CloopASTRacket} \\ \hline
  11197. \CtupASTRacket \\
  11198. \begin{array}{lcl}
  11199. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11200. \end{array}
  11201. \end{array}
  11202. \]
  11203. \fi}
  11204. {\if\edition\pythonEd
  11205. \[
  11206. \begin{array}{l}
  11207. \gray{\CifASTPython} \\ \hline
  11208. \CtupASTPython \\
  11209. \begin{array}{lcl}
  11210. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11211. \end{array}
  11212. \end{array}
  11213. \]
  11214. \fi}
  11215. \end{tcolorbox}
  11216. \caption{The abstract syntax of \LangCVec{}, extending
  11217. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11218. (Figure~\ref{fig:c1-syntax})}.}
  11219. \label{fig:c2-syntax}
  11220. \end{figure}
  11221. The output of \code{explicate\_control} is a program in the
  11222. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11223. Figure~\ref{fig:c2-syntax}.
  11224. %
  11225. %% \racket{(The concrete syntax is defined in
  11226. %% Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11227. %
  11228. The new expressions of \LangCVec{} include \key{allocate},
  11229. %
  11230. \racket{\key{vector-ref}, and \key{vector-set!},}
  11231. %
  11232. \python{accessing tuple elements,}
  11233. %
  11234. and \key{global\_value}.
  11235. %
  11236. \python{\LangCVec{} also includes the \code{collect} statement and
  11237. assignment to a tuple element.}
  11238. %
  11239. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11240. %
  11241. The \code{explicate\_control} pass can treat these new forms much like
  11242. the other forms that we've already encountered. The output of the
  11243. \code{explicate\_control} pass on the running example is shown on the
  11244. left-side of Figure~\ref{fig:select-instr-output-gc} in the next
  11245. section.
  11246. \section{Select Instructions and the \LangXGlobal{} Language}
  11247. \label{sec:select-instructions-gc}
  11248. \index{subject}{instruction selection}
  11249. %% void (rep as zero)
  11250. %% allocate
  11251. %% collect (callq collect)
  11252. %% vector-ref
  11253. %% vector-set!
  11254. %% vector-length
  11255. %% global (postpone)
  11256. In this pass we generate x86 code for most of the new operations that
  11257. were needed to compile tuples, including \code{Allocate},
  11258. \code{Collect}, and accessing tuple elements.
  11259. %
  11260. We compile \code{GlobalValue} to \code{Global} because the later has a
  11261. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11262. \ref{fig:x86-2}). \index{subject}{x86}
  11263. The tuple read and write forms translate into \code{movq}
  11264. instructions. (The $+1$ in the offset is to move past the tag at the
  11265. beginning of the tuple representation.)
  11266. %
  11267. \begin{center}
  11268. \begin{minipage}{\textwidth}
  11269. {\if\edition\racketEd
  11270. \begin{lstlisting}
  11271. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11272. |$\Longrightarrow$|
  11273. movq |$\itm{tup}'$|, %r11
  11274. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11275. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11276. |$\Longrightarrow$|
  11277. movq |$\itm{tup}'$|, %r11
  11278. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11279. movq $0, |$\itm{lhs'}$|
  11280. \end{lstlisting}
  11281. \fi}
  11282. {\if\edition\pythonEd
  11283. \begin{lstlisting}
  11284. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11285. |$\Longrightarrow$|
  11286. movq |$\itm{tup}'$|, %r11
  11287. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11288. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11289. |$\Longrightarrow$|
  11290. movq |$\itm{tup}'$|, %r11
  11291. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11292. \end{lstlisting}
  11293. \fi}
  11294. \end{minipage}
  11295. \end{center}
  11296. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11297. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11298. are obtained by translating from \LangCVec{} to x86.
  11299. %
  11300. The move of $\itm{tup}'$ to
  11301. register \code{r11} ensures that offset expression
  11302. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11303. removing \code{r11} from consideration by the register allocating.
  11304. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11305. \code{rax}. Then the generated code for tuple assignment would be
  11306. \begin{lstlisting}
  11307. movq |$\itm{tup}'$|, %rax
  11308. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11309. \end{lstlisting}
  11310. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11311. \code{patch\_instructions} would insert a move through \code{rax}
  11312. as follows.
  11313. \begin{lstlisting}
  11314. movq |$\itm{tup}'$|, %rax
  11315. movq |$\itm{rhs}'$|, %rax
  11316. movq %rax, |$8(n+1)$|(%rax)
  11317. \end{lstlisting}
  11318. But the above sequence of instructions does not work because we're
  11319. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11320. $\itm{rhs}'$) at the same time!
  11321. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11322. be translated into a sequence of instructions that read the tag of the
  11323. tuple and extract the six bits that represent the tuple length, which
  11324. are the bits starting at index 1 and going up to and including bit 6.
  11325. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11326. (shift right) can be used to accomplish this.
  11327. We compile the \code{allocate} form to operations on the
  11328. \code{free\_ptr}, as shown below. This approach is called
  11329. \emph{inline allocation} as it implements allocation without a
  11330. function call, by simply bumping the allocation pointer. It is much
  11331. more efficient than calling a function for each allocation. The
  11332. address in the \code{free\_ptr} is the next free address in the
  11333. FromSpace, so we copy it into \code{r11} and then move it forward by
  11334. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11335. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11336. the tag. We then initialize the \itm{tag} and finally copy the
  11337. address in \code{r11} to the left-hand-side. Refer to
  11338. Figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11339. %
  11340. \racket{We recommend using the Racket operations
  11341. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11342. during compilation.}
  11343. %
  11344. \python{We recommend using the bitwise-or operator \code{|} and the
  11345. shift-left operator \code{<<} to compute the tag during
  11346. compilation.}
  11347. %
  11348. The type annotation in the \code{allocate} form is used to determine
  11349. the pointer mask region of the tag.
  11350. %
  11351. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11352. address of the \code{free\_ptr} global variable but uses a special
  11353. instruction-pointer relative addressing mode of the x86-64 processor.
  11354. In particular, the assembler computes the distance $d$ between the
  11355. address of \code{free\_ptr} and where the \code{rip} would be at that
  11356. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11357. \code{$d$(\%rip)}, which at runtime will compute the address of
  11358. \code{free\_ptr}.
  11359. %
  11360. {\if\edition\racketEd
  11361. \begin{lstlisting}
  11362. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11363. |$\Longrightarrow$|
  11364. movq free_ptr(%rip), %r11
  11365. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11366. movq $|$\itm{tag}$|, 0(%r11)
  11367. movq %r11, |$\itm{lhs}'$|
  11368. \end{lstlisting}
  11369. \fi}
  11370. {\if\edition\pythonEd
  11371. \begin{lstlisting}
  11372. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11373. |$\Longrightarrow$|
  11374. movq free_ptr(%rip), %r11
  11375. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11376. movq $|$\itm{tag}$|, 0(%r11)
  11377. movq %r11, |$\itm{lhs}'$|
  11378. \end{lstlisting}
  11379. \fi}
  11380. The \code{collect} form is compiled to a call to the \code{collect}
  11381. function in the runtime. The arguments to \code{collect} are 1) the
  11382. top of the root stack and 2) the number of bytes that need to be
  11383. allocated. We use another dedicated register, \code{r15}, to
  11384. store the pointer to the top of the root stack. So \code{r15} is not
  11385. available for use by the register allocator.
  11386. {\if\edition\racketEd
  11387. \begin{lstlisting}
  11388. (collect |$\itm{bytes}$|)
  11389. |$\Longrightarrow$|
  11390. movq %r15, %rdi
  11391. movq $|\itm{bytes}|, %rsi
  11392. callq collect
  11393. \end{lstlisting}
  11394. \fi}
  11395. {\if\edition\pythonEd
  11396. \begin{lstlisting}
  11397. collect(|$\itm{bytes}$|)
  11398. |$\Longrightarrow$|
  11399. movq %r15, %rdi
  11400. movq $|\itm{bytes}|, %rsi
  11401. callq collect
  11402. \end{lstlisting}
  11403. \fi}
  11404. \newcommand{\GrammarXGlobal}{
  11405. \begin{array}{lcl}
  11406. \Arg &::=& \itm{label} \key{(\%rip)}
  11407. \end{array}
  11408. }
  11409. \newcommand{\ASTXGlobalRacket}{
  11410. \begin{array}{lcl}
  11411. \Arg &::=& \GLOBAL{\itm{label}}
  11412. \end{array}
  11413. }
  11414. \begin{figure}[tp]
  11415. \begin{tcolorbox}[colback=white]
  11416. \[
  11417. \begin{array}{l}
  11418. \gray{\GrammarXInt} \\ \hline
  11419. \gray{\GrammarXIf} \\ \hline
  11420. \GrammarXGlobal \\
  11421. \begin{array}{lcl}
  11422. \LangXGlobalM{} &::= & \key{.globl main} \\
  11423. & & \key{main:} \; \Instr^{*}
  11424. \end{array}
  11425. \end{array}
  11426. \]
  11427. \end{tcolorbox}
  11428. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11429. \label{fig:x86-2-concrete}
  11430. \end{figure}
  11431. \begin{figure}[tp]
  11432. \begin{tcolorbox}[colback=white]
  11433. \small
  11434. \[
  11435. \begin{array}{l}
  11436. \gray{\ASTXIntRacket} \\ \hline
  11437. \gray{\ASTXIfRacket} \\ \hline
  11438. \ASTXGlobalRacket \\
  11439. \begin{array}{lcl}
  11440. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11441. \end{array}
  11442. \end{array}
  11443. \]
  11444. \end{tcolorbox}
  11445. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11446. \label{fig:x86-2}
  11447. \end{figure}
  11448. The concrete and abstract syntax of the \LangXGlobal{} language is
  11449. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11450. differs from \LangXIf{} just in the addition of global variables.
  11451. %
  11452. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11453. \code{select\_instructions} pass on the running example.
  11454. \begin{figure}[tbp]
  11455. \centering
  11456. \begin{tcolorbox}[colback=white]
  11457. % tests/s2_17.rkt
  11458. \begin{tabular}{lll}
  11459. \begin{minipage}{0.5\textwidth}
  11460. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11461. start:
  11462. tmp9 = (global-value free_ptr);
  11463. tmp0 = (+ tmp9 16);
  11464. tmp1 = (global-value fromspace_end);
  11465. if (< tmp0 tmp1)
  11466. goto block0;
  11467. else
  11468. goto block1;
  11469. block0:
  11470. _4 = (void);
  11471. goto block9;
  11472. block1:
  11473. (collect 16)
  11474. goto block9;
  11475. block9:
  11476. alloc2 = (allocate 1 (Vector Integer));
  11477. _3 = (vector-set! alloc2 0 42);
  11478. vecinit6 = alloc2;
  11479. tmp2 = (global-value free_ptr);
  11480. tmp3 = (+ tmp2 16);
  11481. tmp4 = (global-value fromspace_end);
  11482. if (< tmp3 tmp4)
  11483. goto block7;
  11484. else
  11485. goto block8;
  11486. block7:
  11487. _8 = (void);
  11488. goto block6;
  11489. block8:
  11490. (collect 16)
  11491. goto block6;
  11492. block6:
  11493. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11494. _7 = (vector-set! alloc5 0 vecinit6);
  11495. tmp5 = (vector-ref alloc5 0);
  11496. return (vector-ref tmp5 0);
  11497. \end{lstlisting}
  11498. \end{minipage}
  11499. &$\Rightarrow$&
  11500. \begin{minipage}{0.4\textwidth}
  11501. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11502. start:
  11503. movq free_ptr(%rip), tmp9
  11504. movq tmp9, tmp0
  11505. addq $16, tmp0
  11506. movq fromspace_end(%rip), tmp1
  11507. cmpq tmp1, tmp0
  11508. jl block0
  11509. jmp block1
  11510. block0:
  11511. movq $0, _4
  11512. jmp block9
  11513. block1:
  11514. movq %r15, %rdi
  11515. movq $16, %rsi
  11516. callq collect
  11517. jmp block9
  11518. block9:
  11519. movq free_ptr(%rip), %r11
  11520. addq $16, free_ptr(%rip)
  11521. movq $3, 0(%r11)
  11522. movq %r11, alloc2
  11523. movq alloc2, %r11
  11524. movq $42, 8(%r11)
  11525. movq $0, _3
  11526. movq alloc2, vecinit6
  11527. movq free_ptr(%rip), tmp2
  11528. movq tmp2, tmp3
  11529. addq $16, tmp3
  11530. movq fromspace_end(%rip), tmp4
  11531. cmpq tmp4, tmp3
  11532. jl block7
  11533. jmp block8
  11534. block7:
  11535. movq $0, _8
  11536. jmp block6
  11537. block8:
  11538. movq %r15, %rdi
  11539. movq $16, %rsi
  11540. callq collect
  11541. jmp block6
  11542. block6:
  11543. movq free_ptr(%rip), %r11
  11544. addq $16, free_ptr(%rip)
  11545. movq $131, 0(%r11)
  11546. movq %r11, alloc5
  11547. movq alloc5, %r11
  11548. movq vecinit6, 8(%r11)
  11549. movq $0, _7
  11550. movq alloc5, %r11
  11551. movq 8(%r11), tmp5
  11552. movq tmp5, %r11
  11553. movq 8(%r11), %rax
  11554. jmp conclusion
  11555. \end{lstlisting}
  11556. \end{minipage}
  11557. \end{tabular}
  11558. \end{tcolorbox}
  11559. \caption{Output of the \code{explicate\_control} (left)
  11560. and \code{select\_instructions} (right) passes on the running example.}
  11561. \label{fig:select-instr-output-gc}
  11562. \end{figure}
  11563. \clearpage
  11564. \section{Register Allocation}
  11565. \label{sec:reg-alloc-gc}
  11566. \index{subject}{register allocation}
  11567. As discussed earlier in this chapter, the garbage collector needs to
  11568. access all the pointers in the root set, that is, all variables that
  11569. are tuples. It will be the responsibility of the register allocator
  11570. to make sure that:
  11571. \begin{enumerate}
  11572. \item the root stack is used for spilling tuple-typed variables, and
  11573. \item if a tuple-typed variable is live during a call to the
  11574. collector, it must be spilled to ensure it is visible to the
  11575. collector.
  11576. \end{enumerate}
  11577. The later responsibility can be handled during construction of the
  11578. interference graph, by adding interference edges between the call-live
  11579. tuple-typed variables and all the callee-saved registers. (They
  11580. already interfere with the caller-saved registers.)
  11581. %
  11582. \racket{The type information for variables is in the \code{Program}
  11583. form, so we recommend adding another parameter to the
  11584. \code{build\_interference} function to communicate this alist.}
  11585. %
  11586. \python{The type information for variables is generated by the type
  11587. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11588. the \code{CProgram} AST mode. You'll need to propagate that
  11589. information so that it is available in this pass.}
  11590. The spilling of tuple-typed variables to the root stack can be handled
  11591. after graph coloring, when choosing how to assign the colors
  11592. (integers) to registers and stack locations. The
  11593. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11594. changes to also record the number of spills to the root stack.
  11595. % build-interference
  11596. %
  11597. % callq
  11598. % extra parameter for var->type assoc. list
  11599. % update 'program' and 'if'
  11600. % allocate-registers
  11601. % allocate spilled vectors to the rootstack
  11602. % don't change color-graph
  11603. % TODO:
  11604. %\section{Patch Instructions}
  11605. %[mention that global variables are memory references]
  11606. \section{Prelude and Conclusion}
  11607. \label{sec:print-x86-gc}
  11608. \label{sec:prelude-conclusion-x86-gc}
  11609. \index{subject}{prelude}\index{subject}{conclusion}
  11610. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11611. \code{prelude\_and\_conclusion} pass on the running example. In the
  11612. prelude and conclusion of the \code{main} function, we allocate space
  11613. on the root stack to make room for the spills of tuple-typed
  11614. variables. We do so by bumping the root stack pointer (\code{r15})
  11615. taking care that the root stack grows up instead of down. For the
  11616. running example, there was just one spill so we increment \code{r15}
  11617. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11618. One issue that deserves special care is that there may be a call to
  11619. \code{collect} prior to the initializing assignments for all the
  11620. variables in the root stack. We do not want the garbage collector to
  11621. accidentally think that some uninitialized variable is a pointer that
  11622. needs to be followed. Thus, we zero-out all locations on the root
  11623. stack in the prelude of \code{main}. In
  11624. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11625. %
  11626. \lstinline{movq $0, 0(%r15)}
  11627. %
  11628. is sufficient to accomplish this task because there is only one spill.
  11629. In general, we have to clear as many words as there are spills of
  11630. tuple-typed variables. The garbage collector tests each root to see
  11631. if it is null prior to dereferencing it.
  11632. \begin{figure}[htbp]
  11633. % TODO: Python Version -Jeremy
  11634. \begin{tcolorbox}[colback=white]
  11635. \begin{minipage}[t]{0.5\textwidth}
  11636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11637. .globl main
  11638. main:
  11639. pushq %rbp
  11640. movq %rsp, %rbp
  11641. subq $0, %rsp
  11642. movq $65536, %rdi
  11643. movq $65536, %rsi
  11644. callq initialize
  11645. movq rootstack_begin(%rip), %r15
  11646. movq $0, 0(%r15)
  11647. addq $8, %r15
  11648. jmp start
  11649. conclusion:
  11650. subq $8, %r15
  11651. addq $0, %rsp
  11652. popq %rbp
  11653. retq
  11654. \end{lstlisting}
  11655. \end{minipage}
  11656. \end{tcolorbox}
  11657. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11658. \label{fig:print-x86-output-gc}
  11659. \end{figure}
  11660. \begin{figure}[tbp]
  11661. \begin{tcolorbox}[colback=white]
  11662. {\if\edition\racketEd
  11663. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11664. \node (Lvec) at (0,2) {\large \LangVec{}};
  11665. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11666. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11667. \node (Lvec-4) at (9,2) {\large \LangAlloc{}};
  11668. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11669. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11670. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11671. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11672. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11673. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11674. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11675. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11676. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11677. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11678. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11679. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11680. \path[->,bend left=15] (Lvec-4) edge [right] node
  11681. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11682. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11683. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11684. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11685. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11686. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11687. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11688. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11689. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11690. \end{tikzpicture}
  11691. \fi}
  11692. {\if\edition\pythonEd
  11693. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11694. \node (Lvec) at (0,2) {\large \LangVec{}};
  11695. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11696. \node (Lvec-5) at (6,2) {\large \LangAlloc{}};
  11697. \node (Lvec-6) at (9,2) {\large \LangAllocANF{}};
  11698. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11699. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11700. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11701. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11702. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11703. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11704. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11705. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11706. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-5);
  11707. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11708. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11709. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11710. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11711. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11712. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11713. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11714. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11715. \end{tikzpicture}
  11716. \fi}
  11717. \end{tcolorbox}
  11718. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11719. \label{fig:Lvec-passes}
  11720. \end{figure}
  11721. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11722. for the compilation of \LangVec{}.
  11723. \clearpage
  11724. {\if\edition\racketEd
  11725. \section{Challenge: Simple Structures}
  11726. \label{sec:simple-structures}
  11727. \index{subject}{struct}
  11728. \index{subject}{structure}
  11729. The language \LangStruct{} extends \LangVec{} with support for simple
  11730. structures. Its concrete syntax is defined in
  11731. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11732. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11733. Racket is a user-defined data type that contains named fields and that
  11734. is heap allocated, similar to a vector. The following is an example of
  11735. a structure definition, in this case the definition of a \code{point}
  11736. type.
  11737. \begin{lstlisting}
  11738. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11739. \end{lstlisting}
  11740. \newcommand{\LstructGrammarRacket}{
  11741. \begin{array}{lcl}
  11742. \Type &::=& \Var \\
  11743. \Exp &::=& (\Var\;\Exp \ldots)\\
  11744. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11745. \end{array}
  11746. }
  11747. \newcommand{\LstructASTRacket}{
  11748. \begin{array}{lcl}
  11749. \Type &::=& \VAR{\Var} \\
  11750. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11751. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11752. \end{array}
  11753. }
  11754. \begin{figure}[tbp]
  11755. \centering
  11756. \begin{tcolorbox}[colback=white]
  11757. \[
  11758. \begin{array}{l}
  11759. \gray{\LintGrammarRacket{}} \\ \hline
  11760. \gray{\LvarGrammarRacket{}} \\ \hline
  11761. \gray{\LifGrammarRacket{}} \\ \hline
  11762. \gray{\LwhileGrammarRacket} \\ \hline
  11763. \gray{\LtupGrammarRacket} \\ \hline
  11764. \LstructGrammarRacket \\
  11765. \begin{array}{lcl}
  11766. \LangStruct{} &::=& \Def \ldots \; \Exp
  11767. \end{array}
  11768. \end{array}
  11769. \]
  11770. \end{tcolorbox}
  11771. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11772. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11773. \label{fig:Lstruct-concrete-syntax}
  11774. \end{figure}
  11775. \begin{figure}[tbp]
  11776. \centering
  11777. \begin{tcolorbox}[colback=white]
  11778. \small
  11779. \[
  11780. \begin{array}{l}
  11781. \gray{\LintASTRacket{}} \\ \hline
  11782. \gray{\LvarASTRacket{}} \\ \hline
  11783. \gray{\LifASTRacket{}} \\ \hline
  11784. \gray{\LwhileASTRacket} \\ \hline
  11785. \gray{\LtupASTRacket} \\ \hline
  11786. \LstructASTRacket \\
  11787. \begin{array}{lcl}
  11788. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11789. \end{array}
  11790. \end{array}
  11791. \]
  11792. \end{tcolorbox}
  11793. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11794. (Figure~\ref{fig:Lvec-syntax}).}
  11795. \label{fig:Lstruct-syntax}
  11796. \end{figure}
  11797. An instance of a structure is created using function call syntax, with
  11798. the name of the structure in the function position:
  11799. \begin{lstlisting}
  11800. (point 7 12)
  11801. \end{lstlisting}
  11802. Function-call syntax is also used to read a field of a structure. The
  11803. function name is formed by the structure name, a dash, and the field
  11804. name. The following example uses \code{point-x} and \code{point-y} to
  11805. access the \code{x} and \code{y} fields of two point instances.
  11806. \begin{center}
  11807. \begin{lstlisting}
  11808. (let ([pt1 (point 7 12)])
  11809. (let ([pt2 (point 4 3)])
  11810. (+ (- (point-x pt1) (point-x pt2))
  11811. (- (point-y pt1) (point-y pt2)))))
  11812. \end{lstlisting}
  11813. \end{center}
  11814. Similarly, to write to a field of a structure, use its set function,
  11815. whose name starts with \code{set-}, followed by the structure name,
  11816. then a dash, then the field name, and concluded with an exclamation
  11817. mark. The following example uses \code{set-point-x!} to change the
  11818. \code{x} field from \code{7} to \code{42}.
  11819. \begin{center}
  11820. \begin{lstlisting}
  11821. (let ([pt (point 7 12)])
  11822. (let ([_ (set-point-x! pt 42)])
  11823. (point-x pt)))
  11824. \end{lstlisting}
  11825. \end{center}
  11826. \begin{exercise}\normalfont\normalsize
  11827. Create a type checker for \LangStruct{} by extending the type
  11828. checker for \LangVec{}. Extend your compiler with support for simple
  11829. structures, compiling \LangStruct{} to x86 assembly code. Create
  11830. five new test cases that use structures and test your compiler.
  11831. \end{exercise}
  11832. % TODO: create an interpreter for L_struct
  11833. \clearpage
  11834. \fi}
  11835. \section{Challenge: Arrays}
  11836. \label{sec:arrays}
  11837. In this chapter we have studied tuples, that is, a heterogeneous
  11838. sequences of elements whose length is determined at compile-time. This
  11839. challenge is also about sequences, but this time the length is
  11840. determined at run-time and all the elements have the same type (they
  11841. are homogeneous). We use the term ``array'' for this later kind of
  11842. sequence.
  11843. %
  11844. \racket{
  11845. The Racket language does not distinguish between tuples and arrays,
  11846. they are both represented by vectors. However, Typed Racket
  11847. distinguishes between tuples and arrays: the \code{Vector} type is for
  11848. tuples and the \code{Vectorof} type is for arrays.}
  11849. \python{
  11850. Arrays correspond to the \code{list} type in Python language.
  11851. }
  11852. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11853. for \LangArray{} and Figure~\ref{fig:Lvecof-syntax} defines the
  11854. abstract syntax, extending \LangVec{} with the
  11855. \racket{\code{Vectorof}}\python{\code{list}} type and the
  11856. %
  11857. \racket{\code{make-vector} primitive operator for creating an array,
  11858. whose arguments are the length of the array and an initial value for
  11859. all the elements in the array.}
  11860. \python{bracket notation for creating an array literal.}
  11861. \racket{
  11862. The \code{vector-length},
  11863. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11864. for tuples become overloaded for use with arrays.}
  11865. \python{
  11866. The subscript operator becomes overloaded for use with arrays and tuples
  11867. and now may appear on the left-hand side of an assignment.
  11868. Note that the index of the subscript, when applied to an array, may be an
  11869. arbitrary expression and not just a constant integer.
  11870. The \code{len} function is also applicable to arrays.
  11871. }
  11872. %
  11873. We include integer multiplication in \LangArray{}, as it is
  11874. useful in many examples involving arrays such as computing the
  11875. inner product of two arrays (Figure~\ref{fig:inner_product}).
  11876. \newcommand{\LarrayGrammarRacket}{
  11877. \begin{array}{lcl}
  11878. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11879. \Exp &::=& \CMUL{\Exp}{\Exp}
  11880. \MID \CMAKEVEC{\Exp}{\Exp}
  11881. \end{array}
  11882. }
  11883. \newcommand{\LarrayASTRacket}{
  11884. \begin{array}{lcl}
  11885. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11886. \Exp &::=& \MUL{\Exp}{\Exp}
  11887. \MID \MAKEVEC{\Exp}{\Exp}
  11888. \end{array}
  11889. }
  11890. \newcommand{\LarrayGrammarPython}{
  11891. \begin{array}{lcl}
  11892. \Type &::=& \key{list}\LS\Type\RS \\
  11893. \Exp &::=& \CMUL{\Exp}{\Exp}
  11894. \MID \CGET{\Exp}{\Exp}
  11895. \MID \LS \Exp \code{,} \ldots \RS \\
  11896. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  11897. \end{array}
  11898. }
  11899. \newcommand{\LarrayASTPython}{
  11900. \begin{array}{lcl}
  11901. \Type &::=& \key{ListType}\LP\Type\RP \\
  11902. \Exp &::=& \MUL{\Exp}{\Exp}
  11903. \MID \GET{\Exp}{\Exp} \\
  11904. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  11905. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  11906. \end{array}
  11907. }
  11908. \begin{figure}[tp]
  11909. \centering
  11910. \begin{tcolorbox}[colback=white]
  11911. \small
  11912. {\if\edition\racketEd
  11913. \[
  11914. \begin{array}{l}
  11915. \gray{\LintGrammarRacket{}} \\ \hline
  11916. \gray{\LvarGrammarRacket{}} \\ \hline
  11917. \gray{\LifGrammarRacket{}} \\ \hline
  11918. \gray{\LwhileGrammarRacket} \\ \hline
  11919. \gray{\LtupGrammarRacket} \\ \hline
  11920. \LarrayGrammarRacket \\
  11921. \begin{array}{lcl}
  11922. \LangArray{} &::=& \Exp
  11923. \end{array}
  11924. \end{array}
  11925. \]
  11926. \fi}
  11927. {\if\edition\pythonEd
  11928. \[
  11929. \begin{array}{l}
  11930. \gray{\LintGrammarPython{}} \\ \hline
  11931. \gray{\LvarGrammarPython{}} \\ \hline
  11932. \gray{\LifGrammarPython{}} \\ \hline
  11933. \gray{\LwhileGrammarPython} \\ \hline
  11934. \gray{\LtupGrammarPython} \\ \hline
  11935. \LarrayGrammarPython \\
  11936. \begin{array}{rcl}
  11937. \LangArrayM{} &::=& \Stmt^{*}
  11938. \end{array}
  11939. \end{array}
  11940. \]
  11941. \fi}
  11942. \end{tcolorbox}
  11943. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11944. \label{fig:Lvecof-concrete-syntax}
  11945. \end{figure}
  11946. \begin{figure}[tp]
  11947. \centering
  11948. \begin{tcolorbox}[colback=white]
  11949. \small
  11950. {\if\edition\racketEd
  11951. \[
  11952. \begin{array}{l}
  11953. \gray{\LintASTRacket{}} \\ \hline
  11954. \gray{\LvarASTRacket{}} \\ \hline
  11955. \gray{\LifASTRacket{}} \\ \hline
  11956. \gray{\LwhileASTRacket} \\ \hline
  11957. \gray{\LtupASTRacket} \\ \hline
  11958. \LarrayASTRacket \\
  11959. \begin{array}{lcl}
  11960. \LangArray{} &::=& \Exp
  11961. \end{array}
  11962. \end{array}
  11963. \]
  11964. \fi}
  11965. {\if\edition\pythonEd
  11966. \[
  11967. \begin{array}{l}
  11968. \gray{\LintASTPython{}} \\ \hline
  11969. \gray{\LvarASTPython{}} \\ \hline
  11970. \gray{\LifASTPython{}} \\ \hline
  11971. \gray{\LwhileASTPython} \\ \hline
  11972. \gray{\LtupASTPython} \\ \hline
  11973. \LarrayASTPython \\
  11974. \begin{array}{rcl}
  11975. \LangArrayM{} &::=& \Stmt^{*}
  11976. \end{array}
  11977. \end{array}
  11978. \]
  11979. \fi}
  11980. \end{tcolorbox}
  11981. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  11982. \label{fig:Lvecof-syntax}
  11983. \end{figure}
  11984. \begin{figure}[tp]
  11985. \begin{tcolorbox}[colback=white]
  11986. {\if\edition\racketEd
  11987. % TODO: remove the function from the following example, like the python version -Jeremy
  11988. \begin{lstlisting}
  11989. (let ([A (make-vector 2 2)])
  11990. (let ([B (make-vector 2 3)])
  11991. (let ([i 0])
  11992. (let ([prod 0])
  11993. (begin
  11994. (while (< i n)
  11995. (begin
  11996. (set! prod (+ prod (* (vector-ref A i)
  11997. (vector-ref B i))))
  11998. (set! i (+ i 1))))
  11999. prod)))))
  12000. \end{lstlisting}
  12001. \fi}
  12002. {\if\edition\pythonEd
  12003. \begin{lstlisting}
  12004. A = [2, 2]
  12005. B = [3, 3]
  12006. i = 0
  12007. prod = 0
  12008. while i != len(A):
  12009. prod = prod + A[i] * B[i]
  12010. i = i + 1
  12011. print( prod )
  12012. \end{lstlisting}
  12013. \fi}
  12014. \end{tcolorbox}
  12015. \caption{Example program that computes the inner product.}
  12016. \label{fig:inner_product}
  12017. \end{figure}
  12018. {\if\edition\racketEd
  12019. The type checker for \LangArray{} is defined in
  12020. Figure~\ref{fig:type-check-Lvecof}. The result type of
  12021. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  12022. of the initializing expression. The length expression is required to
  12023. have type \code{Integer}. The type checking of the operators
  12024. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12025. updated to handle the situation where the vector has type
  12026. \code{Vectorof}. In these cases we translate the operators to their
  12027. \code{vectorof} form so that later passes can easily distinguish
  12028. between operations on tuples versus arrays. We override the
  12029. \code{operator-types} method to provide the type signature for
  12030. multiplication: it takes two integers and returns an integer.
  12031. \fi}
  12032. {\if\edition\pythonEd
  12033. %
  12034. The type checker for \LangArray{} is defined in
  12035. Figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12036. is \code{list[T]} where \code{T} is the type of the initializing
  12037. expressions. The type checking of the \code{len} function and the
  12038. subscript operator is updated to handle lists. The type checker now
  12039. also handles a subscript on the left-hand side of an assignment.
  12040. Regarding multiplication, it takes two integers and returns an
  12041. integer.
  12042. %
  12043. \fi}
  12044. \begin{figure}[tbp]
  12045. \begin{tcolorbox}[colback=white]
  12046. {\if\edition\racketEd
  12047. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12048. (define type-check-Lvecof-class
  12049. (class type-check-Lvec-class
  12050. (super-new)
  12051. (inherit check-type-equal?)
  12052. (define/override (operator-types)
  12053. (append '((* . ((Integer Integer) . Integer)))
  12054. (super operator-types)))
  12055. (define/override (type-check-exp env)
  12056. (lambda (e)
  12057. (define recur (type-check-exp env))
  12058. (match e
  12059. [(Prim 'make-vector (list e1 e2))
  12060. (define-values (e1^ t1) (recur e1))
  12061. (define-values (e2^ elt-type) (recur e2))
  12062. (define vec-type `(Vectorof ,elt-type))
  12063. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  12064. vec-type)]
  12065. [(Prim 'vector-ref (list e1 e2))
  12066. (define-values (e1^ t1) (recur e1))
  12067. (define-values (e2^ t2) (recur e2))
  12068. (match* (t1 t2)
  12069. [(`(Vectorof ,elt-type) 'Integer)
  12070. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12071. [(other wise) ((super type-check-exp env) e)])]
  12072. [(Prim 'vector-set! (list e1 e2 e3) )
  12073. (define-values (e-vec t-vec) (recur e1))
  12074. (define-values (e2^ t2) (recur e2))
  12075. (define-values (e-arg^ t-arg) (recur e3))
  12076. (match t-vec
  12077. [`(Vectorof ,elt-type)
  12078. (check-type-equal? elt-type t-arg e)
  12079. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12080. [else ((super type-check-exp env) e)])]
  12081. [(Prim 'vector-length (list e1))
  12082. (define-values (e1^ t1) (recur e1))
  12083. (match t1
  12084. [`(Vectorof ,t)
  12085. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12086. [else ((super type-check-exp env) e)])]
  12087. [else ((super type-check-exp env) e)])))
  12088. ))
  12089. (define (type-check-Lvecof p)
  12090. (send (new type-check-Lvecof-class) type-check-program p))
  12091. \end{lstlisting}
  12092. \fi}
  12093. {\if\edition\pythonEd
  12094. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12095. class TypeCheckLarray(TypeCheckLtup):
  12096. def type_check_exp(self, e, env):
  12097. match e:
  12098. case ast.List(es, Load()):
  12099. ts = [self.type_check_exp(e, env) for e in es]
  12100. elt_ty = ts[0]
  12101. for (ty, elt) in zip(ts, es):
  12102. self.check_type_equal(elt_ty, ty, elt)
  12103. e.has_type = ListType(elt_ty)
  12104. return e.has_type
  12105. case Call(Name('len'), [tup]):
  12106. tup_t = self.type_check_exp(tup, env)
  12107. tup.has_type = tup_t
  12108. match tup_t:
  12109. case TupleType(ts):
  12110. return IntType()
  12111. case ListType(ty):
  12112. return IntType()
  12113. case _:
  12114. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12115. case Subscript(tup, index, Load()):
  12116. tup_ty = self.type_check_exp(tup, env)
  12117. index_ty = self.type_check_exp(index, env)
  12118. self.check_type_equal(index_ty, IntType(), index)
  12119. match tup_ty:
  12120. case TupleType(ts):
  12121. match index:
  12122. case Constant(i):
  12123. return ts[i]
  12124. case _:
  12125. raise Exception('subscript required constant integer index')
  12126. case ListType(ty):
  12127. return ty
  12128. case _:
  12129. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12130. case BinOp(left, Mult(), right):
  12131. l = self.type_check_exp(left, env)
  12132. self.check_type_equal(l, IntType(), left)
  12133. r = self.type_check_exp(right, env)
  12134. self.check_type_equal(r, IntType(), right)
  12135. return IntType()
  12136. case _:
  12137. return super().type_check_exp(e, env)
  12138. def type_check_stmts(self, ss, env):
  12139. if len(ss) == 0:
  12140. return VoidType()
  12141. match ss[0]:
  12142. case Assign([Subscript(tup, index, Store())], value):
  12143. tup_t = self.type_check_exp(tup, env)
  12144. value_t = self.type_check_exp(value, env)
  12145. index_ty = self.type_check_exp(index, env)
  12146. self.check_type_equal(index_ty, IntType(), index)
  12147. match tup_t:
  12148. case ListType(ty):
  12149. self.check_type_equal(ty, value_t, ss[0])
  12150. case TupleType(ts):
  12151. return self.type_check_stmts(ss, env)
  12152. case _:
  12153. raise Exception('type_check_stmts: '
  12154. 'expected tuple or list, not ' + repr(tup_t))
  12155. return self.type_check_stmts(ss[1:], env)
  12156. case _:
  12157. return super().type_check_stmts(ss, env)
  12158. \end{lstlisting}
  12159. \fi}
  12160. \end{tcolorbox}
  12161. \caption{Type checker for the \LangArray{} language.}
  12162. \label{fig:type-check-Lvecof}
  12163. \end{figure}
  12164. The interpreter for \LangArray{} is defined in
  12165. Figure~\ref{fig:interp-Lvecof}.
  12166. \racket{The \code{make-vector} operator is
  12167. implemented with Racket's \code{make-vector} function and
  12168. multiplication is \code{fx*}, multiplication for \code{fixnum}
  12169. integers.}
  12170. %
  12171. \python{We implement list creation with a Python list comprehension
  12172. and multiplication is implemented with Python multiplication. We
  12173. add a case to handle a subscript on the left-hand side of
  12174. assignment. Other uses of subscript can be handled by the existing
  12175. code for tuples.}
  12176. \begin{figure}[tbp]
  12177. \begin{tcolorbox}[colback=white]
  12178. {\if\edition\racketEd
  12179. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12180. (define interp-Lvecof-class
  12181. (class interp-Lvec-class
  12182. (super-new)
  12183. (define/override (interp-op op)
  12184. (match op
  12185. ['make-vector make-vector]
  12186. ['* fx*]
  12187. [else (super interp-op op)]))
  12188. ))
  12189. (define (interp-Lvecof p)
  12190. (send (new interp-Lvecof-class) interp-program p))
  12191. \end{lstlisting}
  12192. \fi}
  12193. {\if\edition\pythonEd
  12194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12195. class InterpLarray(InterpLtup):
  12196. def interp_exp(self, e, env):
  12197. match e:
  12198. case ast.List(es, Load()):
  12199. return [self.interp_exp(e, env) for e in es]
  12200. case BinOp(left, Mult(), right):
  12201. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12202. return l * r
  12203. case _:
  12204. return super().interp_exp(e, env)
  12205. def interp_stmts(self, ss, env):
  12206. if len(ss) == 0:
  12207. return
  12208. match ss[0]:
  12209. case Assign([Subscript(lst, index)], value):
  12210. lst = self.interp_exp(lst, env)
  12211. index = self.interp_exp(index, env)
  12212. lst[index] = self.interp_exp(value, env)
  12213. return self.interp_stmts(ss[1:], env)
  12214. case _:
  12215. return super().interp_stmts(ss, env)
  12216. \end{lstlisting}
  12217. \fi}
  12218. \end{tcolorbox}
  12219. \caption{Interpreter for \LangArray{}.}
  12220. \label{fig:interp-Lvecof}
  12221. \end{figure}
  12222. \subsection{Data Representation}
  12223. \label{sec:array-rep}
  12224. Just like tuples, we store arrays on the heap which means that the
  12225. garbage collector will need to inspect arrays. An immediate thought is
  12226. to use the same representation for arrays that we use for tuples.
  12227. However, we limit tuples to a length of $50$ so that their length and
  12228. pointer mask can fit into the 64-bit tag at the beginning of each
  12229. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12230. millions of elements, so we need more bits to store the length.
  12231. However, because arrays are homogeneous, we only need one bit for the
  12232. pointer mask instead of one bit per array element. Finally, the
  12233. garbage collector must be able to distinguish between tuples
  12234. and arrays, so we need to reserve one bit for that purpose. We
  12235. arrive at the following layout for the 64-bit tag at the beginning of
  12236. an array:
  12237. \begin{itemize}
  12238. \item The right-most bit is the forwarding bit, just like in a tuple.
  12239. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  12240. it is not.
  12241. \item The next bit to the left is the pointer mask. A $0$ indicates
  12242. that none of the elements are pointers to the heap and a $1$
  12243. indicates that all of the elements are pointers.
  12244. \item The next $60$ bits store the length of the array.
  12245. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12246. versus an array ($1$).
  12247. \item The left-most bit is reserved for use in Chapter~\ref{ch:Lgrad}.
  12248. \end{itemize}
  12249. %% Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12250. %% differentiate the kinds of values that have been injected into the
  12251. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12252. %% to indicate that the value is an array.
  12253. In the following subsections we provide hints regarding how to update
  12254. the passes to handle arrays.
  12255. \subsection{Overload Resolution}
  12256. \label{sec:array-resolution}
  12257. As noted above, with the addition of arrays, several operators have
  12258. become \emph{overloaded}, that is, they can be applied to values of
  12259. more than one type. In this case, the element access and \code{len}
  12260. operators can be applied to both tuples and arrays. This kind of
  12261. overloading is quite common in programming languages, so many
  12262. compilers perform \emph{overload resolution}\index{subject}{overload resolution}
  12263. to handle it. The idea is to translate each overloaded
  12264. operator into different operators for the different types.
  12265. Implement a new pass named \code{resolve}.
  12266. Translate the reading of an array element
  12267. into a call to
  12268. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12269. and the writing of an array element to
  12270. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12271. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12272. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12273. When these operators are applied to tuples, leave them as-is.
  12274. %
  12275. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12276. field which can be inspected to determine whether the operator
  12277. is applied to a tuple or an array.}
  12278. \subsection{Bounds Checking}
  12279. We recommend inserting a new pass named \code{check\_bounds} that
  12280. inserts code around each \racket{\code{vector-ref} and \code{vector-set!}}
  12281. \python{subscript} operation to ensure that the index is greater than or
  12282. equal to zero and less than the array's length.
  12283. %% \subsection{Reveal Casts}
  12284. %% The array-access operators \code{vectorof-ref} and
  12285. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12286. %% \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  12287. %% that the type checker cannot tell whether the index will be in bounds,
  12288. %% so the bounds check must be performed at run time. Recall that the
  12289. %% \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  12290. %% an \code{If} arround a vector reference for update to check whether
  12291. %% the index is less than the length. You should do the same for
  12292. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12293. %% In addition, the handling of the \code{any-vector} operators in
  12294. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12295. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12296. %% generated code should test whether the tag is for tuples (\code{010})
  12297. %% or arrays (\code{110}) and then dispatch to either
  12298. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12299. %% we add a case in \code{select\_instructions} to generate the
  12300. %% appropriate instructions for accessing the array length from the
  12301. %% header of an array.
  12302. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12303. %% the generated code needs to check that the index is less than the
  12304. %% vector length, so like the code for \code{any-vector-length}, check
  12305. %% the tag to determine whether to use \code{any-vector-length} or
  12306. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12307. %% is complete, the generated code can use \code{any-vector-ref} and
  12308. %% \code{any-vector-set!} for both tuples and arrays because the
  12309. %% instructions used for those operators do not look at the tag at the
  12310. %% front of the tuple or array.
  12311. \subsection{Expose Allocation}
  12312. This pass should translate array creation into lower-level
  12313. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12314. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12315. argument must be \ARRAYTY{T} where $T$ is the element type for the
  12316. array. The \code{AllocateArray} AST node allocates an array of the
  12317. length specified by the $\Exp$ (of type \INTTY), but does not initialize the elements of
  12318. the array. Generate code in this pass to initialize the elements
  12319. analogous to the case for tuples.
  12320. \subsection{Remove Complex Operands}
  12321. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12322. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12323. complex and its subexpression must be atomic.
  12324. \subsection{Explicate Control}
  12325. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12326. \code{explicate\_assign}.
  12327. \subsection{Select Instructions}
  12328. Generate instructions for \code{AllocateArray} similar to those for
  12329. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  12330. that the tag at the front of the array should instead use the
  12331. representation discussed in Section~\ref{sec:array-rep}.
  12332. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12333. extract the length from the tag according to the representation discussed in
  12334. Section~\ref{sec:array-rep}.
  12335. The instructions generated for accessing an element of an array differ
  12336. from those for a tuple (Section~\ref{sec:select-instructions-gc}) in
  12337. that the index is not a constant so the offset must be computed at
  12338. runtime.
  12339. %% Also, note that assignment to an array element may appear in
  12340. %% as a stand-alone statement, so make sure to handle that situation in
  12341. %% this pass.
  12342. %% Finally, the instructions for \code{any-vectorof-length} should be
  12343. %% similar to those for \code{vectorof-length}, except that one must
  12344. %% first project the array by writing zeroes into the $3$-bit tag
  12345. \begin{exercise}\normalfont\normalsize
  12346. Implement a compiler for the \LangArray{} language by extending your
  12347. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12348. programs, including the one in Figure~\ref{fig:inner_product} and also
  12349. a program that multiplies two matrices. Note that although matrices
  12350. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12351. arrays by laying out each row in the array, one after the next.
  12352. \end{exercise}
  12353. {\if\edition\racketEd
  12354. \section{Challenge: Generational Collection}
  12355. The copying collector described in Section~\ref{sec:GC} can incur
  12356. significant runtime overhead because the call to \code{collect} takes
  12357. time proportional to all of the live data. One way to reduce this
  12358. overhead is to reduce how much data is inspected in each call to
  12359. \code{collect}. In particular, researchers have observed that recently
  12360. allocated data is more likely to become garbage then data that has
  12361. survived one or more previous calls to \code{collect}. This insight
  12362. motivated the creation of \emph{generational garbage collectors}
  12363. \index{subject}{generational garbage collector} that
  12364. 1) segregates data according to its age into two or more generations,
  12365. 2) allocates less space for younger generations, so collecting them is
  12366. faster, and more space for the older generations, and 3) performs
  12367. collection on the younger generations more frequently then for older
  12368. generations~\citep{Wilson:1992fk}.
  12369. For this challenge assignment, the goal is to adapt the copying
  12370. collector implemented in \code{runtime.c} to use two generations, one
  12371. for young data and one for old data. Each generation consists of a
  12372. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12373. \code{collect} function to use the two generations.
  12374. \begin{enumerate}
  12375. \item Copy the young generation's FromSpace to its ToSpace then switch
  12376. the role of the ToSpace and FromSpace
  12377. \item If there is enough space for the requested number of bytes in
  12378. the young FromSpace, then return from \code{collect}.
  12379. \item If there is not enough space in the young FromSpace for the
  12380. requested bytes, then move the data from the young generation to the
  12381. old one with the following steps:
  12382. \begin{enumerate}
  12383. \item If there is enough room in the old FromSpace, copy the young
  12384. FromSpace to the old FromSpace and then return.
  12385. \item If there is not enough room in the old FromSpace, then collect
  12386. the old generation by copying the old FromSpace to the old ToSpace
  12387. and swap the roles of the old FromSpace and ToSpace.
  12388. \item If there is enough room now, copy the young FromSpace to the
  12389. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12390. and ToSpace for the old generation. Copy the young FromSpace and
  12391. the old FromSpace into the larger FromSpace for the old
  12392. generation and then return.
  12393. \end{enumerate}
  12394. \end{enumerate}
  12395. We recommend that you generalize the \code{cheney} function so that it
  12396. can be used for all the copies mentioned above: between the young
  12397. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12398. between the young FromSpace and old FromSpace. This can be
  12399. accomplished by adding parameters to \code{cheney} that replace its
  12400. use of the global variables \code{fromspace\_begin},
  12401. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12402. Note that the collection of the young generation does not traverse the
  12403. old generation. This introduces a potential problem: there may be
  12404. young data that is only reachable through pointers in the old
  12405. generation. If these pointers are not taken into account, the
  12406. collector could throw away young data that is live! One solution,
  12407. called \emph{pointer recording}, is to maintain a set of all the
  12408. pointers from the old generation into the new generation and consider
  12409. this set as part of the root set. To maintain this set, the compiler
  12410. must insert extra instructions around every \code{vector-set!}. If the
  12411. vector being modified is in the old generation, and if the value being
  12412. written is a pointer into the new generation, than that pointer must
  12413. be added to the set. Also, if the value being overwritten was a
  12414. pointer into the new generation, then that pointer should be removed
  12415. from the set.
  12416. \begin{exercise}\normalfont\normalsize
  12417. Adapt the \code{collect} function in \code{runtime.c} to implement
  12418. generational garbage collection, as outlined in this section.
  12419. Update the code generation for \code{vector-set!} to implement
  12420. pointer recording. Make sure that your new compiler and runtime
  12421. passes your test suite.
  12422. \end{exercise}
  12423. \fi}
  12424. \section{Further Reading}
  12425. \citet{Appel90} describes many data representation approaches,
  12426. including the ones used in the compilation of Standard ML.
  12427. There are many alternatives to copying collectors (and their bigger
  12428. siblings, the generational collectors) when its comes to garbage
  12429. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12430. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12431. collectors are that allocation is fast (just a comparison and pointer
  12432. increment), there is no fragmentation, cyclic garbage is collected,
  12433. and the time complexity of collection only depends on the amount of
  12434. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12435. main disadvantages of a two-space copying collector is that it uses a
  12436. lot of extra space and takes a long time to perform the copy, though
  12437. these problems are ameliorated in generational collectors.
  12438. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12439. small objects and generate a lot of garbage, so copying and
  12440. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12441. Garbage collection is an active research topic, especially concurrent
  12442. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12443. developing new techniques and revisiting old
  12444. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12445. meet every year at the International Symposium on Memory Management to
  12446. present these findings.
  12447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12448. \chapter{Functions}
  12449. \label{ch:Lfun}
  12450. \index{subject}{function}
  12451. This chapter studies the compilation of a subset of \racket{Typed
  12452. Racket}\python{Python} in which only top-level function definitions
  12453. are allowed. This kind of function appears in the C programming
  12454. language and it serves as an important stepping stone to implementing
  12455. lexically-scoped functions in the form of \key{lambda} abstractions,
  12456. which is the topic of Chapter~\ref{ch:Llambda}.
  12457. \section{The \LangFun{} Language}
  12458. The concrete and abstract syntax for function definitions and function
  12459. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12460. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12461. Programs in \LangFun{} begin with zero or more function definitions.
  12462. The function names from these definitions are in-scope for the entire
  12463. program, including all of the function definitions (so the ordering of
  12464. function definitions does not matter).
  12465. %
  12466. \python{The abstract syntax for function parameters in
  12467. Figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12468. consists of a parameter name and its type. This design differs from
  12469. Python's \code{ast} module, which has a more complex structure for
  12470. function parameters to handle keyword parameters,
  12471. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12472. complex Python abstract syntax into the simpler syntax of
  12473. Figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12474. \code{FunctionDef} constructor are for decorators and a type
  12475. comment, neither of which are used by our compiler. We recommend
  12476. replacing them with \code{None} in the \code{shrink} pass.
  12477. }
  12478. %
  12479. The concrete syntax for function application\index{subject}{function
  12480. application} is
  12481. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12482. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12483. where the first expression
  12484. must evaluate to a function and the remaining expressions are the arguments. The
  12485. abstract syntax for function application is
  12486. $\APPLY{\Exp}{\Exp^*}$.
  12487. %% The syntax for function application does not include an explicit
  12488. %% keyword, which is error prone when using \code{match}. To alleviate
  12489. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12490. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12491. Functions are first-class in the sense that a function pointer
  12492. \index{subject}{function pointer} is data and can be stored in memory or passed
  12493. as a parameter to another function. Thus, there is a function
  12494. type, written
  12495. {\if\edition\racketEd
  12496. \begin{lstlisting}
  12497. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12498. \end{lstlisting}
  12499. \fi}
  12500. {\if\edition\pythonEd
  12501. \begin{lstlisting}
  12502. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12503. \end{lstlisting}
  12504. \fi}
  12505. %
  12506. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12507. through $\Type_n$ and whose return type is $\Type_R$. The main
  12508. limitation of these functions (with respect to
  12509. \racket{Racket}\python{Python} functions) is that they are not
  12510. lexically scoped. That is, the only external entities that can be
  12511. referenced from inside a function body are other globally-defined
  12512. functions. The syntax of \LangFun{} prevents function definitions from being
  12513. nested inside each other.
  12514. \newcommand{\LfunGrammarRacket}{
  12515. \begin{array}{lcl}
  12516. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12517. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12518. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12519. \end{array}
  12520. }
  12521. \newcommand{\LfunASTRacket}{
  12522. \begin{array}{lcl}
  12523. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12524. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12525. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12526. \end{array}
  12527. }
  12528. \newcommand{\LfunGrammarPython}{
  12529. \begin{array}{lcl}
  12530. \Type &::=& \key{int}
  12531. \MID \key{bool} \MID \key{void}
  12532. \MID \key{tuple}\LS \Type^+ \RS
  12533. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12534. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12535. \Stmt &::=& \CRETURN{\Exp} \\
  12536. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12537. \end{array}
  12538. }
  12539. \newcommand{\LfunASTPython}{
  12540. \begin{array}{lcl}
  12541. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12542. \MID \key{TupleType}\LS\Type^+\RS\\
  12543. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12544. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12545. \Stmt &::=& \RETURN{\Exp} \\
  12546. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12547. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12548. \end{array}
  12549. }
  12550. \begin{figure}[tp]
  12551. \centering
  12552. \begin{tcolorbox}[colback=white]
  12553. \small
  12554. {\if\edition\racketEd
  12555. \[
  12556. \begin{array}{l}
  12557. \gray{\LintGrammarRacket{}} \\ \hline
  12558. \gray{\LvarGrammarRacket{}} \\ \hline
  12559. \gray{\LifGrammarRacket{}} \\ \hline
  12560. \gray{\LwhileGrammarRacket} \\ \hline
  12561. \gray{\LtupGrammarRacket} \\ \hline
  12562. \LfunGrammarRacket \\
  12563. \begin{array}{lcl}
  12564. \LangFunM{} &::=& \Def \ldots \; \Exp
  12565. \end{array}
  12566. \end{array}
  12567. \]
  12568. \fi}
  12569. {\if\edition\pythonEd
  12570. \[
  12571. \begin{array}{l}
  12572. \gray{\LintGrammarPython{}} \\ \hline
  12573. \gray{\LvarGrammarPython{}} \\ \hline
  12574. \gray{\LifGrammarPython{}} \\ \hline
  12575. \gray{\LwhileGrammarPython} \\ \hline
  12576. \gray{\LtupGrammarPython} \\ \hline
  12577. \LfunGrammarPython \\
  12578. \begin{array}{rcl}
  12579. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12580. \end{array}
  12581. \end{array}
  12582. \]
  12583. \fi}
  12584. \end{tcolorbox}
  12585. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12586. \label{fig:Lfun-concrete-syntax}
  12587. \end{figure}
  12588. \begin{figure}[tp]
  12589. \centering
  12590. \begin{tcolorbox}[colback=white]
  12591. \small
  12592. {\if\edition\racketEd
  12593. \[
  12594. \begin{array}{l}
  12595. \gray{\LintOpAST} \\ \hline
  12596. \gray{\LvarASTRacket{}} \\ \hline
  12597. \gray{\LifASTRacket{}} \\ \hline
  12598. \gray{\LwhileASTRacket{}} \\ \hline
  12599. \gray{\LtupASTRacket{}} \\ \hline
  12600. \LfunASTRacket \\
  12601. \begin{array}{lcl}
  12602. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12603. \end{array}
  12604. \end{array}
  12605. \]
  12606. \fi}
  12607. {\if\edition\pythonEd
  12608. \[
  12609. \begin{array}{l}
  12610. \gray{\LintASTPython{}} \\ \hline
  12611. \gray{\LvarASTPython{}} \\ \hline
  12612. \gray{\LifASTPython{}} \\ \hline
  12613. \gray{\LwhileASTPython} \\ \hline
  12614. \gray{\LtupASTPython} \\ \hline
  12615. \LfunASTPython \\
  12616. \begin{array}{rcl}
  12617. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12618. \end{array}
  12619. \end{array}
  12620. \]
  12621. \fi}
  12622. \end{tcolorbox}
  12623. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12624. \label{fig:Lfun-syntax}
  12625. \end{figure}
  12626. The program in Figure~\ref{fig:Lfun-function-example} is a
  12627. representative example of defining and using functions in \LangFun{}.
  12628. We define a function \code{map} that applies some other function
  12629. \code{f} to both elements of a tuple and returns a new tuple
  12630. containing the results. We also define a function \code{inc}. The
  12631. program applies \code{map} to \code{inc} and
  12632. %
  12633. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12634. %
  12635. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12636. %
  12637. from which we return \code{42}.
  12638. \begin{figure}[tbp]
  12639. \begin{tcolorbox}[colback=white]
  12640. {\if\edition\racketEd
  12641. \begin{lstlisting}
  12642. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12643. : (Vector Integer Integer)
  12644. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12645. (define (inc [x : Integer]) : Integer
  12646. (+ x 1))
  12647. (vector-ref (map inc (vector 0 41)) 1)
  12648. \end{lstlisting}
  12649. \fi}
  12650. {\if\edition\pythonEd
  12651. \begin{lstlisting}
  12652. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12653. return f(v[0]), f(v[1])
  12654. def inc(x : int) -> int:
  12655. return x + 1
  12656. print( map(inc, (0, 41))[1] )
  12657. \end{lstlisting}
  12658. \fi}
  12659. \end{tcolorbox}
  12660. \caption{Example of using functions in \LangFun{}.}
  12661. \label{fig:Lfun-function-example}
  12662. \end{figure}
  12663. The definitional interpreter for \LangFun{} is in
  12664. Figure~\ref{fig:interp-Lfun}. The case for the
  12665. %
  12666. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12667. %
  12668. AST is responsible for setting up the mutual recursion between the
  12669. top-level function definitions.
  12670. %
  12671. \racket{We use the classic back-patching
  12672. \index{subject}{back-patching} approach that uses mutable variables
  12673. and makes two passes over the function
  12674. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12675. top-level environment using a mutable cons cell for each function
  12676. definition. Note that the \code{lambda} value for each function is
  12677. incomplete; it does not yet include the environment. Once the
  12678. top-level environment is constructed, we then iterate over it and
  12679. update the \code{lambda} values to use the top-level environment.}
  12680. %
  12681. \python{We create a dictionary named \code{env} and fill it in
  12682. by mapping each function name to a new \code{Function} value,
  12683. each of which stores a reference to the \code{env}.
  12684. (We define the class \code{Function} for this purpose.)}
  12685. %
  12686. To interpret a function \racket{application}\python{call}, we match
  12687. the result of the function expression to obtain a function value. We
  12688. then extend the function's environment with the mapping of parameters to
  12689. argument values. Finally, we interpret the body of the function in
  12690. this extended environment.
  12691. \begin{figure}[tp]
  12692. \begin{tcolorbox}[colback=white]
  12693. {\if\edition\racketEd
  12694. \begin{lstlisting}
  12695. (define interp-Lfun-class
  12696. (class interp-Lvec-class
  12697. (super-new)
  12698. (define/override ((interp-exp env) e)
  12699. (define recur (interp-exp env))
  12700. (match e
  12701. [(Apply fun args)
  12702. (define fun-val (recur fun))
  12703. (define arg-vals (for/list ([e args]) (recur e)))
  12704. (match fun-val
  12705. [`(function (,xs ...) ,body ,fun-env)
  12706. (define params-args (for/list ([x xs] [arg arg-vals])
  12707. (cons x (box arg))))
  12708. (define new-env (append params-args fun-env))
  12709. ((interp-exp new-env) body)]
  12710. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12711. [else ((super interp-exp env) e)]
  12712. ))
  12713. (define/public (interp-def d)
  12714. (match d
  12715. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12716. (cons f (box `(function ,xs ,body ())))]))
  12717. (define/override (interp-program p)
  12718. (match p
  12719. [(ProgramDefsExp info ds body)
  12720. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12721. (for/list ([f (in-dict-values top-level)])
  12722. (set-box! f (match (unbox f)
  12723. [`(function ,xs ,body ())
  12724. `(function ,xs ,body ,top-level)])))
  12725. ((interp-exp top-level) body))]))
  12726. ))
  12727. (define (interp-Lfun p)
  12728. (send (new interp-Lfun-class) interp-program p))
  12729. \end{lstlisting}
  12730. \fi}
  12731. {\if\edition\pythonEd
  12732. \begin{lstlisting}
  12733. class InterpLfun(InterpLtup):
  12734. def apply_fun(self, fun, args, e):
  12735. match fun:
  12736. case Function(name, xs, body, env):
  12737. new_env = env.copy().update(zip(xs, args))
  12738. return self.interp_stmts(body, new_env)
  12739. case _:
  12740. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12741. def interp_exp(self, e, env):
  12742. match e:
  12743. case Call(Name('input_int'), []):
  12744. return super().interp_exp(e, env)
  12745. case Call(func, args):
  12746. f = self.interp_exp(func, env)
  12747. vs = [self.interp_exp(arg, env) for arg in args]
  12748. return self.apply_fun(f, vs, e)
  12749. case _:
  12750. return super().interp_exp(e, env)
  12751. def interp_stmts(self, ss, env):
  12752. if len(ss) == 0:
  12753. return
  12754. match ss[0]:
  12755. case Return(value):
  12756. return self.interp_exp(value, env)
  12757. case FunctionDef(name, params, bod, dl, returns, comment):
  12758. ps = [x for (x,t) in params]
  12759. env[name] = Function(name, ps, bod, env)
  12760. return self.interp_stmts(ss[1:], env)
  12761. case _:
  12762. return super().interp_stmts(ss, env)
  12763. def interp(self, p):
  12764. match p:
  12765. case Module(ss):
  12766. env = {}
  12767. self.interp_stmts(ss, env)
  12768. if 'main' in env.keys():
  12769. self.apply_fun(env['main'], [], None)
  12770. case _:
  12771. raise Exception('interp: unexpected ' + repr(p))
  12772. \end{lstlisting}
  12773. \fi}
  12774. \end{tcolorbox}
  12775. \caption{Interpreter for the \LangFun{} language.}
  12776. \label{fig:interp-Lfun}
  12777. \end{figure}
  12778. %\margincomment{TODO: explain type checker}
  12779. The type checker for \LangFun{} is in
  12780. Figure~\ref{fig:type-check-Lfun}.
  12781. %
  12782. \python{(We omit the code that parses function parameters into the
  12783. simpler abstract syntax.)}
  12784. %
  12785. Similar to the interpreter, the case for the
  12786. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12787. %
  12788. AST is responsible for setting up the mutual recursion between the
  12789. top-level function definitions. We begin by create a mapping
  12790. \code{env} from every function name to its type. We then type check
  12791. the program using this mapping.
  12792. %
  12793. In the case for function \racket{application}\python{call}, we match
  12794. the type of the function expression to a function type and check that
  12795. the types of the argument expressions are equal to the function's
  12796. parameter types. The type of the \racket{application}\python{call} as
  12797. a whole is the return type from the function type.
  12798. \begin{figure}[tp]
  12799. \begin{tcolorbox}[colback=white]
  12800. {\if\edition\racketEd
  12801. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12802. (define type-check-Lfun-class
  12803. (class type-check-Lvec-class
  12804. (super-new)
  12805. (inherit check-type-equal?)
  12806. (define/public (type-check-apply env e es)
  12807. (define-values (e^ ty) ((type-check-exp env) e))
  12808. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12809. ((type-check-exp env) e)))
  12810. (match ty
  12811. [`(,ty^* ... -> ,rt)
  12812. (for ([arg-ty ty*] [param-ty ty^*])
  12813. (check-type-equal? arg-ty param-ty (Apply e es)))
  12814. (values e^ e* rt)]))
  12815. (define/override (type-check-exp env)
  12816. (lambda (e)
  12817. (match e
  12818. [(FunRef f n)
  12819. (values (FunRef f n) (dict-ref env f))]
  12820. [(Apply e es)
  12821. (define-values (e^ es^ rt) (type-check-apply env e es))
  12822. (values (Apply e^ es^) rt)]
  12823. [(Call e es)
  12824. (define-values (e^ es^ rt) (type-check-apply env e es))
  12825. (values (Call e^ es^) rt)]
  12826. [else ((super type-check-exp env) e)])))
  12827. (define/public (type-check-def env)
  12828. (lambda (e)
  12829. (match e
  12830. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12831. (define new-env (append (map cons xs ps) env))
  12832. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12833. (check-type-equal? ty^ rt body)
  12834. (Def f p:t* rt info body^)])))
  12835. (define/public (fun-def-type d)
  12836. (match d
  12837. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12838. (define/override (type-check-program e)
  12839. (match e
  12840. [(ProgramDefsExp info ds body)
  12841. (define env (for/list ([d ds])
  12842. (cons (Def-name d) (fun-def-type d))))
  12843. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12844. (define-values (body^ ty) ((type-check-exp env) body))
  12845. (check-type-equal? ty 'Integer body)
  12846. (ProgramDefsExp info ds^ body^)]))))
  12847. (define (type-check-Lfun p)
  12848. (send (new type-check-Lfun-class) type-check-program p))
  12849. \end{lstlisting}
  12850. \fi}
  12851. {\if\edition\pythonEd
  12852. \begin{lstlisting}
  12853. class TypeCheckLfun(TypeCheckLtup):
  12854. def type_check_exp(self, e, env):
  12855. match e:
  12856. case Call(Name('input_int'), []):
  12857. return super().type_check_exp(e, env)
  12858. case Call(func, args):
  12859. func_t = self.type_check_exp(func, env)
  12860. args_t = [self.type_check_exp(arg, env) for arg in args]
  12861. match func_t:
  12862. case FunctionType(params_t, return_t):
  12863. for (arg_t, param_t) in zip(args_t, params_t):
  12864. check_type_equal(param_t, arg_t, e)
  12865. return return_t
  12866. case _:
  12867. raise Exception('type_check_exp: in call, unexpected ' +
  12868. repr(func_t))
  12869. case _:
  12870. return super().type_check_exp(e, env)
  12871. def type_check_stmts(self, ss, env):
  12872. if len(ss) == 0:
  12873. return
  12874. match ss[0]:
  12875. case FunctionDef(name, params, body, dl, returns, comment):
  12876. new_env = env.copy().update(params)
  12877. rt = self.type_check_stmts(body, new_env)
  12878. check_type_equal(returns, rt, ss[0])
  12879. return self.type_check_stmts(ss[1:], env)
  12880. case Return(value):
  12881. return self.type_check_exp(value, env)
  12882. case _:
  12883. return super().type_check_stmts(ss, env)
  12884. def type_check(self, p):
  12885. match p:
  12886. case Module(body):
  12887. env = {}
  12888. for s in body:
  12889. match s:
  12890. case FunctionDef(name, params, bod, dl, returns, comment):
  12891. if name in env:
  12892. raise Exception('type_check: function ' +
  12893. repr(name) + ' defined twice')
  12894. params_t = [t for (x,t) in params]
  12895. env[name] = FunctionType(params_t, returns)
  12896. self.type_check_stmts(body, env)
  12897. case _:
  12898. raise Exception('type_check: unexpected ' + repr(p))
  12899. \end{lstlisting}
  12900. \fi}
  12901. \end{tcolorbox}
  12902. \caption{Type checker for the \LangFun{} language.}
  12903. \label{fig:type-check-Lfun}
  12904. \end{figure}
  12905. \clearpage
  12906. \section{Functions in x86}
  12907. \label{sec:fun-x86}
  12908. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12909. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12910. %% \margincomment{\tiny Talk about the return address on the
  12911. %% stack and what callq and retq does.\\ --Jeremy }
  12912. The x86 architecture provides a few features to support the
  12913. implementation of functions. We have already seen that there are
  12914. labels in x86 so that one can refer to the location of an instruction,
  12915. as is needed for jump instructions. Labels can also be used to mark
  12916. the beginning of the instructions for a function. Going further, we
  12917. can obtain the address of a label by using the \key{leaq}
  12918. instruction. For example, the following puts the address of the
  12919. \code{inc} label into the \code{rbx} register.
  12920. \begin{lstlisting}
  12921. leaq inc(%rip), %rbx
  12922. \end{lstlisting}
  12923. Recall from Section~\ref{sec:select-instructions-gc} that
  12924. \verb!inc(%rip)! is an example of instruction-pointer relative
  12925. addressing.
  12926. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12927. to functions whose locations were given by a label, such as
  12928. \code{read\_int}. To support function calls in this chapter we instead
  12929. will be jumping to functions whose location are given by an address in
  12930. a register, that is, we shall use \emph{indirect function calls}. The
  12931. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12932. before the register name.\index{subject}{indirect function call}
  12933. \begin{lstlisting}
  12934. callq *%rbx
  12935. \end{lstlisting}
  12936. \subsection{Calling Conventions}
  12937. \label{sec:calling-conventions-fun}
  12938. \index{subject}{calling conventions}
  12939. The \code{callq} instruction provides partial support for implementing
  12940. functions: it pushes the return address on the stack and it jumps to
  12941. the target. However, \code{callq} does not handle
  12942. \begin{enumerate}
  12943. \item parameter passing,
  12944. \item pushing frames on the procedure call stack and popping them off,
  12945. or
  12946. \item determining how registers are shared by different functions.
  12947. \end{enumerate}
  12948. Regarding parameter passing, recall that the x86-64 calling
  12949. convention for Unix-based system uses the following six registers to
  12950. pass arguments to a function, in this order.
  12951. \begin{lstlisting}
  12952. rdi rsi rdx rcx r8 r9
  12953. \end{lstlisting}
  12954. If there are more than six arguments, then the calling convention
  12955. mandates using space on the frame of the caller for the rest of the
  12956. arguments. However, to ease the implementation of efficient tail calls
  12957. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12958. arguments.
  12959. %
  12960. The return value of the function is stored in register \code{rax}.
  12961. \index{subject}{prelude}\index{subject}{conclusion}
  12962. Regarding frames \index{subject}{frame} and the procedure call stack,
  12963. \index{subject}{procedure call stack} recall from
  12964. Section~\ref{sec:x86} that the stack grows down and each function call
  12965. uses a chunk of space on the stack called a frame. The caller sets the
  12966. stack pointer, register \code{rsp}, to the last data item in its
  12967. frame. The callee must not change anything in the caller's frame, that
  12968. is, anything that is at or above the stack pointer. The callee is free
  12969. to use locations that are below the stack pointer.
  12970. Recall that we store variables of tuple type on the root stack. So
  12971. the prelude of a function needs to move the root stack pointer
  12972. \code{r15} up according to the number of variables of tuple type and
  12973. the conclusion needs to move the root stack pointer back down. Also,
  12974. the prelude must initialize to \code{0} this frame's slots in the root
  12975. stack to signal to the garbage collector that those slots do not yet
  12976. contain a valid pointer. Otherwise the garbage collector will
  12977. interpret the garbage bits in those slots as memory addresses and try
  12978. to traverse them, causing serious mayhem!
  12979. Regarding the sharing of registers between different functions, recall
  12980. from Section~\ref{sec:calling-conventions} that the registers are
  12981. divided into two groups, the caller-saved registers and the
  12982. callee-saved registers. The caller should assume that all the
  12983. caller-saved registers get overwritten with arbitrary values by the
  12984. callee. For that reason we recommend in
  12985. Section~\ref{sec:calling-conventions} that variables that are live
  12986. during a function call should not be assigned to caller-saved
  12987. registers.
  12988. On the flip side, if the callee wants to use a callee-saved register,
  12989. the callee must save the contents of those registers on their stack
  12990. frame and then put them back prior to returning to the caller. For
  12991. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12992. the register allocator assigns a variable to a callee-saved register,
  12993. then the prelude of the \code{main} function must save that register
  12994. to the stack and the conclusion of \code{main} must restore it. This
  12995. recommendation now generalizes to all functions.
  12996. Recall that the base pointer, register \code{rbp}, is used as a
  12997. point-of-reference within a frame, so that each local variable can be
  12998. accessed at a fixed offset from the base pointer
  12999. (Section~\ref{sec:x86}).
  13000. %
  13001. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13002. and callee frames.
  13003. \begin{figure}[tbp]
  13004. \centering
  13005. \begin{tcolorbox}[colback=white]
  13006. \begin{tabular}{r|r|l|l} \hline
  13007. Caller View & Callee View & Contents & Frame \\ \hline
  13008. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13009. 0(\key{\%rbp}) & & old \key{rbp} \\
  13010. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13011. \ldots & & \ldots \\
  13012. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13013. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13014. \ldots & & \ldots \\
  13015. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13016. %% & & \\
  13017. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13018. %% & \ldots & \ldots \\
  13019. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13020. \hline
  13021. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13022. & 0(\key{\%rbp}) & old \key{rbp} \\
  13023. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13024. & \ldots & \ldots \\
  13025. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13026. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13027. & \ldots & \ldots \\
  13028. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13029. \end{tabular}
  13030. \end{tcolorbox}
  13031. \caption{Memory layout of caller and callee frames.}
  13032. \label{fig:call-frames}
  13033. \end{figure}
  13034. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  13035. %% local variables and for storing the values of callee-saved registers
  13036. %% (we shall refer to all of these collectively as ``locals''), and that
  13037. %% at the beginning of a function we move the stack pointer \code{rsp}
  13038. %% down to make room for them.
  13039. %% We recommend storing the local variables
  13040. %% first and then the callee-saved registers, so that the local variables
  13041. %% can be accessed using \code{rbp} the same as before the addition of
  13042. %% functions.
  13043. %% To make additional room for passing arguments, we shall
  13044. %% move the stack pointer even further down. We count how many stack
  13045. %% arguments are needed for each function call that occurs inside the
  13046. %% body of the function and find their maximum. Adding this number to the
  13047. %% number of locals gives us how much the \code{rsp} should be moved at
  13048. %% the beginning of the function. In preparation for a function call, we
  13049. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13050. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13051. %% so on.
  13052. %% Upon calling the function, the stack arguments are retrieved by the
  13053. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13054. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13055. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13056. %% the layout of the caller and callee frames. Notice how important it is
  13057. %% that we correctly compute the maximum number of arguments needed for
  13058. %% function calls; if that number is too small then the arguments and
  13059. %% local variables will smash into each other!
  13060. \subsection{Efficient Tail Calls}
  13061. \label{sec:tail-call}
  13062. In general, the amount of stack space used by a program is determined
  13063. by the longest chain of nested function calls. That is, if function
  13064. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13065. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13066. large if functions are recursive. However, in some cases we can
  13067. arrange to use only a constant amount of space for a long chain of
  13068. nested function calls.
  13069. A \emph{tail call}\index{subject}{tail call} is a function call that
  13070. happens as the last action in a function body.
  13071. For example, in the following
  13072. program, the recursive call to \code{tail\_sum} is a tail call.
  13073. \begin{center}
  13074. {\if\edition\racketEd
  13075. \begin{lstlisting}
  13076. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13077. (if (eq? n 0)
  13078. r
  13079. (tail_sum (- n 1) (+ n r))))
  13080. (+ (tail_sum 3 0) 36)
  13081. \end{lstlisting}
  13082. \fi}
  13083. {\if\edition\pythonEd
  13084. \begin{lstlisting}
  13085. def tail_sum(n : int, r : int) -> int:
  13086. if n == 0:
  13087. return r
  13088. else:
  13089. return tail_sum(n - 1, n + r)
  13090. print( tail_sum(3, 0) + 36)
  13091. \end{lstlisting}
  13092. \fi}
  13093. \end{center}
  13094. At a tail call, the frame of the caller is no longer needed, so we can
  13095. pop the caller's frame before making the tail call. With this
  13096. approach, a recursive function that only makes tail calls ends up
  13097. using a constant amount of stack space. Functional languages like
  13098. Racket rely heavily on recursive functions, so the definition of
  13099. Racket \emph{requires} that all tail calls be optimized in this way.
  13100. \index{subject}{frame}
  13101. Some care is needed with regards to argument passing in tail calls.
  13102. As mentioned above, for arguments beyond the sixth, the convention is
  13103. to use space in the caller's frame for passing arguments. But for a
  13104. tail call we pop the caller's frame and can no longer use it. An
  13105. alternative is to use space in the callee's frame for passing
  13106. arguments. However, this option is also problematic because the caller
  13107. and callee's frames overlap in memory. As we begin to copy the
  13108. arguments from their sources in the caller's frame, the target
  13109. locations in the callee's frame might collide with the sources for
  13110. later arguments! We solve this problem by using the heap instead of
  13111. the stack for passing more than six arguments
  13112. (Section~\ref{sec:limit-functions-r4}).
  13113. As mentioned above, for a tail call we pop the caller's frame prior to
  13114. making the tail call. The instructions for popping a frame are the
  13115. instructions that we usually place in the conclusion of a
  13116. function. Thus, we also need to place such code immediately before
  13117. each tail call. These instructions include restoring the callee-saved
  13118. registers, so it is fortunate that the argument passing registers are
  13119. all caller-saved registers!
  13120. One last note regarding which instruction to use to make the tail
  13121. call. When the callee is finished, it should not return to the current
  13122. function, but it should return to the function that called the current
  13123. one. Thus, the return address that is already on the stack is the
  13124. right one and we should not use \key{callq} to make the tail call, as
  13125. that would overwrite the return address. Instead we simply use the
  13126. \key{jmp} instruction. Like the indirect function call, we write an
  13127. \emph{indirect jump}\index{subject}{indirect jump} with a register
  13128. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13129. jump target because the conclusion can overwrite just about everything
  13130. else.
  13131. \begin{lstlisting}
  13132. jmp *%rax
  13133. \end{lstlisting}
  13134. \section{Shrink \LangFun{}}
  13135. \label{sec:shrink-r4}
  13136. The \code{shrink} pass performs a minor modification to ease the
  13137. later passes. This pass introduces an explicit \code{main} function
  13138. that gobbles up all the top-level statements of the module.
  13139. %
  13140. \racket{It also changes the top \code{ProgramDefsExp} form to
  13141. \code{ProgramDefs}.}
  13142. {\if\edition\racketEd
  13143. \begin{lstlisting}
  13144. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13145. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13146. \end{lstlisting}
  13147. where $\itm{mainDef}$ is
  13148. \begin{lstlisting}
  13149. (Def 'main '() 'Integer '() |$\Exp'$|)
  13150. \end{lstlisting}
  13151. \fi}
  13152. {\if\edition\pythonEd
  13153. \begin{lstlisting}
  13154. Module(|$\Def\ldots\Stmt\ldots$|)
  13155. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13156. \end{lstlisting}
  13157. where $\itm{mainDef}$ is
  13158. \begin{lstlisting}
  13159. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13160. \end{lstlisting}
  13161. \fi}
  13162. \section{Reveal Functions and the \LangFunRef{} language}
  13163. \label{sec:reveal-functions-r4}
  13164. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13165. in that it conflates the use of function names and local
  13166. variables. This is a problem because we need to compile the use of a
  13167. function name differently than the use of a local variable. In
  13168. particular, we use \code{leaq} to convert the function name (a label
  13169. in x86) to an address in a register. Thus, we create a new pass that
  13170. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13171. $n$ is the arity of the function.\python{\footnote{The arity is not
  13172. needed in this chapter but is used in Chapter~\ref{ch:Ldyn}.}}
  13173. This pass is named \code{reveal\_functions} and the output language
  13174. is \LangFunRef{}.
  13175. %is defined in Figure~\ref{fig:f1-syntax}.
  13176. %% The concrete syntax for a
  13177. %% function reference is $\CFUNREF{f}$.
  13178. %% \begin{figure}[tp]
  13179. %% \centering
  13180. %% \fbox{
  13181. %% \begin{minipage}{0.96\textwidth}
  13182. %% {\if\edition\racketEd
  13183. %% \[
  13184. %% \begin{array}{lcl}
  13185. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13186. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13187. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13188. %% \end{array}
  13189. %% \]
  13190. %% \fi}
  13191. %% {\if\edition\pythonEd
  13192. %% \[
  13193. %% \begin{array}{lcl}
  13194. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13195. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13196. %% \end{array}
  13197. %% \]
  13198. %% \fi}
  13199. %% \end{minipage}
  13200. %% }
  13201. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13202. %% (Figure~\ref{fig:Lfun-syntax}).}
  13203. %% \label{fig:f1-syntax}
  13204. %% \end{figure}
  13205. %% Distinguishing between calls in tail position and non-tail position
  13206. %% requires the pass to have some notion of context. We recommend using
  13207. %% two mutually recursive functions, one for processing expressions in
  13208. %% tail position and another for the rest.
  13209. \racket{Placing this pass after \code{uniquify} will make sure that
  13210. there are no local variables and functions that share the same
  13211. name.}
  13212. %
  13213. The \code{reveal\_functions} pass should come before the
  13214. \code{remove\_complex\_operands} pass because function references
  13215. should be categorized as complex expressions.
  13216. \section{Limit Functions}
  13217. \label{sec:limit-functions-r4}
  13218. Recall that we wish to limit the number of function parameters to six
  13219. so that we do not need to use the stack for argument passing, which
  13220. makes it easier to implement efficient tail calls. However, because
  13221. the input language \LangFun{} supports arbitrary numbers of function
  13222. arguments, we have some work to do! The \code{limit\_functions} pass
  13223. transforms functions and function calls that involve more than six
  13224. arguments to pass the first five arguments as usual, but it packs the
  13225. rest of the arguments into a tuple and passes it as the sixth
  13226. argument.\footnote{The implementation this pass can be postponed to
  13227. last because you can test the rest of the passes on functions with
  13228. six or fewer parameters.}
  13229. Each function definition with seven or more parameters is transformed as
  13230. follows.
  13231. {\if\edition\racketEd
  13232. \begin{lstlisting}
  13233. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13234. |$\Rightarrow$|
  13235. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13236. \end{lstlisting}
  13237. \fi}
  13238. {\if\edition\pythonEd
  13239. \begin{lstlisting}
  13240. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13241. |$\Rightarrow$|
  13242. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13243. |$T_r$|, None, |$\itm{body}'$|, None)
  13244. \end{lstlisting}
  13245. \fi}
  13246. %
  13247. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13248. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13249. the $k$th element of the tuple, where $k = i - 6$.
  13250. %
  13251. {\if\edition\racketEd
  13252. \begin{lstlisting}
  13253. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13254. \end{lstlisting}
  13255. \fi}
  13256. {\if\edition\pythonEd
  13257. \begin{lstlisting}
  13258. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13259. \end{lstlisting}
  13260. \fi}
  13261. For function calls with too many arguments, the \code{limit\_functions}
  13262. pass transforms them in the following way.
  13263. \begin{tabular}{lll}
  13264. \begin{minipage}{0.3\textwidth}
  13265. {\if\edition\racketEd
  13266. \begin{lstlisting}
  13267. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13268. \end{lstlisting}
  13269. \fi}
  13270. {\if\edition\pythonEd
  13271. \begin{lstlisting}
  13272. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13273. \end{lstlisting}
  13274. \fi}
  13275. \end{minipage}
  13276. &
  13277. $\Rightarrow$
  13278. &
  13279. \begin{minipage}{0.5\textwidth}
  13280. {\if\edition\racketEd
  13281. \begin{lstlisting}
  13282. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13283. \end{lstlisting}
  13284. \fi}
  13285. {\if\edition\pythonEd
  13286. \begin{lstlisting}
  13287. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13288. \end{lstlisting}
  13289. \fi}
  13290. \end{minipage}
  13291. \end{tabular}
  13292. \section{Remove Complex Operands}
  13293. \label{sec:rco-r4}
  13294. The primary decisions to make for this pass are whether to classify
  13295. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13296. atomic or complex expressions. Recall that an atomic expression will
  13297. end up as an immediate argument of an x86 instruction. Function
  13298. application will be translated to a sequence of instructions, so
  13299. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13300. complex expression. On the other hand, the arguments of
  13301. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13302. expressions.
  13303. %
  13304. Regarding \code{FunRef}, as discussed above, the function label needs
  13305. to be converted to an address using the \code{leaq} instruction. Thus,
  13306. even though \code{FunRef} seems rather simple, it needs to be
  13307. classified as a complex expression so that we generate an assignment
  13308. statement with a left-hand side that can serve as the target of the
  13309. \code{leaq}.
  13310. The output of this pass, \LangFunANF{} (Figure~\ref{fig:Lfun-anf-syntax}),
  13311. extends \LangAllocANF{} (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13312. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13313. and augments programs to include a list of function definitions.
  13314. %
  13315. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13316. \newcommand{\LfunMonadASTRacket}{
  13317. \begin{array}{lcl}
  13318. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13319. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13320. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13321. \end{array}
  13322. }
  13323. \newcommand{\LfunMonadASTPython}{
  13324. \begin{array}{lcl}
  13325. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13326. \MID \key{TupleType}\LS\Type^+\RS\\
  13327. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13328. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13329. \Stmt &::=& \RETURN{\Exp} \\
  13330. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13331. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13332. \end{array}
  13333. }
  13334. \begin{figure}[tp]
  13335. \centering
  13336. \begin{tcolorbox}[colback=white]
  13337. \small
  13338. {\if\edition\racketEd
  13339. \[
  13340. \begin{array}{l}
  13341. \gray{\LvarMonadASTRacket} \\ \hline
  13342. \gray{\LifMonadASTRacket} \\ \hline
  13343. \gray{\LwhileMonadASTRacket} \\ \hline
  13344. \gray{\LtupMonadASTRacket} \\ \hline
  13345. \LfunMonadASTRacket \\
  13346. \begin{array}{rcl}
  13347. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13348. \end{array}
  13349. \end{array}
  13350. \]
  13351. \fi}
  13352. {\if\edition\pythonEd
  13353. \[
  13354. \begin{array}{l}
  13355. \gray{\LvarMonadASTPython} \\ \hline
  13356. \gray{\LifMonadASTPython} \\ \hline
  13357. \gray{\LwhileMonadASTPython} \\ \hline
  13358. \gray{\LtupMonadASTPython} \\ \hline
  13359. \LfunMonadASTPython \\
  13360. \begin{array}{rcl}
  13361. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13362. \end{array}
  13363. \end{array}
  13364. \]
  13365. \fi}
  13366. \end{tcolorbox}
  13367. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13368. \label{fig:Lfun-anf-syntax}
  13369. \end{figure}
  13370. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13371. %% \LangFunANF{} of this pass.
  13372. %% \begin{figure}[tp]
  13373. %% \centering
  13374. %% \fbox{
  13375. %% \begin{minipage}{0.96\textwidth}
  13376. %% \small
  13377. %% \[
  13378. %% \begin{array}{rcl}
  13379. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13380. %% \MID \VOID{} } \\
  13381. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13382. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13383. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13384. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13385. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13386. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13387. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13388. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13389. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13390. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13391. %% \end{array}
  13392. %% \]
  13393. %% \end{minipage}
  13394. %% }
  13395. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13396. %% \label{fig:Lfun-anf-syntax}
  13397. %% \end{figure}
  13398. \section{Explicate Control and the \LangCFun{} language}
  13399. \label{sec:explicate-control-r4}
  13400. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13401. output of \code{explicate\_control}.
  13402. %
  13403. %% \racket{(The concrete syntax is given in
  13404. %% Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13405. %
  13406. The auxiliary functions for assignment\racket{ and tail contexts} should
  13407. be updated with cases for
  13408. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13409. function for predicate context should be updated for
  13410. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13411. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13412. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13413. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13414. auxiliary function for processing function definitions. This code is
  13415. similar to the case for \code{Program} in \LangVec{}. The top-level
  13416. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13417. form of \LangFun{} can then apply this new function to all the
  13418. function definitions.
  13419. {\if\edition\pythonEd
  13420. The translation of \code{Return} statements requires a new auxiliary
  13421. function to handle expressions in tail context, called
  13422. \code{explicate\_tail}. The function should take an expression and the
  13423. dictionary of basic blocks and produce a list of statements in the
  13424. \LangCFun{} language. The \code{explicate\_tail} function should
  13425. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13426. and a default case for other kinds of expressions. The default case
  13427. should produce a \code{Return} statement. The case for \code{Call}
  13428. should change it into \code{TailCall}. The other cases should
  13429. recursively process their subexpressions and statements, choosing the
  13430. appropriate explicate functions for the various contexts.
  13431. \fi}
  13432. \newcommand{\CfunASTRacket}{
  13433. \begin{array}{lcl}
  13434. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13435. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13436. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13437. \end{array}
  13438. }
  13439. \newcommand{\CfunASTPython}{
  13440. \begin{array}{lcl}
  13441. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13442. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13443. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13444. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13445. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13446. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13447. \end{array}
  13448. }
  13449. \begin{figure}[tp]
  13450. \begin{tcolorbox}[colback=white]
  13451. \small
  13452. {\if\edition\racketEd
  13453. \[
  13454. \begin{array}{l}
  13455. \gray{\CvarASTRacket} \\ \hline
  13456. \gray{\CifASTRacket} \\ \hline
  13457. \gray{\CloopASTRacket} \\ \hline
  13458. \gray{\CtupASTRacket} \\ \hline
  13459. \CfunASTRacket \\
  13460. \begin{array}{lcl}
  13461. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13462. \end{array}
  13463. \end{array}
  13464. \]
  13465. \fi}
  13466. {\if\edition\pythonEd
  13467. \[
  13468. \begin{array}{l}
  13469. \gray{\CifASTPython} \\ \hline
  13470. \gray{\CtupASTPython} \\ \hline
  13471. \CfunASTPython \\
  13472. \begin{array}{lcl}
  13473. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13474. \end{array}
  13475. \end{array}
  13476. \]
  13477. \fi}
  13478. \end{tcolorbox}
  13479. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13480. \label{fig:c3-syntax}
  13481. \end{figure}
  13482. \clearpage
  13483. \section{Select Instructions and the \LangXIndCall{} Language}
  13484. \label{sec:select-r4}
  13485. \index{subject}{instruction selection}
  13486. The output of select instructions is a program in the \LangXIndCall{}
  13487. language, whose concrete syntax is defined in
  13488. Figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13489. Figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13490. labels of function definitions to make sure the bottom three bits are
  13491. zero, which we make use of in Chapter~\ref{ch:Ldyn}. We discuss the
  13492. new instructions as needed in this section. \index{subject}{x86}
  13493. \newcommand{\GrammarXIndCall}{
  13494. \begin{array}{lcl}
  13495. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13496. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13497. \Block &::= & \Instr^{+} \\
  13498. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13499. \end{array}
  13500. }
  13501. \newcommand{\ASTXIndCallRacket}{
  13502. \begin{array}{lcl}
  13503. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13504. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13505. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13506. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13507. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13508. \end{array}
  13509. }
  13510. \begin{figure}[tp]
  13511. \begin{tcolorbox}[colback=white]
  13512. \small
  13513. \[
  13514. \begin{array}{l}
  13515. \gray{\GrammarXInt} \\ \hline
  13516. \gray{\GrammarXIf} \\ \hline
  13517. \gray{\GrammarXGlobal} \\ \hline
  13518. \GrammarXIndCall \\
  13519. \begin{array}{lcl}
  13520. \LangXIndCallM{} &::= & \Def^{*}
  13521. \end{array}
  13522. \end{array}
  13523. \]
  13524. \end{tcolorbox}
  13525. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13526. \label{fig:x86-3-concrete}
  13527. \end{figure}
  13528. \begin{figure}[tp]
  13529. \begin{tcolorbox}[colback=white]
  13530. \small
  13531. {\if\edition\racketEd
  13532. \[\arraycolsep=3pt
  13533. \begin{array}{l}
  13534. \gray{\ASTXIntRacket} \\ \hline
  13535. \gray{\ASTXIfRacket} \\ \hline
  13536. \gray{\ASTXGlobalRacket} \\ \hline
  13537. \ASTXIndCallRacket \\
  13538. \begin{array}{lcl}
  13539. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13540. \end{array}
  13541. \end{array}
  13542. \]
  13543. \fi}
  13544. {\if\edition\pythonEd
  13545. \[
  13546. \begin{array}{lcl}
  13547. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13548. \MID \BYTEREG{\Reg} } \\
  13549. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13550. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13551. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13552. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13553. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13554. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13555. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13556. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13557. \end{array}
  13558. \]
  13559. \fi}
  13560. \end{tcolorbox}
  13561. \caption{The abstract syntax of \LangXIndCall{} (extends
  13562. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13563. \label{fig:x86-3}
  13564. \end{figure}
  13565. An assignment of a function reference to a variable becomes a
  13566. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13567. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13568. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13569. node, whose concrete syntax is instruction-pointer relative
  13570. addressing.
  13571. \begin{center}
  13572. \begin{tabular}{lcl}
  13573. \begin{minipage}{0.35\textwidth}
  13574. {\if\edition\racketEd
  13575. \begin{lstlisting}
  13576. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13577. \end{lstlisting}
  13578. \fi}
  13579. {\if\edition\pythonEd
  13580. \begin{lstlisting}
  13581. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13582. \end{lstlisting}
  13583. \fi}
  13584. \end{minipage}
  13585. &
  13586. $\Rightarrow$\qquad\qquad
  13587. &
  13588. \begin{minipage}{0.3\textwidth}
  13589. \begin{lstlisting}
  13590. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13591. \end{lstlisting}
  13592. \end{minipage}
  13593. \end{tabular}
  13594. \end{center}
  13595. Regarding function definitions, we need to remove the parameters and
  13596. instead perform parameter passing using the conventions discussed in
  13597. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13598. registers. We recommend turning the parameters into local variables
  13599. and generating instructions at the beginning of the function to move
  13600. from the argument passing registers
  13601. (Section~\ref{sec:calling-conventions-fun}) to these local variables.
  13602. {\if\edition\racketEd
  13603. \begin{lstlisting}
  13604. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13605. |$\Rightarrow$|
  13606. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13607. \end{lstlisting}
  13608. \fi}
  13609. {\if\edition\pythonEd
  13610. \begin{lstlisting}
  13611. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13612. |$\Rightarrow$|
  13613. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13614. \end{lstlisting}
  13615. \fi}
  13616. The basic blocks $B'$ are the same as $B$ except that the
  13617. \code{start} block is modified to add the instructions for moving from
  13618. the argument registers to the parameter variables. So the \code{start}
  13619. block of $B$ shown on the left is changed to the code on the right.
  13620. \begin{center}
  13621. \begin{minipage}{0.3\textwidth}
  13622. \begin{lstlisting}
  13623. start:
  13624. |$\itm{instr}_1$|
  13625. |$\cdots$|
  13626. |$\itm{instr}_n$|
  13627. \end{lstlisting}
  13628. \end{minipage}
  13629. $\Rightarrow$
  13630. \begin{minipage}{0.3\textwidth}
  13631. \begin{lstlisting}
  13632. |$f$|start:
  13633. movq %rdi, |$x_1$|
  13634. movq %rsi, |$x_2$|
  13635. |$\cdots$|
  13636. |$\itm{instr}_1$|
  13637. |$\cdots$|
  13638. |$\itm{instr}_n$|
  13639. \end{lstlisting}
  13640. \end{minipage}
  13641. \end{center}
  13642. Recall that we use the label \code{start} for the initial block of a
  13643. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13644. the conclusion of the program with \code{conclusion}, so that
  13645. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13646. by a jump to \code{conclusion}. With the addition of function
  13647. definitions, there is a start block and conclusion for each function,
  13648. but their labels need to be unique. We recommend prepending the
  13649. function's name to \code{start} and \code{conclusion}, respectively,
  13650. to obtain unique labels.
  13651. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13652. parameters the function expects, but the parameters are no longer in
  13653. the syntax of function definitions. Instead, add an entry to
  13654. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13655. to construct $\itm{info}'$.}
  13656. By changing the parameters to local variables, we are giving the
  13657. register allocator control over which registers or stack locations to
  13658. use for them. If you implemented the move-biasing challenge
  13659. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13660. assign the parameter variables to the corresponding argument register,
  13661. in which case the \code{patch\_instructions} pass will remove the
  13662. \code{movq} instruction. This happens in the example translation in
  13663. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13664. the \code{add} function.
  13665. %
  13666. Also, note that the register allocator will perform liveness analysis
  13667. on this sequence of move instructions and build the interference
  13668. graph. So, for example, $x_1$ will be marked as interfering with
  13669. \code{rsi} and that will prevent the assignment of $x_1$ to
  13670. \code{rsi}, which is good, because that would overwrite the argument
  13671. that needs to move into $x_2$.
  13672. Next, consider the compilation of function calls. In the mirror image
  13673. of the handling of parameters in function definitions, the arguments
  13674. are moved to the argument passing registers. Note that the function
  13675. is not given as a label, but its address is produced by the argument
  13676. $\itm{arg}_0$. So we translate the call into an indirect function
  13677. call. The return value from the function is stored in \code{rax}, so
  13678. it needs to be moved into the \itm{lhs}.
  13679. \begin{lstlisting}
  13680. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13681. |$\Rightarrow$|
  13682. movq |$\itm{arg}_1$|, %rdi
  13683. movq |$\itm{arg}_2$|, %rsi
  13684. |$\vdots$|
  13685. callq *|$\itm{arg}_0$|
  13686. movq %rax, |$\itm{lhs}$|
  13687. \end{lstlisting}
  13688. The \code{IndirectCallq} AST node includes an integer for the arity of
  13689. the function, i.e., the number of parameters. That information is
  13690. useful in the \code{uncover\_live} pass for determining which
  13691. argument-passing registers are potentially read during the call.
  13692. For tail calls, the parameter passing is the same as non-tail calls:
  13693. generate instructions to move the arguments into the argument
  13694. passing registers. After that we need to pop the frame from the
  13695. procedure call stack. However, we do not yet know how big the frame
  13696. is; that gets determined during register allocation. So instead of
  13697. generating those instructions here, we invent a new instruction that
  13698. means ``pop the frame and then do an indirect jump'', which we name
  13699. \code{TailJmp}. The abstract syntax for this instruction includes an
  13700. argument that specifies where to jump and an integer that represents
  13701. the arity of the function being called.
  13702. \section{Register Allocation}
  13703. \label{sec:register-allocation-r4}
  13704. The addition of functions requires some changes to all three aspects
  13705. of register allocation, which we discuss in the following subsections.
  13706. \subsection{Liveness Analysis}
  13707. \label{sec:liveness-analysis-r4}
  13708. \index{subject}{liveness analysis}
  13709. %% The rest of the passes need only minor modifications to handle the new
  13710. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13711. %% \code{leaq}.
  13712. The \code{IndirectCallq} instruction should be treated like
  13713. \code{Callq} regarding its written locations $W$, in that they should
  13714. include all the caller-saved registers. Recall that the reason for
  13715. that is to force variables that are live across a function call to be assigned to callee-saved
  13716. registers or to be spilled to the stack.
  13717. Regarding the set of read locations $R$, the arity field of
  13718. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13719. argument-passing registers should be considered as read by those
  13720. instructions. Also, the target field of \code{TailJmp} and
  13721. \code{IndirectCallq} should be included in the set of read locations
  13722. $R$.
  13723. \subsection{Build Interference Graph}
  13724. \label{sec:build-interference-r4}
  13725. With the addition of function definitions, we compute a separate interference
  13726. graph for each function (not just one for the whole program).
  13727. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13728. spill tuple-typed variables that are live during a call to
  13729. \code{collect}, the garbage collector. With the addition of functions
  13730. to our language, we need to revisit this issue. Functions that perform
  13731. allocation contain calls to the collector. Thus, we should not only
  13732. spill a tuple-typed variable when it is live during a call to
  13733. \code{collect}, but we should spill the variable if it is live during
  13734. call to any user-defined function. Thus, in the
  13735. \code{build\_interference} pass, we recommend adding interference
  13736. edges between call-live tuple-typed variables and the callee-saved
  13737. registers (in addition to the usual addition of edges between
  13738. call-live variables and the caller-saved registers).
  13739. \subsection{Allocate Registers}
  13740. The primary change to the \code{allocate\_registers} pass is adding an
  13741. auxiliary function for handling definitions (the \Def{} non-terminal
  13742. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13743. logic is the same as described in
  13744. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13745. allocation is performed many times, once for each function definition,
  13746. instead of just once for the whole program.
  13747. \section{Patch Instructions}
  13748. In \code{patch\_instructions}, you should deal with the x86
  13749. idiosyncrasy that the destination argument of \code{leaq} must be a
  13750. register. Additionally, you should ensure that the argument of
  13751. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13752. trample many other registers before the tail call (as explained in the
  13753. next section).
  13754. \section{Prelude and Conclusion}
  13755. Now that register allocation is complete, we can translate the
  13756. \code{TailJmp} into a sequence of instructions. A naive translation of
  13757. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13758. before the jump we need to pop the current frame to achieve efficient
  13759. tail calls. This sequence of instructions is the same as the code for
  13760. the conclusion of a function, except the \code{retq} is replaced with
  13761. \code{jmp *$\itm{arg}$}.
  13762. Regarding function definitions, we generate a prelude and conclusion
  13763. for each one. This code is similar to the prelude and conclusion
  13764. generated for the \code{main} function in Chapter~\ref{ch:Lvec}. To
  13765. review, the prelude of every function should carry out the following
  13766. steps.
  13767. % TODO: .align the functions!
  13768. \begin{enumerate}
  13769. %% \item Start with \code{.global} and \code{.align} directives followed
  13770. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13771. %% example.)
  13772. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13773. pointer.
  13774. \item Push to the stack all of the callee-saved registers that were
  13775. used for register allocation.
  13776. \item Move the stack pointer \code{rsp} down to make room for the
  13777. regular spills. (Aligned to 16 bytes.)
  13778. \item Move the root stack pointer \code{r15} up by the size of the
  13779. root-stack frame for this function, which depends on the number of
  13780. spilled tuple-typed variables. \label{root-stack-init}
  13781. \item Initialize to zero all new entries in the root-stack frame.
  13782. \item Jump to the start block.
  13783. \end{enumerate}
  13784. The prelude of the \code{main} function has an additional task: call
  13785. the \code{initialize} function to set up the garbage collector and
  13786. then move the value of the global \code{rootstack\_begin} in
  13787. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13788. above, which depends on \code{r15}.
  13789. The conclusion of every function should do the following.
  13790. \begin{enumerate}
  13791. \item Move the stack pointer back up past the regular spills.
  13792. \item Restore the callee-saved registers by popping them from the
  13793. stack.
  13794. \item Move the root stack pointer back down by the size of the
  13795. root-stack frame for this function.
  13796. \item Restore \code{rbp} by popping it from the stack.
  13797. \item Return to the caller with the \code{retq} instruction.
  13798. \end{enumerate}
  13799. The output of this pass is \LangXIndCallFlat{}, which differs from
  13800. \LangXIndCall{} in that there is no longer an AST node for function
  13801. definitions. Instead, a program is just an association list of basic
  13802. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  13803. \[
  13804. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  13805. \]
  13806. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13807. compiling \LangFun{} to x86.
  13808. \begin{exercise}\normalfont\normalsize
  13809. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13810. Create 8 new programs that use functions, including examples that pass
  13811. functions and return functions from other functions, recursive
  13812. functions, functions that create vectors, and functions that make tail
  13813. calls. Test your compiler on these new programs and all of your
  13814. previously created test programs.
  13815. \end{exercise}
  13816. \begin{figure}[tbp]
  13817. \begin{tcolorbox}[colback=white]
  13818. {\if\edition\racketEd
  13819. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13820. \node (Lfun) at (0,2) {\large \LangFun{}};
  13821. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13822. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13823. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13824. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13825. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13826. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13827. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13828. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13829. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13830. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13831. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13832. \node (x86-5) at (9,-6) {\large \LangXIndCallFlat{}};
  13833. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13834. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13835. \path[->,bend left=15] (Lfun) edge [above] node
  13836. {\ttfamily\footnotesize shrink} (Lfun-1);
  13837. \path[->,bend left=15] (Lfun-1) edge [above] node
  13838. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13839. \path[->,bend left=15] (Lfun-2) edge [above] node
  13840. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13841. \path[->,bend left=15] (F1-1) edge [left] node
  13842. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13843. \path[->,bend left=15] (F1-2) edge [below] node
  13844. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13845. \path[->,bend left=15] (F1-3) edge [below] node
  13846. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13847. \path[->,bend right=15] (F1-4) edge [above] node
  13848. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13849. \path[->,bend right=15] (F1-5) edge [left] node
  13850. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13851. \path[->,bend right=15] (C3-2) edge [left] node
  13852. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13853. \path[->,bend left=15] (x86-2) edge [left] node
  13854. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13855. \path[->,bend right=15] (x86-2-1) edge [below] node
  13856. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13857. \path[->,bend right=15] (x86-2-2) edge [left] node
  13858. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13859. \path[->,bend left=15] (x86-3) edge [above] node
  13860. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13861. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13862. \end{tikzpicture}
  13863. \fi}
  13864. {\if\edition\pythonEd
  13865. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13866. \node (Lfun) at (0,2) {\large \LangFun{}};
  13867. \node (Lfun-2) at (3,2) {\large \LangFun{}};
  13868. \node (F1-1) at (6,2) {\large \LangFunRef{}};
  13869. \node (F1-2) at (9,2) {\large \LangFunRef{}};
  13870. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13871. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13872. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  13873. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  13874. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  13875. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  13876. \node (x86-5) at (6,-6) {\large \LangXIndCallFlat{}};
  13877. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  13878. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  13879. \path[->,bend left=15] (Lfun) edge [above] node
  13880. {\ttfamily\footnotesize shrink} (Lfun-2);
  13881. \path[->,bend left=15] (Lfun-2) edge [above] node
  13882. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13883. \path[->,bend left=15] (F1-1) edge [above] node
  13884. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13885. \path[->,bend left=15] (F1-2) edge [right] node
  13886. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  13887. \path[->,bend right=15] (F1-4) edge [above] node
  13888. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13889. \path[->,bend right=15] (F1-5) edge [right] node
  13890. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13891. \path[->,bend left=15] (C3-2) edge [right] node
  13892. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13893. \path[->,bend right=15] (x86-2) edge [right] node
  13894. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13895. \path[->,bend right=15] (x86-2-1) edge [below] node
  13896. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13897. \path[->,bend right=15] (x86-2-2) edge [right] node
  13898. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13899. \path[->,bend left=15] (x86-3) edge [above] node
  13900. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13901. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude.} (x86-5);
  13902. \end{tikzpicture}
  13903. \fi}
  13904. \end{tcolorbox}
  13905. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13906. \label{fig:Lfun-passes}
  13907. \end{figure}
  13908. \section{An Example Translation}
  13909. \label{sec:functions-example}
  13910. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13911. function in \LangFun{} to x86. The figure also includes the results of the
  13912. \code{explicate\_control} and \code{select\_instructions} passes.
  13913. \begin{figure}[htbp]
  13914. \begin{tcolorbox}[colback=white]
  13915. \begin{tabular}{ll}
  13916. \begin{minipage}{0.4\textwidth}
  13917. % s3_2.rkt
  13918. {\if\edition\racketEd
  13919. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13920. (define (add [x : Integer]
  13921. [y : Integer])
  13922. : Integer
  13923. (+ x y))
  13924. (add 40 2)
  13925. \end{lstlisting}
  13926. \fi}
  13927. {\if\edition\pythonEd
  13928. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13929. def add(x:int, y:int) -> int:
  13930. return x + y
  13931. print(add(40, 2))
  13932. \end{lstlisting}
  13933. \fi}
  13934. $\Downarrow$
  13935. {\if\edition\racketEd
  13936. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13937. (define (add86 [x87 : Integer]
  13938. [y88 : Integer])
  13939. : Integer
  13940. add86start:
  13941. return (+ x87 y88);
  13942. )
  13943. (define (main) : Integer ()
  13944. mainstart:
  13945. tmp89 = (fun-ref add86 2);
  13946. (tail-call tmp89 40 2)
  13947. )
  13948. \end{lstlisting}
  13949. \fi}
  13950. {\if\edition\pythonEd
  13951. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13952. def add(x:int, y:int) -> int:
  13953. addstart:
  13954. return x + y
  13955. def main() -> int:
  13956. mainstart:
  13957. fun.0 = add
  13958. tmp.1 = fun.0(40, 2)
  13959. print(tmp.1)
  13960. return 0
  13961. \end{lstlisting}
  13962. \fi}
  13963. \end{minipage}
  13964. &
  13965. $\Rightarrow$
  13966. \begin{minipage}{0.5\textwidth}
  13967. {\if\edition\racketEd
  13968. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13969. (define (add86) : Integer
  13970. add86start:
  13971. movq %rdi, x87
  13972. movq %rsi, y88
  13973. movq x87, %rax
  13974. addq y88, %rax
  13975. jmp inc1389conclusion
  13976. )
  13977. (define (main) : Integer
  13978. mainstart:
  13979. leaq (fun-ref add86 2), tmp89
  13980. movq $40, %rdi
  13981. movq $2, %rsi
  13982. tail-jmp tmp89
  13983. )
  13984. \end{lstlisting}
  13985. \fi}
  13986. {\if\edition\pythonEd
  13987. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13988. def add() -> int:
  13989. addstart:
  13990. movq %rdi, x
  13991. movq %rsi, y
  13992. movq x, %rax
  13993. addq y, %rax
  13994. jmp addconclusion
  13995. def main() -> int:
  13996. mainstart:
  13997. leaq add, fun.0
  13998. movq $40, %rdi
  13999. movq $2, %rsi
  14000. callq *fun.0
  14001. movq %rax, tmp.1
  14002. movq tmp.1, %rdi
  14003. callq print_int
  14004. movq $0, %rax
  14005. jmp mainconclusion
  14006. \end{lstlisting}
  14007. \fi}
  14008. $\Downarrow$
  14009. \end{minipage}
  14010. \end{tabular}
  14011. \begin{tabular}{ll}
  14012. \begin{minipage}{0.3\textwidth}
  14013. {\if\edition\racketEd
  14014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14015. .globl add86
  14016. .align 8
  14017. add86:
  14018. pushq %rbp
  14019. movq %rsp, %rbp
  14020. jmp add86start
  14021. add86start:
  14022. movq %rdi, %rax
  14023. addq %rsi, %rax
  14024. jmp add86conclusion
  14025. add86conclusion:
  14026. popq %rbp
  14027. retq
  14028. \end{lstlisting}
  14029. \fi}
  14030. {\if\edition\pythonEd
  14031. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14032. .align 8
  14033. add:
  14034. pushq %rbp
  14035. movq %rsp, %rbp
  14036. subq $0, %rsp
  14037. jmp addstart
  14038. addstart:
  14039. movq %rdi, %rdx
  14040. movq %rsi, %rcx
  14041. movq %rdx, %rax
  14042. addq %rcx, %rax
  14043. jmp addconclusion
  14044. addconclusion:
  14045. subq $0, %r15
  14046. addq $0, %rsp
  14047. popq %rbp
  14048. retq
  14049. \end{lstlisting}
  14050. \fi}
  14051. \end{minipage}
  14052. &
  14053. \begin{minipage}{0.5\textwidth}
  14054. {\if\edition\racketEd
  14055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14056. .globl main
  14057. .align 8
  14058. main:
  14059. pushq %rbp
  14060. movq %rsp, %rbp
  14061. movq $16384, %rdi
  14062. movq $16384, %rsi
  14063. callq initialize
  14064. movq rootstack_begin(%rip), %r15
  14065. jmp mainstart
  14066. mainstart:
  14067. leaq add86(%rip), %rcx
  14068. movq $40, %rdi
  14069. movq $2, %rsi
  14070. movq %rcx, %rax
  14071. popq %rbp
  14072. jmp *%rax
  14073. mainconclusion:
  14074. popq %rbp
  14075. retq
  14076. \end{lstlisting}
  14077. \fi}
  14078. {\if\edition\pythonEd
  14079. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14080. .globl main
  14081. .align 8
  14082. main:
  14083. pushq %rbp
  14084. movq %rsp, %rbp
  14085. subq $0, %rsp
  14086. movq $65536, %rdi
  14087. movq $65536, %rsi
  14088. callq initialize
  14089. movq rootstack_begin(%rip), %r15
  14090. jmp mainstart
  14091. mainstart:
  14092. leaq add(%rip), %rcx
  14093. movq $40, %rdi
  14094. movq $2, %rsi
  14095. callq *%rcx
  14096. movq %rax, %rcx
  14097. movq %rcx, %rdi
  14098. callq print_int
  14099. movq $0, %rax
  14100. jmp mainconclusion
  14101. mainconclusion:
  14102. subq $0, %r15
  14103. addq $0, %rsp
  14104. popq %rbp
  14105. retq
  14106. \end{lstlisting}
  14107. \fi}
  14108. \end{minipage}
  14109. \end{tabular}
  14110. \end{tcolorbox}
  14111. \caption{Example compilation of a simple function to x86.}
  14112. \label{fig:add-fun}
  14113. \end{figure}
  14114. % Challenge idea: inlining! (simple version)
  14115. % Further Reading
  14116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14117. \chapter{Lexically Scoped Functions}
  14118. \label{ch:Llambda}
  14119. \index{subject}{lambda}
  14120. \index{subject}{lexical scoping}
  14121. This chapter studies lexically scoped functions. Lexical scoping means
  14122. that a function's body may refer to variables whose binding site is
  14123. outside of the function, in an enclosing scope.
  14124. %
  14125. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  14126. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14127. creating lexically scoped functions. The body of the \key{lambda}
  14128. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14129. binding sites for \code{x} and \code{y} are outside of the
  14130. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14131. \key{let}}\python{a local variable of function \code{f}} and
  14132. \code{x} is a parameter of function \code{f}. Note that function
  14133. \code{f} returns the \key{lambda} as its result value. The main
  14134. expression of the program includes two calls to \code{f} with
  14135. different arguments for \code{x}, first \code{5} then \code{3}. The
  14136. functions returned from \code{f} are bound to variables \code{g} and
  14137. \code{h}. Even though these two functions were created by the same
  14138. \code{lambda}, they are really different functions because they use
  14139. different values for \code{x}. Applying \code{g} to \code{11} produces
  14140. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14141. so the result of the program is \code{42}.
  14142. \begin{figure}[btp]
  14143. \begin{tcolorbox}[colback=white]
  14144. {\if\edition\racketEd
  14145. % lambda_test_21.rkt
  14146. \begin{lstlisting}
  14147. (define (f [x : Integer]) : (Integer -> Integer)
  14148. (let ([y 4])
  14149. (lambda: ([z : Integer]) : Integer
  14150. (+ x (+ y z)))))
  14151. (let ([g (f 5)])
  14152. (let ([h (f 3)])
  14153. (+ (g 11) (h 15))))
  14154. \end{lstlisting}
  14155. \fi}
  14156. {\if\edition\pythonEd
  14157. \begin{lstlisting}
  14158. def f(x : int) -> Callable[[int], int]:
  14159. y = 4
  14160. return lambda z: x + y + z
  14161. g = f(5)
  14162. h = f(3)
  14163. print( g(11) + h(15) )
  14164. \end{lstlisting}
  14165. \fi}
  14166. \end{tcolorbox}
  14167. \caption{Example of a lexically scoped function.}
  14168. \label{fig:lexical-scoping}
  14169. \end{figure}
  14170. The approach that we take for implementing lexically scoped functions
  14171. is to compile them into top-level function definitions, translating
  14172. from \LangLam{} into \LangFun{}. However, the compiler must give
  14173. special treatment to variable occurrences such as \code{x} and
  14174. \code{y} in the body of the \code{lambda} of
  14175. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14176. may not refer to variables defined outside of it. To identify such
  14177. variable occurrences, we review the standard notion of free variable.
  14178. \begin{definition}
  14179. A variable is \textbf{free in expression} $e$ if the variable occurs
  14180. inside $e$ but does not have an enclosing definition that is also in
  14181. $e$.\index{subject}{free variable}
  14182. \end{definition}
  14183. For example, in the expression
  14184. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14185. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14186. only \code{x} and \code{y} are free in the following expression
  14187. because \code{z} is defined by the \code{lambda}.
  14188. {\if\edition\racketEd
  14189. \begin{lstlisting}
  14190. (lambda: ([z : Integer]) : Integer
  14191. (+ x (+ y z)))
  14192. \end{lstlisting}
  14193. \fi}
  14194. {\if\edition\pythonEd
  14195. \begin{lstlisting}
  14196. lambda z: x + y + z
  14197. \end{lstlisting}
  14198. \fi}
  14199. %
  14200. So the free variables of a \code{lambda} are the ones that need
  14201. special treatment. We need to transport, at runtime, the values of
  14202. those variables from the point where the \code{lambda} was created to
  14203. the point where the \code{lambda} is applied. An efficient solution to
  14204. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  14205. of the free variables together with a function pointer into a tuple,
  14206. an arrangement called a \emph{flat closure} (which we shorten to just
  14207. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  14208. %
  14209. By design, we have all the ingredients to make closures:
  14210. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  14211. function pointers. The function pointer resides at index $0$ and the
  14212. values for the free variables fill in the rest of the tuple.
  14213. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  14214. how closures work. It is a three-step dance. The program calls
  14215. function \code{f}, which creates a closure for the \code{lambda}. The
  14216. closure is a tuple whose first element is a pointer to the top-level
  14217. function that we will generate for the \code{lambda}, the second
  14218. element is the value of \code{x}, which is \code{5}, and the third
  14219. element is \code{4}, the value of \code{y}. The closure does not
  14220. contain an element for \code{z} because \code{z} is not a free
  14221. variable of the \code{lambda}. Creating the closure is step 1 of the
  14222. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14223. shown in Figure~\ref{fig:closures}.
  14224. %
  14225. The second call to \code{f} creates another closure, this time with
  14226. \code{3} in the second slot (for \code{x}). This closure is also
  14227. returned from \code{f} but bound to \code{h}, which is also shown in
  14228. Figure~\ref{fig:closures}.
  14229. \begin{figure}[tbp]
  14230. \centering
  14231. \begin{minipage}{0.65\textwidth}
  14232. \begin{tcolorbox}[colback=white]
  14233. \includegraphics[width=\textwidth]{figs/closures}
  14234. \end{tcolorbox}
  14235. \end{minipage}
  14236. \caption{Flat closure representations for the two functions
  14237. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  14238. \label{fig:closures}
  14239. \end{figure}
  14240. Continuing with the example, consider the application of \code{g} to
  14241. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  14242. obtain the function pointer from the first element of the closure and
  14243. call it, passing in the closure itself and then the regular arguments,
  14244. in this case \code{11}. This technique for applying a closure is step
  14245. 2 of the dance.
  14246. %
  14247. But doesn't this \code{lambda} only take 1 argument, for parameter
  14248. \code{z}? The third and final step of the dance is generating a
  14249. top-level function for a \code{lambda}. We add an additional
  14250. parameter for the closure and we insert an initialization at the beginning
  14251. of the function for each free variable, to bind those variables to the
  14252. appropriate elements from the closure parameter.
  14253. %
  14254. This three-step dance is known as \emph{closure conversion}. We
  14255. discuss the details of closure conversion in
  14256. Section~\ref{sec:closure-conversion} and show the code generated from
  14257. the example in Section~\ref{sec:example-lambda}. But first we define
  14258. the syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  14259. \section{The \LangLam{} Language}
  14260. \label{sec:r5}
  14261. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  14262. functions and lexical scoping, is defined in
  14263. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  14264. the \key{lambda} form to the grammar for \LangFun{}, which already has
  14265. syntax for function application.
  14266. %
  14267. \python{The syntax also includes an assignment statement that includes
  14268. a type annotation for the variable on the left-hand side, which
  14269. facilitates the type checking of \code{lambda} expressions that we
  14270. discuss later in this section.}
  14271. %
  14272. \racket{The \code{procedure-arity} operation returns the number of parameters
  14273. of a given function, an operation that we need for the translation
  14274. of dynamic typing in Chapter~\ref{ch:Ldyn}.}
  14275. %
  14276. \python{The \code{arity} operation returns the number of parameters of
  14277. a given function, an operation that we need for the translation
  14278. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  14279. The \code{arity} operation is not in Python, but the same functionality
  14280. is available in a more complex form. We include \code{arity} in the
  14281. \LangLam{} source language to enable testing.}
  14282. \newcommand{\LlambdaGrammarRacket}{
  14283. \begin{array}{lcl}
  14284. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14285. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14286. \end{array}
  14287. }
  14288. \newcommand{\LlambdaASTRacket}{
  14289. \begin{array}{lcl}
  14290. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14291. \itm{op} &::=& \code{procedure-arity}
  14292. \end{array}
  14293. }
  14294. \newcommand{\LlambdaGrammarPython}{
  14295. \begin{array}{lcl}
  14296. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14297. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14298. \end{array}
  14299. }
  14300. \newcommand{\LlambdaASTPython}{
  14301. \begin{array}{lcl}
  14302. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14303. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14304. \end{array}
  14305. }
  14306. % include AnnAssign in ASTPython
  14307. \begin{figure}[tp]
  14308. \centering
  14309. \begin{tcolorbox}[colback=white]
  14310. \small
  14311. {\if\edition\racketEd
  14312. \[
  14313. \begin{array}{l}
  14314. \gray{\LintGrammarRacket{}} \\ \hline
  14315. \gray{\LvarGrammarRacket{}} \\ \hline
  14316. \gray{\LifGrammarRacket{}} \\ \hline
  14317. \gray{\LwhileGrammarRacket} \\ \hline
  14318. \gray{\LtupGrammarRacket} \\ \hline
  14319. \gray{\LfunGrammarRacket} \\ \hline
  14320. \LlambdaGrammarRacket \\
  14321. \begin{array}{lcl}
  14322. \LangLamM{} &::=& \Def\ldots \; \Exp
  14323. \end{array}
  14324. \end{array}
  14325. \]
  14326. \fi}
  14327. {\if\edition\pythonEd
  14328. \[
  14329. \begin{array}{l}
  14330. \gray{\LintGrammarPython{}} \\ \hline
  14331. \gray{\LvarGrammarPython{}} \\ \hline
  14332. \gray{\LifGrammarPython{}} \\ \hline
  14333. \gray{\LwhileGrammarPython} \\ \hline
  14334. \gray{\LtupGrammarPython} \\ \hline
  14335. \gray{\LfunGrammarPython} \\ \hline
  14336. \LlambdaGrammarPython \\
  14337. \begin{array}{lcl}
  14338. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14339. \end{array}
  14340. \end{array}
  14341. \]
  14342. \fi}
  14343. \end{tcolorbox}
  14344. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-concrete-syntax})
  14345. with \key{lambda}.}
  14346. \label{fig:Llam-concrete-syntax}
  14347. \end{figure}
  14348. \begin{figure}[tp]
  14349. \centering
  14350. \begin{tcolorbox}[colback=white]
  14351. \small
  14352. {\if\edition\racketEd
  14353. \[\arraycolsep=3pt
  14354. \begin{array}{l}
  14355. \gray{\LintOpAST} \\ \hline
  14356. \gray{\LvarASTRacket{}} \\ \hline
  14357. \gray{\LifASTRacket{}} \\ \hline
  14358. \gray{\LwhileASTRacket{}} \\ \hline
  14359. \gray{\LtupASTRacket{}} \\ \hline
  14360. \gray{\LfunASTRacket} \\ \hline
  14361. \LlambdaASTRacket \\
  14362. \begin{array}{lcl}
  14363. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14364. \end{array}
  14365. \end{array}
  14366. \]
  14367. \fi}
  14368. {\if\edition\pythonEd
  14369. \[
  14370. \begin{array}{l}
  14371. \gray{\LintASTPython} \\ \hline
  14372. \gray{\LvarASTPython{}} \\ \hline
  14373. \gray{\LifASTPython{}} \\ \hline
  14374. \gray{\LwhileASTPython{}} \\ \hline
  14375. \gray{\LtupASTPython{}} \\ \hline
  14376. \gray{\LfunASTPython} \\ \hline
  14377. \LlambdaASTPython \\
  14378. \begin{array}{lcl}
  14379. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14380. \end{array}
  14381. \end{array}
  14382. \]
  14383. \fi}
  14384. \end{tcolorbox}
  14385. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-syntax}).}
  14386. \label{fig:Llam-syntax}
  14387. \end{figure}
  14388. \index{subject}{interpreter}
  14389. \label{sec:interp-Llambda}
  14390. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14391. \LangLam{}. The case for \key{Lambda} saves the current environment
  14392. inside the returned function value. Recall that during function
  14393. application, the environment stored in the function value, extended
  14394. with the mapping of parameters to argument values, is used to
  14395. interpret the body of the function.
  14396. \begin{figure}[tbp]
  14397. \begin{tcolorbox}[colback=white]
  14398. {\if\edition\racketEd
  14399. \begin{lstlisting}
  14400. (define interp-Llambda-class
  14401. (class interp-Lfun-class
  14402. (super-new)
  14403. (define/override (interp-op op)
  14404. (match op
  14405. ['procedure-arity
  14406. (lambda (v)
  14407. (match v
  14408. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14409. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14410. [else (super interp-op op)]))
  14411. (define/override ((interp-exp env) e)
  14412. (define recur (interp-exp env))
  14413. (match e
  14414. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14415. `(function ,xs ,body ,env)]
  14416. [else ((super interp-exp env) e)]))
  14417. ))
  14418. (define (interp-Llambda p)
  14419. (send (new interp-Llambda-class) interp-program p))
  14420. \end{lstlisting}
  14421. \fi}
  14422. {\if\edition\pythonEd
  14423. \begin{lstlisting}
  14424. class InterpLlambda(InterpLfun):
  14425. def arity(self, v):
  14426. match v:
  14427. case Function(name, params, body, env):
  14428. return len(params)
  14429. case _:
  14430. raise Exception('Llambda arity unexpected ' + repr(v))
  14431. def interp_exp(self, e, env):
  14432. match e:
  14433. case Call(Name('arity'), [fun]):
  14434. f = self.interp_exp(fun, env)
  14435. return self.arity(f)
  14436. case Lambda(params, body):
  14437. return Function('lambda', params, [Return(body)], env)
  14438. case _:
  14439. return super().interp_exp(e, env)
  14440. def interp_stmts(self, ss, env):
  14441. if len(ss) == 0:
  14442. return
  14443. match ss[0]:
  14444. case AnnAssign(lhs, typ, value, simple):
  14445. env[lhs.id] = self.interp_exp(value, env)
  14446. return self.interp_stmts(ss[1:], env)
  14447. case _:
  14448. return super().interp_stmts(ss, env)
  14449. \end{lstlisting}
  14450. \fi}
  14451. \end{tcolorbox}
  14452. \caption{Interpreter for \LangLam{}.}
  14453. \label{fig:interp-Llambda}
  14454. \end{figure}
  14455. \label{sec:type-check-r5}
  14456. \index{subject}{type checking}
  14457. {\if\edition\racketEd
  14458. %
  14459. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14460. \key{lambda} form. The body of the \key{lambda} is checked in an
  14461. environment that includes the current environment (because it is
  14462. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14463. require the body's type to match the declared return type.
  14464. %
  14465. \fi}
  14466. {\if\edition\pythonEd
  14467. %
  14468. Figures~\ref{fig:type-check-Llambda} and
  14469. \ref{fig:type-check-Llambda-part2} define the type checker for
  14470. \LangLam{}, which is more complex than one might expect. The reason
  14471. for the added complexity is that the syntax of \key{lambda} does not
  14472. include type annotations for the parameters or return type. Instead
  14473. they must be inferred. There are many approaches of type inference to
  14474. choose from of varying degrees of complexity. We choose one of the
  14475. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14476. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14477. this book is compilation, not type inference.
  14478. The main idea of bidirectional type inference is to add an auxiliary
  14479. function, here named \code{check\_exp}, that takes an expected type
  14480. and checks whether the given expression is of that type. Thus, in
  14481. \code{check\_exp}, type information flows in a top-down manner with
  14482. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14483. function, where type information flows in a primarily bottom-up
  14484. manner.
  14485. %
  14486. The idea then is to use \code{check\_exp} in all the places where we
  14487. already know what the type of an expression should be, such as in the
  14488. \code{return} statement of a top-level function definition, or on the
  14489. right-hand side of an annotated assignment statement.
  14490. Getting back to \code{lambda}, it is straightforward to check a
  14491. \code{lambda} inside \code{check\_exp} because the expected type
  14492. provides the parameter types and the return type. On the other hand,
  14493. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14494. that we do not allow \code{lambda} in contexts where we don't already
  14495. know its type. This restriction does not incur a loss of
  14496. expressiveness for \LangLam{} because it is straightforward to modify
  14497. a program to sidestep the restriction, for example, by using an
  14498. annotated assignment statement to assign the \code{lambda} to a
  14499. temporary variable.
  14500. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14501. checker records their type in a \code{has\_type} field. This type
  14502. information is used later in this chapter.
  14503. %
  14504. \fi}
  14505. \begin{figure}[tbp]
  14506. \begin{tcolorbox}[colback=white]
  14507. {\if\edition\racketEd
  14508. \begin{lstlisting}
  14509. (define (type-check-Llambda env)
  14510. (lambda (e)
  14511. (match e
  14512. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14513. (define-values (new-body bodyT)
  14514. ((type-check-exp (append (map cons xs Ts) env)) body))
  14515. (define ty `(,@Ts -> ,rT))
  14516. (cond
  14517. [(equal? rT bodyT)
  14518. (values (HasType (Lambda params rT new-body) ty) ty)]
  14519. [else
  14520. (error "mismatch in return type" bodyT rT)])]
  14521. ...
  14522. )))
  14523. \end{lstlisting}
  14524. \fi}
  14525. {\if\edition\pythonEd
  14526. \begin{lstlisting}
  14527. class TypeCheckLlambda(TypeCheckLfun):
  14528. def type_check_exp(self, e, env):
  14529. match e:
  14530. case Name(id):
  14531. e.has_type = env[id]
  14532. return env[id]
  14533. case Lambda(params, body):
  14534. raise Exception('cannot synthesize a type for a lambda')
  14535. case Call(Name('arity'), [func]):
  14536. func_t = self.type_check_exp(func, env)
  14537. match func_t:
  14538. case FunctionType(params_t, return_t):
  14539. return IntType()
  14540. case _:
  14541. raise Exception('in arity, unexpected ' + repr(func_t))
  14542. case _:
  14543. return super().type_check_exp(e, env)
  14544. def check_exp(self, e, ty, env):
  14545. match e:
  14546. case Lambda(params, body):
  14547. e.has_type = ty
  14548. match ty:
  14549. case FunctionType(params_t, return_t):
  14550. new_env = env.copy().update(zip(params, params_t))
  14551. self.check_exp(body, return_t, new_env)
  14552. case _:
  14553. raise Exception('lambda does not have type ' + str(ty))
  14554. case Call(func, args):
  14555. func_t = self.type_check_exp(func, env)
  14556. match func_t:
  14557. case FunctionType(params_t, return_t):
  14558. for (arg, param_t) in zip(args, params_t):
  14559. self.check_exp(arg, param_t, env)
  14560. self.check_type_equal(return_t, ty, e)
  14561. case _:
  14562. raise Exception('type_check_exp: in call, unexpected ' + \
  14563. repr(func_t))
  14564. case _:
  14565. t = self.type_check_exp(e, env)
  14566. self.check_type_equal(t, ty, e)
  14567. \end{lstlisting}
  14568. \fi}
  14569. \end{tcolorbox}
  14570. \caption{Type checking \LangLam{}\python{, part 1}.}
  14571. \label{fig:type-check-Llambda}
  14572. \end{figure}
  14573. {\if\edition\pythonEd
  14574. \begin{figure}[tbp]
  14575. \begin{tcolorbox}[colback=white]
  14576. \begin{lstlisting}
  14577. def check_stmts(self, ss, return_ty, env):
  14578. if len(ss) == 0:
  14579. return
  14580. match ss[0]:
  14581. case FunctionDef(name, params, body, dl, returns, comment):
  14582. new_env = env.copy().update(params)
  14583. rt = self.check_stmts(body, returns, new_env)
  14584. self.check_stmts(ss[1:], return_ty, env)
  14585. case Return(value):
  14586. self.check_exp(value, return_ty, env)
  14587. case Assign([Name(id)], value):
  14588. if id in env:
  14589. self.check_exp(value, env[id], env)
  14590. else:
  14591. env[id] = self.type_check_exp(value, env)
  14592. self.check_stmts(ss[1:], return_ty, env)
  14593. case Assign([Subscript(tup, Constant(index), Store())], value):
  14594. tup_t = self.type_check_exp(tup, env)
  14595. match tup_t:
  14596. case TupleType(ts):
  14597. self.check_exp(value, ts[index], env)
  14598. case _:
  14599. raise Exception('expected a tuple, not ' + repr(tup_t))
  14600. self.check_stmts(ss[1:], return_ty, env)
  14601. case AnnAssign(Name(id), ty_annot, value, simple):
  14602. ss[0].annotation = ty_annot
  14603. if id in env:
  14604. self.check_type_equal(env[id], ty_annot)
  14605. else:
  14606. env[id] = ty_annot
  14607. self.check_exp(value, ty_annot, env)
  14608. self.check_stmts(ss[1:], return_ty, env)
  14609. case _:
  14610. self.type_check_stmts(ss, env)
  14611. def type_check(self, p):
  14612. match p:
  14613. case Module(body):
  14614. env = {}
  14615. for s in body:
  14616. match s:
  14617. case FunctionDef(name, params, bod, dl, returns, comment):
  14618. params_t = [t for (x,t) in params]
  14619. env[name] = FunctionType(params_t, returns)
  14620. self.check_stmts(body, int, env)
  14621. \end{lstlisting}
  14622. \end{tcolorbox}
  14623. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14624. \label{fig:type-check-Llambda-part2}
  14625. \end{figure}
  14626. \fi}
  14627. \clearpage
  14628. \section{Assignment and Lexically Scoped Functions}
  14629. \label{sec:assignment-scoping}
  14630. The combination of lexically-scoped functions and assignment to
  14631. variables raises a challenge with the flat-closure approach to
  14632. implementing lexically-scoped functions. Consider the following
  14633. example in which function \code{f} has a free variable \code{x} that
  14634. is changed after \code{f} is created but before the call to \code{f}.
  14635. % loop_test_11.rkt
  14636. {\if\edition\racketEd
  14637. \begin{lstlisting}
  14638. (let ([x 0])
  14639. (let ([y 0])
  14640. (let ([z 20])
  14641. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14642. (begin
  14643. (set! x 10)
  14644. (set! y 12)
  14645. (f y))))))
  14646. \end{lstlisting}
  14647. \fi}
  14648. {\if\edition\pythonEd
  14649. % box_free_assign.py
  14650. \begin{lstlisting}
  14651. def g(z : int) -> int:
  14652. x = 0
  14653. y = 0
  14654. f : Callable[[int],int] = lambda a: a + x + z
  14655. x = 10
  14656. y = 12
  14657. return f(y)
  14658. print( g(20) )
  14659. \end{lstlisting}
  14660. \fi} The correct output for this example is \code{42} because the call
  14661. to \code{f} is required to use the current value of \code{x} (which is
  14662. \code{10}). Unfortunately, the closure conversion pass
  14663. (Section~\ref{sec:closure-conversion}) generates code for the
  14664. \code{lambda} that copies the old value of \code{x} into a
  14665. closure. Thus, if we naively apply closure conversion, the output of
  14666. this program would be \code{32}.
  14667. A first attempt at solving this problem would be to save a pointer to
  14668. \code{x} in the closure and change the occurrences of \code{x} inside
  14669. the lambda to dereference the pointer. Of course, this would require
  14670. assigning \code{x} to the stack and not to a register. However, the
  14671. problem goes a bit deeper.
  14672. Consider the following example that returns a function that refers to
  14673. a local variable of the enclosing function.
  14674. \begin{center}
  14675. \begin{minipage}{\textwidth}
  14676. {\if\edition\racketEd
  14677. \begin{lstlisting}
  14678. (define (f []) : Integer
  14679. (let ([x 0])
  14680. (let ([g (lambda: () : Integer x)])
  14681. (begin
  14682. (set! x 42)
  14683. g))))
  14684. ((f))
  14685. \end{lstlisting}
  14686. \fi}
  14687. {\if\edition\pythonEd
  14688. % counter.py
  14689. \begin{lstlisting}
  14690. def f():
  14691. x = 0
  14692. g = lambda: x
  14693. x = 42
  14694. return g
  14695. print( f()() )
  14696. \end{lstlisting}
  14697. \fi}
  14698. \end{minipage}
  14699. \end{center}
  14700. In this example, the lifetime of \code{x} extends beyond the lifetime
  14701. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14702. stack frame for the call to \code{f}, it would be gone by the time we
  14703. call \code{g}, leaving us with dangling pointers for
  14704. \code{x}. This example demonstrates that when a variable occurs free
  14705. inside a function, its lifetime becomes indefinite. Thus, the value of
  14706. the variable needs to live on the heap. The verb
  14707. \emph{box}\index{subject}{box} is often used for allocating a single
  14708. value on the heap, producing a pointer, and
  14709. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14710. %
  14711. We introduce a new pass named \code{convert\_assignments} to address
  14712. this challenge.
  14713. %
  14714. \python{But before diving into that, we have one more
  14715. problem to discuss.}
  14716. \if\edition\pythonEd
  14717. \section{Uniquify Variables}
  14718. \label{sec:uniquify-lambda}
  14719. With the addition of \code{lambda} we have a complication to deal
  14720. with: name shadowing. Consider the following program with a function
  14721. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14722. \code{lambda} expressions. The first \code{lambda} has a parameter
  14723. that is also named \code{x}.
  14724. \begin{lstlisting}
  14725. def f(x:int, y:int) -> Callable[[int], int]:
  14726. g : Callable[[int],int] = (lambda x: x + y)
  14727. h : Callable[[int],int] = (lambda y: x + y)
  14728. x = input_int()
  14729. return g
  14730. print(f(0, 10)(32))
  14731. \end{lstlisting}
  14732. Many of our compiler passes rely on being able to connect variable
  14733. uses with their definitions using just the name of the variable,
  14734. including new passes in this chapter. However, in the above example
  14735. the name of the variable does not uniquely determine its
  14736. definition. To solve this problem we recommend implementing a pass
  14737. named \code{uniquify} that renames every variable in the program to
  14738. make sure they are all unique.
  14739. The following shows the result of \code{uniquify} for the above
  14740. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14741. and the \code{x} parameter of the \code{lambda} is renamed to
  14742. \code{x\_4}.
  14743. \begin{lstlisting}
  14744. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14745. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14746. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14747. x_0 = input_int()
  14748. return g_2
  14749. def main() -> int :
  14750. print(f(0, 10)(32))
  14751. return 0
  14752. \end{lstlisting}
  14753. \fi
  14754. %% \section{Reveal Functions}
  14755. %% \label{sec:reveal-functions-r5}
  14756. %% \racket{To support the \code{procedure-arity} operator we need to
  14757. %% communicate the arity of a function to the point of closure
  14758. %% creation.}
  14759. %% %
  14760. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14761. %% function at runtime. Thus, we need to communicate the arity of a
  14762. %% function to the point of closure creation.}
  14763. %% %
  14764. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14765. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14766. %% \[
  14767. %% \begin{array}{lcl}
  14768. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14769. %% \end{array}
  14770. %% \]
  14771. \section{Assignment Conversion}
  14772. \label{sec:convert-assignments}
  14773. The purpose of the \code{convert\_assignments} pass is to address the
  14774. challenge regarding the interaction between variable assignments and
  14775. closure conversion. First we identify which variables need to be
  14776. boxed, then we transform the program to box those variables. In
  14777. general, boxing introduces runtime overhead that we would like to
  14778. avoid, so we should box as few variables as possible. We recommend
  14779. boxing the variables in the intersection of the following two sets of
  14780. variables:
  14781. \begin{enumerate}
  14782. \item The variables that are free in a \code{lambda}.
  14783. \item The variables that appear on the left-hand side of an
  14784. assignment.
  14785. \end{enumerate}
  14786. The first condition is a must but the second condition is
  14787. conservative. It is possible to develop a more liberal condition using
  14788. static program analysis.
  14789. Consider again the first example from
  14790. Section~\ref{sec:assignment-scoping}:
  14791. %
  14792. {\if\edition\racketEd
  14793. \begin{lstlisting}
  14794. (let ([x 0])
  14795. (let ([y 0])
  14796. (let ([z 20])
  14797. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14798. (begin
  14799. (set! x 10)
  14800. (set! y 12)
  14801. (f y))))))
  14802. \end{lstlisting}
  14803. \fi}
  14804. {\if\edition\pythonEd
  14805. \begin{lstlisting}
  14806. def g(z : int) -> int:
  14807. x = 0
  14808. y = 0
  14809. f : Callable[[int],int] = lambda a: a + x + z
  14810. x = 10
  14811. y = 12
  14812. return f(y)
  14813. print( g(20) )
  14814. \end{lstlisting}
  14815. \fi}
  14816. %
  14817. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14818. variables \code{x} and \code{z} occur free inside the
  14819. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14820. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14821. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14822. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14823. with a tuple write. The output of \code{convert\_assignments} for
  14824. this example is as follows.
  14825. %
  14826. {\if\edition\racketEd
  14827. \begin{lstlisting}
  14828. (define (main) : Integer
  14829. (let ([x0 (vector 0)])
  14830. (let ([y1 0])
  14831. (let ([z2 20])
  14832. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14833. (+ a3 (+ (vector-ref x0 0) z2)))])
  14834. (begin
  14835. (vector-set! x0 0 10)
  14836. (set! y1 12)
  14837. (f4 y1)))))))
  14838. \end{lstlisting}
  14839. \fi}
  14840. %
  14841. {\if\edition\pythonEd
  14842. \begin{lstlisting}
  14843. def g(z : int)-> int:
  14844. x = (uninitialized(int),)
  14845. x[0] = 0
  14846. y = 0
  14847. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14848. x[0] = 10
  14849. y = 12
  14850. return f(y)
  14851. def main() -> int:
  14852. print(g(20))
  14853. return 0
  14854. \end{lstlisting}
  14855. \fi}
  14856. To compute the free variables of all the \code{lambda} expressions, we
  14857. recommend defining two auxiliary functions:
  14858. \begin{enumerate}
  14859. \item \code{free\_variables} computes the free variables of an expression, and
  14860. \item \code{free\_in\_lambda} collects all of the variables that are
  14861. free in any of the \code{lambda} expressions, using
  14862. \code{free\_variables} in the case for each \code{lambda}.
  14863. \end{enumerate}
  14864. {\if\edition\racketEd
  14865. %
  14866. To compute the variables that are assigned-to, we recommend using the
  14867. \code{collect-set!} function that we introduced in
  14868. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14869. forms such as \code{Lambda}.
  14870. %
  14871. \fi}
  14872. {\if\edition\pythonEd
  14873. %
  14874. To compute the variables that are assigned-to, we recommend defining
  14875. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14876. the set of variables that occur in the left-hand side of an assignment
  14877. statement, and otherwise returns the empty set.
  14878. %
  14879. \fi}
  14880. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14881. free in a \code{lambda} and that are assigned-to in the enclosing
  14882. function definition.
  14883. Next we discuss the \code{convert\_assignments} pass. In the case for
  14884. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14885. $\VAR{x}$ to a tuple read.
  14886. %
  14887. {\if\edition\racketEd
  14888. \begin{lstlisting}
  14889. (Var |$x$|)
  14890. |$\Rightarrow$|
  14891. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14892. \end{lstlisting}
  14893. \fi}
  14894. %
  14895. {\if\edition\pythonEd
  14896. \begin{lstlisting}
  14897. Name(|$x$|)
  14898. |$\Rightarrow$|
  14899. Subscript(Name(|$x$|), Constant(0), Load())
  14900. \end{lstlisting}
  14901. \fi}
  14902. %
  14903. \noindent In the case for assignment, recursively process the
  14904. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14905. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14906. as follows.
  14907. %
  14908. {\if\edition\racketEd
  14909. \begin{lstlisting}
  14910. (SetBang |$x$| |$\itm{rhs}$|)
  14911. |$\Rightarrow$|
  14912. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14913. \end{lstlisting}
  14914. \fi}
  14915. {\if\edition\pythonEd
  14916. \begin{lstlisting}
  14917. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14918. |$\Rightarrow$|
  14919. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14920. \end{lstlisting}
  14921. \fi}
  14922. %
  14923. {\if\edition\racketEd
  14924. The case for \code{Lambda} is non-trivial, but it is similar to the
  14925. case for function definitions, which we discuss next.
  14926. \fi}
  14927. %
  14928. To translate a function definition, we first compute $\mathit{AF}$,
  14929. the intersection of the variables that are free in a \code{lambda} and
  14930. that are assigned-to. We then apply assignment conversion to the body
  14931. of the function definition. Finally, we box the parameters of this
  14932. function definition that are in $\mathit{AF}$. For example,
  14933. the parameter \code{x} of the following function \code{g}
  14934. needs to be boxed.
  14935. {\if\edition\racketEd
  14936. \begin{lstlisting}
  14937. (define (g [x : Integer]) : Integer
  14938. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14939. (begin
  14940. (set! x 10)
  14941. (f 32))))
  14942. \end{lstlisting}
  14943. \fi}
  14944. %
  14945. {\if\edition\pythonEd
  14946. \begin{lstlisting}
  14947. def g(x : int) -> int:
  14948. f : Callable[[int],int] = lambda a: a + x
  14949. x = 10
  14950. return f(32)
  14951. \end{lstlisting}
  14952. \fi}
  14953. %
  14954. \noindent We box parameter \code{x} by creating a local variable named
  14955. \code{x} that is initialized to a tuple whose contents is the value of
  14956. the parameter, which has been renamed to \code{x\_0}.
  14957. %
  14958. {\if\edition\racketEd
  14959. \begin{lstlisting}
  14960. (define (g [x_0 : Integer]) : Integer
  14961. (let ([x (vector x_0)])
  14962. (let ([f (lambda: ([a : Integer]) : Integer
  14963. (+ a (vector-ref x 0)))])
  14964. (begin
  14965. (vector-set! x 0 10)
  14966. (f 32)))))
  14967. \end{lstlisting}
  14968. \fi}
  14969. %
  14970. {\if\edition\pythonEd
  14971. \begin{lstlisting}
  14972. def g(x_0 : int)-> int:
  14973. x = (x_0,)
  14974. f : Callable[[int], int] = (lambda a: a + x[0])
  14975. x[0] = 10
  14976. return f(32)
  14977. \end{lstlisting}
  14978. \fi}
  14979. \section{Closure Conversion}
  14980. \label{sec:closure-conversion}
  14981. \index{subject}{closure conversion}
  14982. The compiling of lexically-scoped functions into top-level function
  14983. definitions and flat closures is accomplished in the pass
  14984. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  14985. and before \code{limit\_functions}.
  14986. As usual, we implement the pass as a recursive function over the
  14987. AST. The interesting cases are the ones for \key{lambda} and function
  14988. application. We transform a \key{lambda} expression into an expression
  14989. that creates a closure, that is, a tuple whose first element is a
  14990. function pointer and the rest of the elements are the values of the
  14991. free variables of the \key{lambda}.
  14992. %
  14993. However, we use the \code{Closure} AST node instead of using a tuple
  14994. so that we can record the arity.
  14995. %
  14996. In the generated code below, \itm{fvs} is the free variables of the
  14997. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14998. %
  14999. \racket{The \itm{arity} is the number of parameters (the length of
  15000. \itm{ps}).}
  15001. %
  15002. {\if\edition\racketEd
  15003. \begin{lstlisting}
  15004. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15005. |$\Rightarrow$|
  15006. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15007. \end{lstlisting}
  15008. \fi}
  15009. %
  15010. {\if\edition\pythonEd
  15011. \begin{lstlisting}
  15012. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15013. |$\Rightarrow$|
  15014. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15015. \end{lstlisting}
  15016. \fi}
  15017. %
  15018. In addition to transforming each \key{Lambda} AST node into a
  15019. tuple, we create a top-level function definition for each
  15020. \key{Lambda}, as shown below.\\
  15021. \begin{minipage}{0.8\textwidth}
  15022. {\if\edition\racketEd
  15023. \begin{lstlisting}
  15024. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15025. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15026. ...
  15027. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15028. |\itm{body'}|)...))
  15029. \end{lstlisting}
  15030. \fi}
  15031. {\if\edition\pythonEd
  15032. \begin{lstlisting}
  15033. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15034. |$\itm{fvs}_1$| = clos[1]
  15035. |$\ldots$|
  15036. |$\itm{fvs}_n$| = clos[|$n$|]
  15037. |\itm{body'}|
  15038. \end{lstlisting}
  15039. \fi}
  15040. \end{minipage}\\
  15041. The \code{clos} parameter refers to the closure. Translate the type
  15042. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15043. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15044. \itm{closTy} is a tuple type whose first element type is
  15045. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15046. the element types are the types of the free variables in the
  15047. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15048. is non-trivial to give a type to the function in the closure's type.%
  15049. %
  15050. \footnote{To give an accurate type to a closure, we would need to add
  15051. existential types to the type checker~\citep{Minamide:1996ys}.}
  15052. %
  15053. %% The dummy type is considered to be equal to any other type during type
  15054. %% checking.
  15055. The free variables become local variables that are initialized with
  15056. their values in the closure.
  15057. Closure conversion turns every function into a tuple, so the type
  15058. annotations in the program must also be translated. We recommend
  15059. defining an auxiliary recursive function for this purpose. Function
  15060. types should be translated as follows.
  15061. %
  15062. {\if\edition\racketEd
  15063. \begin{lstlisting}
  15064. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15065. |$\Rightarrow$|
  15066. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15067. \end{lstlisting}
  15068. \fi}
  15069. {\if\edition\pythonEd
  15070. \begin{lstlisting}
  15071. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15072. |$\Rightarrow$|
  15073. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15074. \end{lstlisting}
  15075. \fi}
  15076. %
  15077. The above type says that the first thing in the tuple is a
  15078. function. The first parameter of the function is a tuple (a closure)
  15079. and the rest of the parameters are the ones from the original
  15080. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15081. omits the types of the free variables because 1) those types are not
  15082. available in this context and 2) we do not need them in the code that
  15083. is generated for function application. So this type only describes the
  15084. first component of the closure tuple. At runtime the tuple may have
  15085. more components, but we ignore them at this point.
  15086. We transform function application into code that retrieves the
  15087. function from the closure and then calls the function, passing the
  15088. closure as the first argument. We place $e'$ in a temporary variable
  15089. to avoid code duplication.
  15090. \begin{center}
  15091. \begin{minipage}{\textwidth}
  15092. {\if\edition\racketEd
  15093. \begin{lstlisting}
  15094. (Apply |$e$| |$\itm{es}$|)
  15095. |$\Rightarrow$|
  15096. (Let |$\itm{tmp}$| |$e'$|
  15097. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15098. \end{lstlisting}
  15099. \fi}
  15100. %
  15101. {\if\edition\pythonEd
  15102. \begin{lstlisting}
  15103. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15104. |$\Rightarrow$|
  15105. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15106. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15107. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15108. \end{lstlisting}
  15109. \fi}
  15110. \end{minipage}
  15111. \end{center}
  15112. There is also the question of what to do with references to top-level
  15113. function definitions. To maintain a uniform translation of function
  15114. application, we turn function references into closures.
  15115. \begin{tabular}{lll}
  15116. \begin{minipage}{0.3\textwidth}
  15117. {\if\edition\racketEd
  15118. \begin{lstlisting}
  15119. (FunRef |$f$| |$n$|)
  15120. \end{lstlisting}
  15121. \fi}
  15122. {\if\edition\pythonEd
  15123. \begin{lstlisting}
  15124. FunRef(|$f$|, |$n$|)
  15125. \end{lstlisting}
  15126. \fi}
  15127. \end{minipage}
  15128. &
  15129. $\Rightarrow$
  15130. &
  15131. \begin{minipage}{0.5\textwidth}
  15132. {\if\edition\racketEd
  15133. \begin{lstlisting}
  15134. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15135. \end{lstlisting}
  15136. \fi}
  15137. {\if\edition\pythonEd
  15138. \begin{lstlisting}
  15139. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15140. \end{lstlisting}
  15141. \fi}
  15142. \end{minipage}
  15143. \end{tabular} \\
  15144. We no longer need the annotated assignment statement \code{AnnAssign}
  15145. to support the type checking of \code{lambda} expressions, so we
  15146. translate it to a regular \code{Assign} statement.
  15147. The top-level function definitions need to be updated to take an extra
  15148. closure parameter but that parameter is ignored in the body of those
  15149. functions.
  15150. \section{An Example Translation}
  15151. \label{sec:example-lambda}
  15152. Figure~\ref{fig:lexical-functions-example} shows the result of
  15153. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15154. program demonstrating lexical scoping that we discussed at the
  15155. beginning of this chapter.
  15156. \begin{figure}[tbp]
  15157. \begin{tcolorbox}[colback=white]
  15158. \begin{minipage}{0.8\textwidth}
  15159. {\if\edition\racketEd
  15160. % tests/lambda_test_6.rkt
  15161. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15162. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15163. (let ([y8 4])
  15164. (lambda: ([z9 : Integer]) : Integer
  15165. (+ x7 (+ y8 z9)))))
  15166. (define (main) : Integer
  15167. (let ([g0 ((fun-ref f6 1) 5)])
  15168. (let ([h1 ((fun-ref f6 1) 3)])
  15169. (+ (g0 11) (h1 15)))))
  15170. \end{lstlisting}
  15171. $\Rightarrow$
  15172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15173. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15174. (let ([y8 4])
  15175. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15176. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15177. (let ([x7 (vector-ref fvs3 1)])
  15178. (let ([y8 (vector-ref fvs3 2)])
  15179. (+ x7 (+ y8 z9)))))
  15180. (define (main) : Integer
  15181. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15182. ((vector-ref clos5 0) clos5 5))])
  15183. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15184. ((vector-ref clos6 0) clos6 3))])
  15185. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15186. \end{lstlisting}
  15187. \fi}
  15188. %
  15189. {\if\edition\pythonEd
  15190. % free_var.py
  15191. \begin{lstlisting}
  15192. def f(x : int) -> Callable[[int], int]:
  15193. y = 4
  15194. return lambda z: x + y + z
  15195. g = f(5)
  15196. h = f(3)
  15197. print( g(11) + h(15) )
  15198. \end{lstlisting}
  15199. $\Rightarrow$
  15200. \begin{lstlisting}
  15201. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15202. x = fvs_1[1]
  15203. y = fvs_1[2]
  15204. return x + y[0] + z
  15205. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15206. y = (777,)
  15207. y[0] = 4
  15208. return (lambda_0, x, y)
  15209. def main() -> int:
  15210. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15211. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15212. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15213. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15214. return 0
  15215. \end{lstlisting}
  15216. \fi}
  15217. \end{minipage}
  15218. \end{tcolorbox}
  15219. \caption{Example of closure conversion.}
  15220. \label{fig:lexical-functions-example}
  15221. \end{figure}
  15222. \begin{exercise}\normalfont\normalsize
  15223. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15224. Create 5 new programs that use \key{lambda} functions and make use of
  15225. lexical scoping. Test your compiler on these new programs and all of
  15226. your previously created test programs.
  15227. \end{exercise}
  15228. \section{Expose Allocation}
  15229. \label{sec:expose-allocation-r5}
  15230. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15231. that allocates and initializes a tuple, similar to the translation of
  15232. the tuple creation in Section~\ref{sec:expose-allocation}.
  15233. The only difference is replacing the use of
  15234. \ALLOC{\itm{len}}{\itm{type}} with
  15235. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15236. \section{Explicate Control and \LangCLam{}}
  15237. \label{sec:explicate-r5}
  15238. The output language of \code{explicate\_control} is \LangCLam{} whose
  15239. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  15240. %
  15241. \racket{The only differences with respect to \LangCFun{} is the
  15242. addition of the \code{AllocateClosure} form to the grammar for
  15243. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15244. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15245. similar to the handling of other expressions such as primitive
  15246. operators.}
  15247. %
  15248. \python{The differences with respect to \LangCFun{} are the
  15249. additions of \code{Uninitialized}, \code{AllocateClosure},
  15250. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15251. \code{explicate\_control} pass is similar to the handling of other
  15252. expressions such as primitive operators.}
  15253. \newcommand{\ClambdaASTRacket}{
  15254. \begin{array}{lcl}
  15255. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15256. \itm{op} &::= & \code{procedure-arity}
  15257. \end{array}
  15258. }
  15259. \newcommand{\ClambdaASTPython}{
  15260. \begin{array}{lcl}
  15261. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15262. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15263. &\MID& \ARITY{\Atm}
  15264. \end{array}
  15265. }
  15266. \begin{figure}[tp]
  15267. \begin{tcolorbox}[colback=white]
  15268. \small
  15269. {\if\edition\racketEd
  15270. \[
  15271. \begin{array}{l}
  15272. \gray{\CvarASTRacket} \\ \hline
  15273. \gray{\CifASTRacket} \\ \hline
  15274. \gray{\CloopASTRacket} \\ \hline
  15275. \gray{\CtupASTRacket} \\ \hline
  15276. \gray{\CfunASTRacket} \\ \hline
  15277. \ClambdaASTRacket \\
  15278. \begin{array}{lcl}
  15279. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15280. \end{array}
  15281. \end{array}
  15282. \]
  15283. \fi}
  15284. {\if\edition\pythonEd
  15285. \[
  15286. \begin{array}{l}
  15287. \gray{\CifASTPython} \\ \hline
  15288. \gray{\CtupASTPython} \\ \hline
  15289. \gray{\CfunASTPython} \\ \hline
  15290. \ClambdaASTPython \\
  15291. \begin{array}{lcl}
  15292. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15293. \end{array}
  15294. \end{array}
  15295. \]
  15296. \fi}
  15297. \end{tcolorbox}
  15298. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  15299. \label{fig:Clam-syntax}
  15300. \end{figure}
  15301. \section{Select Instructions}
  15302. \label{sec:select-instructions-Llambda}
  15303. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15304. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15305. (Section~\ref{sec:select-instructions-gc}). The only difference is
  15306. that you should place the \itm{arity} in the tag that is stored at
  15307. position $0$ of the vector. Recall that in
  15308. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15309. was not used. We store the arity in the $5$ bits starting at position
  15310. $58$.
  15311. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15312. instructions that access the tag from position $0$ of the vector and
  15313. extract the $5$-bits starting at position $58$ from the tag.}
  15314. %
  15315. \python{Compile a call to the \code{arity} operator to a sequence of
  15316. instructions that access the tag from position $0$ of the tuple
  15317. (representing a closure) and extract the $5$-bits starting at position
  15318. $58$ from the tag.}
  15319. \begin{figure}[p]
  15320. \begin{tcolorbox}[colback=white]
  15321. {\if\edition\racketEd
  15322. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15323. \node (Lfun) at (0,2) {\large \LangLam{}};
  15324. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15325. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15326. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15327. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15328. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  15329. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  15330. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  15331. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15332. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15333. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  15334. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  15335. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  15336. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  15337. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  15338. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  15339. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  15340. \path[->,bend left=15] (Lfun) edge [above] node
  15341. {\ttfamily\footnotesize shrink} (Lfun-2);
  15342. \path[->,bend left=15] (Lfun-2) edge [above] node
  15343. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15344. \path[->,bend left=15] (Lfun-3) edge [above] node
  15345. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15346. \path[->,bend left=15] (F1-0) edge [above] node
  15347. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15348. \path[->,bend left=15] (F1-1) edge [left] node
  15349. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15350. \path[->,bend left=15] (F1-2) edge [below] node
  15351. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15352. \path[->,bend right=15] (F1-3) edge [above] node
  15353. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  15354. \path[->,bend left=15] (F1-4) edge [below] node
  15355. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15356. \path[->,bend right=15] (F1-5) edge [above] node
  15357. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15358. \path[->,bend right=15] (F1-6) edge [right] node
  15359. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15360. \path[->,bend left=15] (C3-2) edge [left] node
  15361. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15362. \path[->,bend right=15] (x86-2) edge [left] node
  15363. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15364. \path[->,bend right=15] (x86-2-1) edge [below] node
  15365. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15366. \path[->,bend right=15] (x86-2-2) edge [left] node
  15367. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15368. \path[->,bend left=15] (x86-3) edge [above] node
  15369. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15370. \path[->,bend left=15] (x86-4) edge [right] node
  15371. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  15372. \end{tikzpicture}
  15373. \fi}
  15374. {\if\edition\pythonEd
  15375. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15376. \node (Lfun) at (0,2) {\large \LangLam{}};
  15377. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  15378. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  15379. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  15380. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  15381. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  15382. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  15383. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  15384. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  15385. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15386. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15387. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15388. \node (x86-2-2) at (3,-6) {\large \LangXIndCallVar{}};
  15389. \node (x86-3) at (3,-4) {\large \LangXIndCallVar{}};
  15390. \node (x86-4) at (6,-4) {\large \LangXIndCall{}};
  15391. \node (x86-5) at (6,-6) {\large \LangXIndCall{}};
  15392. \path[->,bend left=15] (Lfun) edge [above] node
  15393. {\ttfamily\footnotesize shrink} (Lfun-2);
  15394. \path[->,bend left=15] (Lfun-2) edge [above] node
  15395. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15396. \path[->,bend left=15] (Lfun-3) edge [above] node
  15397. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15398. \path[->,bend left=15] (F1-0) edge [above] node
  15399. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  15400. \path[->,bend left=15] (F1-1) edge [left] node
  15401. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  15402. \path[->,bend left=15] (F1-2) edge [below] node
  15403. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  15404. \path[->,bend right=15] (F1-3) edge [above] node
  15405. {\ttfamily\footnotesize expose\_alloc.} (F1-5);
  15406. \path[->,bend right=15] (F1-5) edge [above] node
  15407. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  15408. \path[->,bend right=15] (F1-6) edge [right] node
  15409. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15410. \path[->,bend left=15] (C3-2) edge [right] node
  15411. {\ttfamily\footnotesize select\_instr.} (x86-2);
  15412. \path[->,bend right=15] (x86-2) edge [right] node
  15413. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15414. \path[->,bend right=15] (x86-2-1) edge [below] node
  15415. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  15416. \path[->,bend right=15] (x86-2-2) edge [right] node
  15417. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  15418. \path[->,bend left=15] (x86-3) edge [above] node
  15419. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  15420. \path[->,bend left=15] (x86-4) edge [right] node
  15421. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15422. \end{tikzpicture}
  15423. \fi}
  15424. \end{tcolorbox}
  15425. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  15426. functions.}
  15427. \label{fig:Llambda-passes}
  15428. \end{figure}
  15429. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15430. needed for the compilation of \LangLam{}.
  15431. \clearpage
  15432. \section{Challenge: Optimize Closures}
  15433. \label{sec:optimize-closures}
  15434. In this chapter we compiled lexically-scoped functions into a
  15435. relatively efficient representation: flat closures. However, even this
  15436. representation comes with some overhead. For example, consider the
  15437. following program with a function \code{tail\_sum} that does not have
  15438. any free variables and where all the uses of \code{tail\_sum} are in
  15439. applications where we know that only \code{tail\_sum} is being applied
  15440. (and not any other functions).
  15441. \begin{center}
  15442. \begin{minipage}{0.95\textwidth}
  15443. {\if\edition\racketEd
  15444. \begin{lstlisting}
  15445. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15446. (if (eq? n 0)
  15447. s
  15448. (tail_sum (- n 1) (+ n s))))
  15449. (+ (tail_sum 3 0) 36)
  15450. \end{lstlisting}
  15451. \fi}
  15452. {\if\edition\pythonEd
  15453. \begin{lstlisting}
  15454. def tail_sum(n : int, s : int) -> int:
  15455. if n == 0:
  15456. return s
  15457. else:
  15458. return tail_sum(n - 1, n + s)
  15459. print( tail_sum(3, 0) + 36)
  15460. \end{lstlisting}
  15461. \fi}
  15462. \end{minipage}
  15463. \end{center}
  15464. As described in this chapter, we uniformly apply closure conversion to
  15465. all functions, obtaining the following output for this program.
  15466. \begin{center}
  15467. \begin{minipage}{0.95\textwidth}
  15468. {\if\edition\racketEd
  15469. \begin{lstlisting}
  15470. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15471. (if (eq? n2 0)
  15472. s3
  15473. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15474. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15475. (define (main) : Integer
  15476. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15477. ((vector-ref clos6 0) clos6 3 0)) 27))
  15478. \end{lstlisting}
  15479. \fi}
  15480. {\if\edition\pythonEd
  15481. \begin{lstlisting}
  15482. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15483. if n_0 == 0:
  15484. return s_1
  15485. else:
  15486. return (let clos_2 = (tail_sum,)
  15487. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15488. def main() -> int :
  15489. print((let clos_4 = (tail_sum,)
  15490. in clos_4[0](clos_4, 3, 0)) + 36)
  15491. return 0
  15492. \end{lstlisting}
  15493. \fi}
  15494. \end{minipage}
  15495. \end{center}
  15496. In the previous chapter, there would be no allocation in the program
  15497. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  15498. the above program allocates memory for each closure and the calls to
  15499. \code{tail\_sum} are indirect. These two differences incur
  15500. considerable overhead in a program such as this one, where the
  15501. allocations and indirect calls occur inside a tight loop.
  15502. One might think that this problem is trivial to solve: can't we just
  15503. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15504. and compile them to direct calls instead of treating it like a call to
  15505. a closure? We would also drop the new \code{fvs} parameter of
  15506. \code{tail\_sum}.
  15507. %
  15508. However, this problem is not so trivial because a global function may
  15509. ``escape'' and become involved in applications that also involve
  15510. closures. Consider the following example in which the application
  15511. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15512. application, because the \code{lambda} may flow into \code{f}, but the
  15513. \code{inc} function might also flow into \code{f}.
  15514. \begin{center}
  15515. \begin{minipage}{\textwidth}
  15516. % lambda_test_30.rkt
  15517. {\if\edition\racketEd
  15518. \begin{lstlisting}
  15519. (define (inc [x : Integer]) : Integer
  15520. (+ x 1))
  15521. (let ([y (read)])
  15522. (let ([f (if (eq? (read) 0)
  15523. inc
  15524. (lambda: ([x : Integer]) : Integer (- x y)))])
  15525. (f 41)))
  15526. \end{lstlisting}
  15527. \fi}
  15528. {\if\edition\pythonEd
  15529. \begin{lstlisting}
  15530. def add1(x : int) -> int:
  15531. return x + 1
  15532. y = input_int()
  15533. g : Callable[[int], int] = lambda x: x - y
  15534. f = add1 if input_int() == 0 else g
  15535. print( f(41) )
  15536. \end{lstlisting}
  15537. \fi}
  15538. \end{minipage}
  15539. \end{center}
  15540. If a global function name is used in any way other than as the
  15541. operator in a direct call, then we say that the function
  15542. \emph{escapes}. If a global function does not escape, then we do not
  15543. need to perform closure conversion on the function.
  15544. \begin{exercise}\normalfont\normalsize
  15545. Implement an auxiliary function for detecting which global
  15546. functions escape. Using that function, implement an improved version
  15547. of closure conversion that does not apply closure conversion to
  15548. global functions that do not escape but instead compiles them as
  15549. regular functions. Create several new test cases that check whether
  15550. you properly detect whether global functions escape or not.
  15551. \end{exercise}
  15552. So far we have reduced the overhead of calling global functions, but
  15553. it would also be nice to reduce the overhead of calling a
  15554. \code{lambda} when we can determine at compile time which
  15555. \code{lambda} will be called. We refer to such calls as \emph{known
  15556. calls}. Consider the following example in which a \code{lambda} is
  15557. bound to \code{f} and then applied.
  15558. {\if\edition\racketEd
  15559. % lambda_test_9.rkt
  15560. \begin{lstlisting}
  15561. (let ([y (read)])
  15562. (let ([f (lambda: ([x : Integer]) : Integer
  15563. (+ x y))])
  15564. (f 21)))
  15565. \end{lstlisting}
  15566. \fi}
  15567. {\if\edition\pythonEd
  15568. \begin{lstlisting}
  15569. y = input_int()
  15570. f : Callable[[int],int] = lambda x: x + y
  15571. print( f(21) )
  15572. \end{lstlisting}
  15573. \fi}
  15574. %
  15575. \noindent Closure conversion compiles the application
  15576. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15577. %
  15578. {\if\edition\racketEd
  15579. \begin{lstlisting}
  15580. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15581. (let ([y2 (vector-ref fvs6 1)])
  15582. (+ x3 y2)))
  15583. (define (main) : Integer
  15584. (let ([y2 (read)])
  15585. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15586. ((vector-ref f4 0) f4 21))))
  15587. \end{lstlisting}
  15588. \fi}
  15589. {\if\edition\pythonEd
  15590. \begin{lstlisting}
  15591. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15592. y_1 = fvs_4[1]
  15593. return x_2 + y_1[0]
  15594. def main() -> int:
  15595. y_1 = (777,)
  15596. y_1[0] = input_int()
  15597. f_0 = (lambda_3, y_1)
  15598. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15599. return 0
  15600. \end{lstlisting}
  15601. \fi}
  15602. %
  15603. \noindent but we can instead compile the application
  15604. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15605. %
  15606. {\if\edition\racketEd
  15607. \begin{lstlisting}
  15608. (define (main) : Integer
  15609. (let ([y2 (read)])
  15610. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15611. ((fun-ref lambda5 1) f4 21))))
  15612. \end{lstlisting}
  15613. \fi}
  15614. {\if\edition\pythonEd
  15615. \begin{lstlisting}
  15616. def main() -> int:
  15617. y_1 = (777,)
  15618. y_1[0] = input_int()
  15619. f_0 = (lambda_3, y_1)
  15620. print(lambda_3(f_0, 21))
  15621. return 0
  15622. \end{lstlisting}
  15623. \fi}
  15624. The problem of determining which \code{lambda} will be called from a
  15625. particular application is quite challenging in general and the topic
  15626. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15627. following exercise we recommend that you compile an application to a
  15628. direct call when the operator is a variable and \racket{the variable
  15629. is \code{let}-bound to a closure}\python{the previous assignment to
  15630. the variable is a closure}. This can be accomplished by maintaining
  15631. an environment mapping variables to function names. Extend the
  15632. environment whenever you encounter a closure on the right-hand side of
  15633. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15634. name of the global function for the closure. This pass should come
  15635. after closure conversion.
  15636. \begin{exercise}\normalfont\normalsize
  15637. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15638. compiles known calls into direct calls. Verify that your compiler is
  15639. successful in this regard on several example programs.
  15640. \end{exercise}
  15641. These exercises only scratches the surface of optimizing of
  15642. closures. A good next step for the interested reader is to look at the
  15643. work of \citet{Keep:2012ab}.
  15644. \section{Further Reading}
  15645. The notion of lexically scoped functions predates modern computers by
  15646. about a decade. They were invented by \citet{Church:1932aa}, who
  15647. proposed the lambda calculus as a foundation for logic. Anonymous
  15648. functions were included in the LISP~\citep{McCarthy:1960dz}
  15649. programming language but were initially dynamically scoped. The Scheme
  15650. dialect of LISP adopted lexical scoping and
  15651. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15652. Scheme programs. However, environments were represented as linked
  15653. lists, so variable look-up was linear in the size of the
  15654. environment. \citet{Appel91} gives a detailed description of several
  15655. closure representations. In this chapter we represent environments
  15656. using flat closures, which were invented by
  15657. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15658. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15659. closures, variable look-up is constant time but the time to create a
  15660. closure is proportional to the number of its free variables. Flat
  15661. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15662. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15663. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15664. % compilers)
  15665. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15666. \chapter{Dynamic Typing}
  15667. \label{ch:Ldyn}
  15668. \index{subject}{dynamic typing}
  15669. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15670. typed language that is a subset of \racket{Racket}\python{Python}. The
  15671. focus on dynamic typing is in contrast to the previous chapters, which
  15672. have studied the compilation of statically typed languages. In
  15673. dynamically typed languages such as \LangDyn{}, a particular
  15674. expression may produce a value of a different type each time it is
  15675. executed. Consider the following example with a conditional \code{if}
  15676. expression that may return a Boolean or an integer depending on the
  15677. input to the program.
  15678. % part of dynamic_test_25.rkt
  15679. {\if\edition\racketEd
  15680. \begin{lstlisting}
  15681. (not (if (eq? (read) 1) #f 0))
  15682. \end{lstlisting}
  15683. \fi}
  15684. {\if\edition\pythonEd
  15685. \begin{lstlisting}
  15686. not (False if input_int() == 1 else 0)
  15687. \end{lstlisting}
  15688. \fi}
  15689. Languages that allow expressions to produce different kinds of values
  15690. are called \emph{polymorphic}, a word composed of the Greek roots
  15691. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15692. are several kinds of polymorphism in programming languages, such as
  15693. subtype polymorphism and parametric
  15694. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15695. study in this chapter does not have a special name but it is the kind
  15696. that arises in dynamically typed languages.
  15697. Another characteristic of dynamically typed languages is that
  15698. primitive operations, such as \code{not}, are often defined to operate
  15699. on many different types of values. In fact, in
  15700. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15701. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15702. given anything else it returns \FALSE{}.
  15703. Furthermore, even when primitive operations restrict their inputs to
  15704. values of a certain type, this restriction is enforced at runtime
  15705. instead of during compilation. For example, the tuple read
  15706. operation
  15707. \racket{\code{(vector-ref \#t 0)}}
  15708. \python{\code{True[0]}}
  15709. results in a run-time error because the first argument must
  15710. be a tuple, not a Boolean.
  15711. \section{The \LangDyn{} Language}
  15712. \newcommand{\LdynGrammarRacket}{
  15713. \begin{array}{rcl}
  15714. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15715. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15716. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15717. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15718. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15719. \end{array}
  15720. }
  15721. \newcommand{\LdynASTRacket}{
  15722. \begin{array}{lcl}
  15723. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15724. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15725. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15726. \end{array}
  15727. }
  15728. \begin{figure}[tp]
  15729. \centering
  15730. \begin{tcolorbox}[colback=white]
  15731. \small
  15732. {\if\edition\racketEd
  15733. \[
  15734. \begin{array}{l}
  15735. \gray{\LintGrammarRacket{}} \\ \hline
  15736. \gray{\LvarGrammarRacket{}} \\ \hline
  15737. \gray{\LifGrammarRacket{}} \\ \hline
  15738. \gray{\LwhileGrammarRacket} \\ \hline
  15739. \gray{\LtupGrammarRacket} \\ \hline
  15740. \LdynGrammarRacket \\
  15741. \begin{array}{rcl}
  15742. \LangDynM{} &::=& \Def\ldots\; \Exp
  15743. \end{array}
  15744. \end{array}
  15745. \]
  15746. \fi}
  15747. {\if\edition\pythonEd
  15748. \[
  15749. \begin{array}{rcl}
  15750. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15751. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15752. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15753. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15754. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15755. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15756. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15757. \MID \CLEN{\Exp} \\
  15758. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15759. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15760. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15761. \MID \Var\mathop{\key{=}}\Exp \\
  15762. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15763. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15764. &\MID& \CRETURN{\Exp} \\
  15765. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15766. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15767. \end{array}
  15768. \]
  15769. \fi}
  15770. \end{tcolorbox}
  15771. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15772. \label{fig:r7-concrete-syntax}
  15773. \end{figure}
  15774. \begin{figure}[tp]
  15775. \centering
  15776. \begin{tcolorbox}[colback=white]
  15777. \small
  15778. {\if\edition\racketEd
  15779. \[
  15780. \begin{array}{l}
  15781. \gray{\LintASTRacket{}} \\ \hline
  15782. \gray{\LvarASTRacket{}} \\ \hline
  15783. \gray{\LifASTRacket{}} \\ \hline
  15784. \gray{\LwhileASTRacket} \\ \hline
  15785. \gray{\LtupASTRacket} \\ \hline
  15786. \LdynASTRacket \\
  15787. \begin{array}{lcl}
  15788. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15789. \end{array}
  15790. \end{array}
  15791. \]
  15792. \fi}
  15793. {\if\edition\pythonEd
  15794. \[
  15795. \begin{array}{rcl}
  15796. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15797. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15798. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15799. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15800. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15801. &\MID & \code{Is()} \\
  15802. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15803. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15804. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15805. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15806. \MID \VAR{\Var{}} \\
  15807. &\MID& \BOOL{\itm{bool}}
  15808. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15809. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15810. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15811. &\MID& \LEN{\Exp} \\
  15812. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15813. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15814. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15815. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15816. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15817. &\MID& \RETURN{\Exp} \\
  15818. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15819. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15820. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15821. \end{array}
  15822. \]
  15823. \fi}
  15824. \end{tcolorbox}
  15825. \caption{The abstract syntax of \LangDyn{}.}
  15826. \label{fig:r7-syntax}
  15827. \end{figure}
  15828. The concrete and abstract syntax of \LangDyn{} is defined in
  15829. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15830. %
  15831. There is no type checker for \LangDyn{} because it only checks types
  15832. at runtime.
  15833. The definitional interpreter for \LangDyn{} is presented in
  15834. \racket{Figure~\ref{fig:interp-Ldyn}}
  15835. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15836. and its auxiliary functions are defined in
  15837. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15838. \INT{n}. Instead of simply returning the integer \code{n} (as
  15839. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15840. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15841. value} that combines an underlying value with a tag that identifies
  15842. what kind of value it is. We define the following \racket{struct}\python{class}
  15843. to represented tagged values.
  15844. %
  15845. {\if\edition\racketEd
  15846. \begin{lstlisting}
  15847. (struct Tagged (value tag) #:transparent)
  15848. \end{lstlisting}
  15849. \fi}
  15850. {\if\edition\pythonEd
  15851. \begin{minipage}{\textwidth}
  15852. \begin{lstlisting}
  15853. @dataclass(eq=True)
  15854. class Tagged(Value):
  15855. value : Value
  15856. tag : str
  15857. def __str__(self):
  15858. return str(self.value)
  15859. \end{lstlisting}
  15860. \end{minipage}
  15861. \fi}
  15862. %
  15863. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  15864. \code{Vector}, and \code{Procedure}.}
  15865. %
  15866. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15867. \code{'tuple'}, and \code{'function'}.}
  15868. %
  15869. Tags are closely related to types but don't always capture all the
  15870. information that a type does.
  15871. %
  15872. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15873. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15874. Any)} is tagged with \code{Procedure}.}
  15875. %
  15876. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15877. is tagged with \code{'tuple'} and a function of type
  15878. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15879. is tagged with \code{'function'}.}
  15880. Next consider the match case for accessing the element of a tuple.
  15881. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15882. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15883. argument is a tuple and the second is an integer.
  15884. \racket{
  15885. If they are not, a \code{trapped-error} is raised. Recall from
  15886. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15887. raises a \code{trapped-error} error, the compiled code must also
  15888. signal an error by exiting with return code \code{255}. A
  15889. \code{trapped-error} is also raised if the index is not less than the
  15890. length of the vector.
  15891. }
  15892. %
  15893. \python{If they are not, an exception is raised. The compiled code
  15894. must also signal an error by exiting with return code \code{255}. A
  15895. exception is also raised if the index is not less than the length of the
  15896. tuple or if it is negative.}
  15897. \begin{figure}[tbp]
  15898. \begin{tcolorbox}[colback=white]
  15899. {\if\edition\racketEd
  15900. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15901. (define ((interp-Ldyn-exp env) ast)
  15902. (define recur (interp-Ldyn-exp env))
  15903. (match ast
  15904. [(Var x) (dict-ref env x)]
  15905. [(Int n) (Tagged n 'Integer)]
  15906. [(Bool b) (Tagged b 'Boolean)]
  15907. [(Lambda xs rt body)
  15908. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15909. [(Prim 'vector es)
  15910. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15911. [(Prim 'vector-ref (list e1 e2))
  15912. (define vec (recur e1)) (define i (recur e2))
  15913. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15914. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15915. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15916. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15917. [(Prim 'vector-set! (list e1 e2 e3))
  15918. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15919. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15920. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15921. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15922. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15923. (Tagged (void) 'Void)]
  15924. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15925. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15926. [(Prim 'or (list e1 e2))
  15927. (define v1 (recur e1))
  15928. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15929. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15930. [(Prim op (list e1))
  15931. #:when (set-member? type-predicates op)
  15932. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15933. [(Prim op es)
  15934. (define args (map recur es))
  15935. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15936. (unless (for/or ([expected-tags (op-tags op)])
  15937. (equal? expected-tags tags))
  15938. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15939. (tag-value
  15940. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15941. [(If q t f)
  15942. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15943. [(Apply f es)
  15944. (define new-f (recur f)) (define args (map recur es))
  15945. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15946. (match f-val
  15947. [`(function ,xs ,body ,lam-env)
  15948. (unless (eq? (length xs) (length args))
  15949. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15950. (define new-env (append (map cons xs args) lam-env))
  15951. ((interp-Ldyn-exp new-env) body)]
  15952. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15953. \end{lstlisting}
  15954. \fi}
  15955. {\if\edition\pythonEd
  15956. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15957. class InterpLdyn(InterpLlambda):
  15958. def interp_exp(self, e, env):
  15959. match e:
  15960. case Constant(n):
  15961. return self.tag(super().interp_exp(e, env))
  15962. case Tuple(es, Load()):
  15963. return self.tag(super().interp_exp(e, env))
  15964. case Lambda(params, body):
  15965. return self.tag(super().interp_exp(e, env))
  15966. case Call(Name('input_int'), []):
  15967. return self.tag(super().interp_exp(e, env))
  15968. case BinOp(left, Add(), right):
  15969. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15970. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15971. case BinOp(left, Sub(), right):
  15972. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15973. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15974. case UnaryOp(USub(), e1):
  15975. v = self.interp_exp(e1, env)
  15976. return self.tag(- self.untag(v, 'int', e))
  15977. case IfExp(test, body, orelse):
  15978. v = self.interp_exp(test, env)
  15979. if self.untag(v, 'bool', e):
  15980. return self.interp_exp(body, env)
  15981. else:
  15982. return self.interp_exp(orelse, env)
  15983. case UnaryOp(Not(), e1):
  15984. v = self.interp_exp(e1, env)
  15985. return self.tag(not self.untag(v, 'bool', e))
  15986. case BoolOp(And(), values):
  15987. left = values[0]; right = values[1]
  15988. l = self.interp_exp(left, env)
  15989. if self.untag(l, 'bool', e):
  15990. return self.interp_exp(right, env)
  15991. else:
  15992. return self.tag(False)
  15993. case BoolOp(Or(), values):
  15994. left = values[0]; right = values[1]
  15995. l = self.interp_exp(left, env)
  15996. if self.untag(l, 'bool', e):
  15997. return self.tag(True)
  15998. else:
  15999. return self.interp_exp(right, env)
  16000. case Compare(left, [cmp], [right]):
  16001. l = self.interp_exp(left, env)
  16002. r = self.interp_exp(right, env)
  16003. if l.tag == r.tag:
  16004. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16005. else:
  16006. raise Exception('interp Compare unexpected '
  16007. + repr(l) + ' ' + repr(r))
  16008. case Subscript(tup, index, Load()):
  16009. t = self.interp_exp(tup, env)
  16010. n = self.interp_exp(index, env)
  16011. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16012. case Call(Name('len'), [tup]):
  16013. t = self.interp_exp(tup, env)
  16014. return self.tag(len(self.untag(t, 'tuple', e)))
  16015. case _:
  16016. return self.tag(super().interp_exp(e, env))
  16017. \end{lstlisting}
  16018. \fi}
  16019. \end{tcolorbox}
  16020. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16021. \label{fig:interp-Ldyn}
  16022. \end{figure}
  16023. {\if\edition\pythonEd
  16024. \begin{figure}[tbp]
  16025. \begin{tcolorbox}[colback=white]
  16026. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16027. class InterpLdyn(InterpLlambda):
  16028. def interp_stmts(self, ss, env):
  16029. if len(ss) == 0:
  16030. return
  16031. match ss[0]:
  16032. case If(test, body, orelse):
  16033. v = self.interp_exp(test, env)
  16034. if self.untag(v, 'bool', ss[0]):
  16035. return self.interp_stmts(body + ss[1:], env)
  16036. else:
  16037. return self.interp_stmts(orelse + ss[1:], env)
  16038. case While(test, body, []):
  16039. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16040. self.interp_stmts(body, env)
  16041. return self.interp_stmts(ss[1:], env)
  16042. case Assign([Subscript(tup, index)], value):
  16043. tup = self.interp_exp(tup, env)
  16044. index = self.interp_exp(index, env)
  16045. tup_v = self.untag(tup, 'tuple', ss[0])
  16046. index_v = self.untag(index, 'int', ss[0])
  16047. tup_v[index_v] = self.interp_exp(value, env)
  16048. return self.interp_stmts(ss[1:], env)
  16049. case FunctionDef(name, params, bod, dl, returns, comment):
  16050. ps = [x for (x,t) in params]
  16051. env[name] = self.tag(Function(name, ps, bod, env))
  16052. return self.interp_stmts(ss[1:], env)
  16053. case _:
  16054. return super().interp_stmts(ss, env)
  16055. \end{lstlisting}
  16056. \end{tcolorbox}
  16057. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16058. \label{fig:interp-Ldyn-2}
  16059. \end{figure}
  16060. \fi}
  16061. \begin{figure}[tbp]
  16062. \begin{tcolorbox}[colback=white]
  16063. {\if\edition\racketEd
  16064. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16065. (define (interp-op op)
  16066. (match op
  16067. ['+ fx+]
  16068. ['- fx-]
  16069. ['read read-fixnum]
  16070. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16071. ['< (lambda (v1 v2)
  16072. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16073. ['<= (lambda (v1 v2)
  16074. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16075. ['> (lambda (v1 v2)
  16076. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16077. ['>= (lambda (v1 v2)
  16078. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16079. ['boolean? boolean?]
  16080. ['integer? fixnum?]
  16081. ['void? void?]
  16082. ['vector? vector?]
  16083. ['vector-length vector-length]
  16084. ['procedure? (match-lambda
  16085. [`(functions ,xs ,body ,env) #t] [else #f])]
  16086. [else (error 'interp-op "unknown operator" op)]))
  16087. (define (op-tags op)
  16088. (match op
  16089. ['+ '((Integer Integer))]
  16090. ['- '((Integer Integer) (Integer))]
  16091. ['read '(())]
  16092. ['not '((Boolean))]
  16093. ['< '((Integer Integer))]
  16094. ['<= '((Integer Integer))]
  16095. ['> '((Integer Integer))]
  16096. ['>= '((Integer Integer))]
  16097. ['vector-length '((Vector))]))
  16098. (define type-predicates
  16099. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16100. (define (tag-value v)
  16101. (cond [(boolean? v) (Tagged v 'Boolean)]
  16102. [(fixnum? v) (Tagged v 'Integer)]
  16103. [(procedure? v) (Tagged v 'Procedure)]
  16104. [(vector? v) (Tagged v 'Vector)]
  16105. [(void? v) (Tagged v 'Void)]
  16106. [else (error 'tag-value "unidentified value ~a" v)]))
  16107. (define (check-tag val expected ast)
  16108. (define tag (Tagged-tag val))
  16109. (unless (eq? tag expected)
  16110. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16111. \end{lstlisting}
  16112. \fi}
  16113. {\if\edition\pythonEd
  16114. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16115. class InterpLdyn(InterpLlambda):
  16116. def tag(self, v):
  16117. if v is True or v is False:
  16118. return Tagged(v, 'bool')
  16119. elif isinstance(v, int):
  16120. return Tagged(v, 'int')
  16121. elif isinstance(v, Function):
  16122. return Tagged(v, 'function')
  16123. elif isinstance(v, tuple):
  16124. return Tagged(v, 'tuple')
  16125. elif isinstance(v, type(None)):
  16126. return Tagged(v, 'none')
  16127. else:
  16128. raise Exception('tag: unexpected ' + repr(v))
  16129. def untag(self, v, expected_tag, ast):
  16130. match v:
  16131. case Tagged(val, tag) if tag == expected_tag:
  16132. return val
  16133. case _:
  16134. raise Exception('expected Tagged value with '
  16135. + expected_tag + ', not ' + ' ' + repr(v))
  16136. def apply_fun(self, fun, args, e):
  16137. f = self.untag(fun, 'function', e)
  16138. return super().apply_fun(f, args, e)
  16139. \end{lstlisting}
  16140. \fi}
  16141. \end{tcolorbox}
  16142. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16143. \label{fig:interp-Ldyn-aux}
  16144. \end{figure}
  16145. \clearpage
  16146. \section{Representation of Tagged Values}
  16147. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  16148. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  16149. values at the bit level. Because almost every operation in \LangDyn{}
  16150. involves manipulating tagged values, the representation must be
  16151. efficient. Recall that all of our values are 64 bits. We shall steal
  16152. the 3 right-most bits to encode the tag. We use $001$ to identify
  16153. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  16154. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  16155. function for mapping types to tag codes.
  16156. {\if\edition\racketEd
  16157. \begin{align*}
  16158. \itm{tagof}(\key{Integer}) &= 001 \\
  16159. \itm{tagof}(\key{Boolean}) &= 100 \\
  16160. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16161. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16162. \itm{tagof}(\key{Void}) &= 101
  16163. \end{align*}
  16164. \fi}
  16165. {\if\edition\pythonEd
  16166. \begin{align*}
  16167. \itm{tagof}(\key{IntType()}) &= 001 \\
  16168. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16169. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16170. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16171. \itm{tagof}(\key{type(None)}) &= 101
  16172. \end{align*}
  16173. \fi}
  16174. This stealing of 3 bits comes at some price: integers are now restricted
  16175. to the range from $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16176. affect tuples and procedures because those values are addresses, and
  16177. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  16178. they are always $000$. Thus, we do not lose information by overwriting
  16179. the rightmost 3 bits with the tag and we can simply zero-out the tag
  16180. to recover the original address.
  16181. To make tagged values into first-class entities, we can give them a
  16182. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  16183. operations such as \code{Inject} and \code{Project} for creating and
  16184. using them, yielding the statically typed \LangAny{} intermediate
  16185. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16186. Section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  16187. language in greater detail.
  16188. \section{The \LangAny{} Language}
  16189. \label{sec:Rany-lang}
  16190. \newcommand{\LanyASTRacket}{
  16191. \begin{array}{lcl}
  16192. \Type &::= & \ANYTY \\
  16193. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16194. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16195. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16196. \itm{op} &::= & \code{any-vector-length}
  16197. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16198. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16199. \MID \code{procedure?} \MID \code{void?} \\
  16200. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16201. \end{array}
  16202. }
  16203. \newcommand{\LanyASTPython}{
  16204. \begin{array}{lcl}
  16205. \Type &::= & \key{AnyType()} \\
  16206. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16207. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16208. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16209. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16210. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16211. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16212. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16213. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16214. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16215. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16216. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16217. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16218. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16219. \end{array}
  16220. }
  16221. \begin{figure}[tp]
  16222. \centering
  16223. \begin{tcolorbox}[colback=white]
  16224. \small
  16225. {\if\edition\racketEd
  16226. \[
  16227. \begin{array}{l}
  16228. \gray{\LintOpAST} \\ \hline
  16229. \gray{\LvarASTRacket{}} \\ \hline
  16230. \gray{\LifASTRacket{}} \\ \hline
  16231. \gray{\LwhileASTRacket{}} \\ \hline
  16232. \gray{\LtupASTRacket{}} \\ \hline
  16233. \gray{\LfunASTRacket} \\ \hline
  16234. \gray{\LlambdaASTRacket} \\ \hline
  16235. \LanyASTRacket \\
  16236. \begin{array}{lcl}
  16237. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16238. \end{array}
  16239. \end{array}
  16240. \]
  16241. \fi}
  16242. {\if\edition\pythonEd
  16243. \[
  16244. \begin{array}{l}
  16245. \gray{\LintASTPython} \\ \hline
  16246. \gray{\LvarASTPython{}} \\ \hline
  16247. \gray{\LifASTPython{}} \\ \hline
  16248. \gray{\LwhileASTPython{}} \\ \hline
  16249. \gray{\LtupASTPython{}} \\ \hline
  16250. \gray{\LfunASTPython} \\ \hline
  16251. \gray{\LlambdaASTPython} \\ \hline
  16252. \LanyASTPython \\
  16253. \begin{array}{lcl}
  16254. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16255. \end{array}
  16256. \end{array}
  16257. \]
  16258. \fi}
  16259. \end{tcolorbox}
  16260. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Llam-syntax}).}
  16261. \label{fig:Lany-syntax}
  16262. \end{figure}
  16263. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Lany-syntax}.
  16264. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16265. %% Figure~\ref{fig:Lany-concrete-syntax}.)}
  16266. The $\INJECT{e}{T}$ form
  16267. converts the value produced by expression $e$ of type $T$ into a
  16268. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  16269. produced by expression $e$ into a value of type $T$ or halts the
  16270. program if the type tag does not match $T$.
  16271. %
  16272. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16273. restricted to a flat type $\FType$, which simplifies the
  16274. implementation and corresponds with the needs for compiling \LangDyn{}.
  16275. The \racket{\code{any-vector}} operators
  16276. \python{\code{any\_tuple\_load} and \code{any\_len}}
  16277. adapt the tuple operations so that they can be applied to a value of
  16278. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16279. tuple operations in that the index is not restricted to be a literal
  16280. integer in the grammar but is allowed to be any expression.
  16281. \racket{The type predicates such as
  16282. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16283. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16284. the predicate and they return {\FALSE} otherwise.}
  16285. The type checker for \LangAny{} is shown in
  16286. Figure~\ref{fig:type-check-Lany}
  16287. %
  16288. \racket{ and uses the auxiliary functions in
  16289. Figure~\ref{fig:type-check-Lany-aux}}.
  16290. %
  16291. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Lany} and
  16292. its auxiliary functions are in Figure~\ref{fig:interp-Lany-aux}.
  16293. \begin{figure}[btp]
  16294. \begin{tcolorbox}[colback=white]
  16295. {\if\edition\racketEd
  16296. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16297. (define type-check-Lany-class
  16298. (class type-check-Llambda-class
  16299. (super-new)
  16300. (inherit check-type-equal?)
  16301. (define/override (type-check-exp env)
  16302. (lambda (e)
  16303. (define recur (type-check-exp env))
  16304. (match e
  16305. [(Inject e1 ty)
  16306. (unless (flat-ty? ty)
  16307. (error 'type-check "may only inject from flat type, not ~a" ty))
  16308. (define-values (new-e1 e-ty) (recur e1))
  16309. (check-type-equal? e-ty ty e)
  16310. (values (Inject new-e1 ty) 'Any)]
  16311. [(Project e1 ty)
  16312. (unless (flat-ty? ty)
  16313. (error 'type-check "may only project to flat type, not ~a" ty))
  16314. (define-values (new-e1 e-ty) (recur e1))
  16315. (check-type-equal? e-ty 'Any e)
  16316. (values (Project new-e1 ty) ty)]
  16317. [(Prim 'any-vector-length (list e1))
  16318. (define-values (e1^ t1) (recur e1))
  16319. (check-type-equal? t1 'Any e)
  16320. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16321. [(Prim 'any-vector-ref (list e1 e2))
  16322. (define-values (e1^ t1) (recur e1))
  16323. (define-values (e2^ t2) (recur e2))
  16324. (check-type-equal? t1 'Any e)
  16325. (check-type-equal? t2 'Integer e)
  16326. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16327. [(Prim 'any-vector-set! (list e1 e2 e3))
  16328. (define-values (e1^ t1) (recur e1))
  16329. (define-values (e2^ t2) (recur e2))
  16330. (define-values (e3^ t3) (recur e3))
  16331. (check-type-equal? t1 'Any e)
  16332. (check-type-equal? t2 'Integer e)
  16333. (check-type-equal? t3 'Any e)
  16334. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16335. [(Prim pred (list e1))
  16336. #:when (set-member? (type-predicates) pred)
  16337. (define-values (new-e1 e-ty) (recur e1))
  16338. (check-type-equal? e-ty 'Any e)
  16339. (values (Prim pred (list new-e1)) 'Boolean)]
  16340. [(Prim 'eq? (list arg1 arg2))
  16341. (define-values (e1 t1) (recur arg1))
  16342. (define-values (e2 t2) (recur arg2))
  16343. (match* (t1 t2)
  16344. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16345. [(other wise) (check-type-equal? t1 t2 e)])
  16346. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16347. [else ((super type-check-exp env) e)])))
  16348. ))
  16349. \end{lstlisting}
  16350. \fi}
  16351. {\if\edition\pythonEd
  16352. \begin{lstlisting}
  16353. class TypeCheckLany(TypeCheckLlambda):
  16354. def type_check_exp(self, e, env):
  16355. match e:
  16356. case Inject(value, typ):
  16357. self.check_exp(value, typ, env)
  16358. return AnyType()
  16359. case Project(value, typ):
  16360. self.check_exp(value, AnyType(), env)
  16361. return typ
  16362. case Call(Name('any_tuple_load'), [tup, index]):
  16363. self.check_exp(tup, AnyType(), env)
  16364. self.check_exp(index, IntType(), env)
  16365. return AnyType()
  16366. case Call(Name('any_len'), [tup]):
  16367. self.check_exp(tup, AnyType(), env)
  16368. return IntType()
  16369. case Call(Name('arity'), [fun]):
  16370. ty = self.type_check_exp(fun, env)
  16371. match ty:
  16372. case FunctionType(ps, rt):
  16373. return IntType()
  16374. case TupleType([FunctionType(ps,rs)]):
  16375. return IntType()
  16376. case _:
  16377. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16378. case Call(Name('make_any'), [value, tag]):
  16379. self.type_check_exp(value, env)
  16380. self.check_exp(tag, IntType(), env)
  16381. return AnyType()
  16382. case AnnLambda(params, returns, body):
  16383. new_env = {x:t for (x,t) in env.items()}
  16384. for (x,t) in params:
  16385. new_env[x] = t
  16386. return_t = self.type_check_exp(body, new_env)
  16387. self.check_type_equal(returns, return_t, e)
  16388. return FunctionType([t for (x,t) in params], return_t)
  16389. case _:
  16390. return super().type_check_exp(e, env)
  16391. \end{lstlisting}
  16392. \fi}
  16393. \end{tcolorbox}
  16394. \caption{Type checker for the \LangAny{} language.}
  16395. \label{fig:type-check-Lany}
  16396. \end{figure}
  16397. {\if\edition\racketEd
  16398. \begin{figure}[tbp]
  16399. \begin{tcolorbox}[colback=white]
  16400. \begin{lstlisting}
  16401. (define/override (operator-types)
  16402. (append
  16403. '((integer? . ((Any) . Boolean))
  16404. (vector? . ((Any) . Boolean))
  16405. (procedure? . ((Any) . Boolean))
  16406. (void? . ((Any) . Boolean)))
  16407. (super operator-types)))
  16408. (define/public (type-predicates)
  16409. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16410. (define/public (flat-ty? ty)
  16411. (match ty
  16412. [(or `Integer `Boolean `Void) #t]
  16413. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16414. ['(Vectorof Any) #t]
  16415. [`(,ts ... -> ,rt)
  16416. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16417. [else #f]))
  16418. \end{lstlisting}
  16419. \end{tcolorbox}
  16420. \caption{Auxiliary methods for type checking \LangAny{}.}
  16421. \label{fig:type-check-Lany-aux}
  16422. \end{figure}
  16423. \fi}
  16424. \begin{figure}[btp]
  16425. \begin{tcolorbox}[colback=white]
  16426. {\if\edition\racketEd
  16427. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16428. (define interp-Lany-class
  16429. (class interp-Llambda-class
  16430. (super-new)
  16431. (define/override (interp-op op)
  16432. (match op
  16433. ['boolean? (match-lambda
  16434. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16435. [else #f])]
  16436. ['integer? (match-lambda
  16437. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16438. [else #f])]
  16439. ['vector? (match-lambda
  16440. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16441. [else #f])]
  16442. ['procedure? (match-lambda
  16443. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16444. [else #f])]
  16445. ['eq? (match-lambda*
  16446. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16447. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16448. [ls (apply (super interp-op op) ls)])]
  16449. ['any-vector-ref (lambda (v i)
  16450. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16451. ['any-vector-set! (lambda (v i a)
  16452. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16453. ['any-vector-length (lambda (v)
  16454. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16455. [else (super interp-op op)]))
  16456. (define/override ((interp-exp env) e)
  16457. (define recur (interp-exp env))
  16458. (match e
  16459. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16460. [(Project e ty2) (apply-project (recur e) ty2)]
  16461. [else ((super interp-exp env) e)]))
  16462. ))
  16463. (define (interp-Lany p)
  16464. (send (new interp-Lany-class) interp-program p))
  16465. \end{lstlisting}
  16466. \fi}
  16467. {\if\edition\pythonEd
  16468. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16469. class InterpLany(InterpLlambda):
  16470. def interp_exp(self, e, env):
  16471. match e:
  16472. case Inject(value, typ):
  16473. v = self.interp_exp(value, env)
  16474. return Tagged(v, self.type_to_tag(typ))
  16475. case Project(value, typ):
  16476. v = self.interp_exp(value, env)
  16477. match v:
  16478. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16479. return val
  16480. case _:
  16481. raise Exception('interp project to ' + repr(typ)
  16482. + ' unexpected ' + repr(v))
  16483. case Call(Name('any_tuple_load'), [tup, index]):
  16484. tv = self.interp_exp(tup, env)
  16485. n = self.interp_exp(index, env)
  16486. match tv:
  16487. case Tagged(v, tag):
  16488. return v[n]
  16489. case _:
  16490. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16491. case Call(Name('any_len'), [value]):
  16492. v = self.interp_exp(value, env)
  16493. match v:
  16494. case Tagged(value, tag):
  16495. return len(value)
  16496. case _:
  16497. raise Exception('interp any_len unexpected ' + repr(v))
  16498. case Call(Name('arity'), [fun]):
  16499. f = self.interp_exp(fun, env)
  16500. return self.arity(f)
  16501. case _:
  16502. return super().interp_exp(e, env)
  16503. \end{lstlisting}
  16504. \fi}
  16505. \end{tcolorbox}
  16506. \caption{Interpreter for \LangAny{}.}
  16507. \label{fig:interp-Lany}
  16508. \end{figure}
  16509. \begin{figure}[tbp]
  16510. \begin{tcolorbox}[colback=white]
  16511. {\if\edition\racketEd
  16512. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16513. (define/public (apply-inject v tg) (Tagged v tg))
  16514. (define/public (apply-project v ty2)
  16515. (define tag2 (any-tag ty2))
  16516. (match v
  16517. [(Tagged v1 tag1)
  16518. (cond
  16519. [(eq? tag1 tag2)
  16520. (match ty2
  16521. [`(Vector ,ts ...)
  16522. (define l1 ((interp-op 'vector-length) v1))
  16523. (cond
  16524. [(eq? l1 (length ts)) v1]
  16525. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16526. l1 (length ts))])]
  16527. [`(,ts ... -> ,rt)
  16528. (match v1
  16529. [`(function ,xs ,body ,env)
  16530. (cond [(eq? (length xs) (length ts)) v1]
  16531. [else
  16532. (error 'apply-project "arity mismatch ~a != ~a"
  16533. (length xs) (length ts))])]
  16534. [else (error 'apply-project "expected function not ~a" v1)])]
  16535. [else v1])]
  16536. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16537. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16538. \end{lstlisting}
  16539. \fi}
  16540. {\if\edition\pythonEd
  16541. \begin{lstlisting}
  16542. class InterpLany(InterpLlambda):
  16543. def type_to_tag(self, typ):
  16544. match typ:
  16545. case FunctionType(params, rt):
  16546. return 'function'
  16547. case TupleType(fields):
  16548. return 'tuple'
  16549. case t if t == int:
  16550. return 'int'
  16551. case t if t == bool:
  16552. return 'bool'
  16553. case IntType():
  16554. return 'int'
  16555. case BoolType():
  16556. return 'int'
  16557. case _:
  16558. raise Exception('type_to_tag unexpected ' + repr(typ))
  16559. def arity(self, v):
  16560. match v:
  16561. case Function(name, params, body, env):
  16562. return len(params)
  16563. case ClosureTuple(args, arity):
  16564. return arity
  16565. case _:
  16566. raise Exception('Lany arity unexpected ' + repr(v))
  16567. \end{lstlisting}
  16568. \fi}
  16569. \end{tcolorbox}
  16570. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16571. \label{fig:interp-Lany-aux}
  16572. \end{figure}
  16573. \clearpage
  16574. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16575. \label{sec:compile-r7}
  16576. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16577. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16578. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16579. is that given any subexpression $e$ in the \LangDyn{} program, the
  16580. pass will produce an expression $e'$ in \LangAny{} that has type
  16581. \ANYTY{}. For example, the first row in
  16582. Figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16583. \TRUE{}, which must be injected to produce an expression of type
  16584. \ANYTY{}.
  16585. %
  16586. The second row of Figure~\ref{fig:compile-r7-Lany}, the compilation of
  16587. addition, is representative of compilation for many primitive
  16588. operations: the arguments have type \ANYTY{} and must be projected to
  16589. \INTTYPE{} before the addition can be performed.
  16590. The compilation of \key{lambda} (third row of
  16591. Figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16592. produce type annotations: we simply use \ANYTY{}.
  16593. %
  16594. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16595. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16596. this pass has to account for some differences in behavior between
  16597. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16598. permissive than \LangAny{} regarding what kind of values can be used
  16599. in various places. For example, the condition of an \key{if} does
  16600. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16601. of the same type (in that case the result is \code{\#f}).}
  16602. \begin{figure}[btp]
  16603. \centering
  16604. \begin{tcolorbox}[colback=white]
  16605. {\if\edition\racketEd
  16606. \begin{tabular}{lll}
  16607. \begin{minipage}{0.27\textwidth}
  16608. \begin{lstlisting}
  16609. #t
  16610. \end{lstlisting}
  16611. \end{minipage}
  16612. &
  16613. $\Rightarrow$
  16614. &
  16615. \begin{minipage}{0.65\textwidth}
  16616. \begin{lstlisting}
  16617. (inject #t Boolean)
  16618. \end{lstlisting}
  16619. \end{minipage}
  16620. \\[2ex]\hline
  16621. \begin{minipage}{0.27\textwidth}
  16622. \begin{lstlisting}
  16623. (+ |$e_1$| |$e_2$|)
  16624. \end{lstlisting}
  16625. \end{minipage}
  16626. &
  16627. $\Rightarrow$
  16628. &
  16629. \begin{minipage}{0.65\textwidth}
  16630. \begin{lstlisting}
  16631. (inject
  16632. (+ (project |$e'_1$| Integer)
  16633. (project |$e'_2$| Integer))
  16634. Integer)
  16635. \end{lstlisting}
  16636. \end{minipage}
  16637. \\[2ex]\hline
  16638. \begin{minipage}{0.27\textwidth}
  16639. \begin{lstlisting}
  16640. (lambda (|$x_1 \ldots$|) |$e$|)
  16641. \end{lstlisting}
  16642. \end{minipage}
  16643. &
  16644. $\Rightarrow$
  16645. &
  16646. \begin{minipage}{0.65\textwidth}
  16647. \begin{lstlisting}
  16648. (inject
  16649. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16650. (Any|$\ldots$|Any -> Any))
  16651. \end{lstlisting}
  16652. \end{minipage}
  16653. \\[2ex]\hline
  16654. \begin{minipage}{0.27\textwidth}
  16655. \begin{lstlisting}
  16656. (|$e_0$| |$e_1 \ldots e_n$|)
  16657. \end{lstlisting}
  16658. \end{minipage}
  16659. &
  16660. $\Rightarrow$
  16661. &
  16662. \begin{minipage}{0.65\textwidth}
  16663. \begin{lstlisting}
  16664. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16665. \end{lstlisting}
  16666. \end{minipage}
  16667. \\[2ex]\hline
  16668. \begin{minipage}{0.27\textwidth}
  16669. \begin{lstlisting}
  16670. (vector-ref |$e_1$| |$e_2$|)
  16671. \end{lstlisting}
  16672. \end{minipage}
  16673. &
  16674. $\Rightarrow$
  16675. &
  16676. \begin{minipage}{0.65\textwidth}
  16677. \begin{lstlisting}
  16678. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16679. \end{lstlisting}
  16680. \end{minipage}
  16681. \\[2ex]\hline
  16682. \begin{minipage}{0.27\textwidth}
  16683. \begin{lstlisting}
  16684. (if |$e_1$| |$e_2$| |$e_3$|)
  16685. \end{lstlisting}
  16686. \end{minipage}
  16687. &
  16688. $\Rightarrow$
  16689. &
  16690. \begin{minipage}{0.65\textwidth}
  16691. \begin{lstlisting}
  16692. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16693. \end{lstlisting}
  16694. \end{minipage}
  16695. \\[2ex]\hline
  16696. \begin{minipage}{0.27\textwidth}
  16697. \begin{lstlisting}
  16698. (eq? |$e_1$| |$e_2$|)
  16699. \end{lstlisting}
  16700. \end{minipage}
  16701. &
  16702. $\Rightarrow$
  16703. &
  16704. \begin{minipage}{0.65\textwidth}
  16705. \begin{lstlisting}
  16706. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16707. \end{lstlisting}
  16708. \end{minipage}
  16709. \\[2ex]\hline
  16710. \begin{minipage}{0.27\textwidth}
  16711. \begin{lstlisting}
  16712. (not |$e_1$|)
  16713. \end{lstlisting}
  16714. \end{minipage}
  16715. &
  16716. $\Rightarrow$
  16717. &
  16718. \begin{minipage}{0.65\textwidth}
  16719. \begin{lstlisting}
  16720. (if (eq? |$e'_1$| (inject #f Boolean))
  16721. (inject #t Boolean) (inject #f Boolean))
  16722. \end{lstlisting}
  16723. \end{minipage}
  16724. \end{tabular}
  16725. \fi}
  16726. {\if\edition\pythonEd
  16727. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16728. \begin{minipage}{0.23\textwidth}
  16729. \begin{lstlisting}
  16730. True
  16731. \end{lstlisting}
  16732. \end{minipage}
  16733. &
  16734. $\Rightarrow$
  16735. &
  16736. \begin{minipage}{0.7\textwidth}
  16737. \begin{lstlisting}
  16738. Inject(True, BoolType())
  16739. \end{lstlisting}
  16740. \end{minipage}
  16741. \\[2ex]\hline
  16742. \begin{minipage}{0.23\textwidth}
  16743. \begin{lstlisting}
  16744. |$e_1$| + |$e_2$|
  16745. \end{lstlisting}
  16746. \end{minipage}
  16747. &
  16748. $\Rightarrow$
  16749. &
  16750. \begin{minipage}{0.7\textwidth}
  16751. \begin{lstlisting}
  16752. Inject(Project(|$e'_1$|, IntType())
  16753. + Project(|$e'_2$|, IntType()),
  16754. IntType())
  16755. \end{lstlisting}
  16756. \end{minipage}
  16757. \\[2ex]\hline
  16758. \begin{minipage}{0.23\textwidth}
  16759. \begin{lstlisting}
  16760. lambda |$x_1 \ldots$|: |$e$|
  16761. \end{lstlisting}
  16762. \end{minipage}
  16763. &
  16764. $\Rightarrow$
  16765. &
  16766. \begin{minipage}{0.7\textwidth}
  16767. \begin{lstlisting}
  16768. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  16769. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16770. \end{lstlisting}
  16771. \end{minipage}
  16772. \\[2ex]\hline
  16773. \begin{minipage}{0.23\textwidth}
  16774. \begin{lstlisting}
  16775. |$e_0$|(|$e_1 \ldots e_n$|)
  16776. \end{lstlisting}
  16777. \end{minipage}
  16778. &
  16779. $\Rightarrow$
  16780. &
  16781. \begin{minipage}{0.7\textwidth}
  16782. \begin{lstlisting}
  16783. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16784. AnyType())), |$e'_1, \ldots, e'_n$|)
  16785. \end{lstlisting}
  16786. \end{minipage}
  16787. \\[2ex]\hline
  16788. \begin{minipage}{0.23\textwidth}
  16789. \begin{lstlisting}
  16790. |$e_1$|[|$e_2$|]
  16791. \end{lstlisting}
  16792. \end{minipage}
  16793. &
  16794. $\Rightarrow$
  16795. &
  16796. \begin{minipage}{0.7\textwidth}
  16797. \begin{lstlisting}
  16798. Call(Name('any_tuple_load'),
  16799. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  16800. \end{lstlisting}
  16801. \end{minipage}
  16802. %% \begin{minipage}{0.23\textwidth}
  16803. %% \begin{lstlisting}
  16804. %% |$e_2$| if |$e_1$| else |$e_3$|
  16805. %% \end{lstlisting}
  16806. %% \end{minipage}
  16807. %% &
  16808. %% $\Rightarrow$
  16809. %% &
  16810. %% \begin{minipage}{0.7\textwidth}
  16811. %% \begin{lstlisting}
  16812. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16813. %% \end{lstlisting}
  16814. %% \end{minipage}
  16815. %% \\[2ex]\hline
  16816. %% \begin{minipage}{0.23\textwidth}
  16817. %% \begin{lstlisting}
  16818. %% (eq? |$e_1$| |$e_2$|)
  16819. %% \end{lstlisting}
  16820. %% \end{minipage}
  16821. %% &
  16822. %% $\Rightarrow$
  16823. %% &
  16824. %% \begin{minipage}{0.7\textwidth}
  16825. %% \begin{lstlisting}
  16826. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16827. %% \end{lstlisting}
  16828. %% \end{minipage}
  16829. %% \\[2ex]\hline
  16830. %% \begin{minipage}{0.23\textwidth}
  16831. %% \begin{lstlisting}
  16832. %% (not |$e_1$|)
  16833. %% \end{lstlisting}
  16834. %% \end{minipage}
  16835. %% &
  16836. %% $\Rightarrow$
  16837. %% &
  16838. %% \begin{minipage}{0.7\textwidth}
  16839. %% \begin{lstlisting}
  16840. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16841. %% (inject #t Boolean) (inject #f Boolean))
  16842. %% \end{lstlisting}
  16843. %% \end{minipage}
  16844. %% \\[2ex]\hline
  16845. \\\hline
  16846. \end{tabular}
  16847. \fi}
  16848. \end{tcolorbox}
  16849. \caption{Cast Insertion}
  16850. \label{fig:compile-r7-Lany}
  16851. \end{figure}
  16852. \section{Reveal Casts}
  16853. \label{sec:reveal-casts-Lany}
  16854. % TODO: define R'_6
  16855. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16856. into a conditional expression that checks whether the value's tag
  16857. matches the target type; if it does, the value is converted to a value
  16858. of the target type by removing the tag; if it does not, the program
  16859. exits.
  16860. %
  16861. {\if\edition\racketEd
  16862. %
  16863. To perform these actions we need a new primitive operation,
  16864. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16865. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16866. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16867. underlying value from a tagged value. The \code{ValueOf} form
  16868. includes the type for the underlying value which is used by the type
  16869. checker. Finally, the \code{Exit} form ends the execution of the
  16870. program.
  16871. %
  16872. \fi}
  16873. %
  16874. {\if\edition\pythonEd
  16875. %
  16876. To perform these actions we need the \code{exit} function (from the C
  16877. standard library) and two new AST classes: \code{TagOf} and
  16878. \code{ValueOf}. The \code{exit} function ends the execution of the
  16879. program. The \code{TagOf} operation retrieves the type tag from a
  16880. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16881. the underlying value from a tagged value. The \code{ValueOf}
  16882. operation includes the type for the underlying value which is used by
  16883. the type checker.
  16884. %
  16885. \fi}
  16886. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16887. \code{Project} can be translated as follows.
  16888. \begin{center}
  16889. \begin{minipage}{1.0\textwidth}
  16890. {\if\edition\racketEd
  16891. \begin{lstlisting}
  16892. (Project |$e$| |$\FType$|)
  16893. |$\Rightarrow$|
  16894. (Let |$\itm{tmp}$| |$e'$|
  16895. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16896. (Int |$\itm{tagof}(\FType)$|)))
  16897. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16898. (Exit)))
  16899. \end{lstlisting}
  16900. \fi}
  16901. {\if\edition\pythonEd
  16902. \begin{lstlisting}
  16903. Project(|$e$|, |$\FType$|)
  16904. |$\Rightarrow$|
  16905. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16906. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16907. [Constant(|$\itm{tagof}(\FType)$|)]),
  16908. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16909. Call(Name('exit'), [])))
  16910. \end{lstlisting}
  16911. \fi}
  16912. \end{minipage}
  16913. \end{center}
  16914. If the target type of the projection is a tuple or function type, then
  16915. there is a bit more work to do. For tuples, check that the length of
  16916. the tuple type matches the length of the tuple. For functions, check
  16917. that the number of parameters in the function type matches the
  16918. function's arity.
  16919. Regarding \code{Inject}, we recommend compiling it to a slightly
  16920. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16921. takes a tag instead of a type.
  16922. \begin{center}
  16923. \begin{minipage}{1.0\textwidth}
  16924. {\if\edition\racketEd
  16925. \begin{lstlisting}
  16926. (Inject |$e$| |$\FType$|)
  16927. |$\Rightarrow$|
  16928. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16929. \end{lstlisting}
  16930. \fi}
  16931. {\if\edition\pythonEd
  16932. \begin{lstlisting}
  16933. Inject(|$e$|, |$\FType$|)
  16934. |$\Rightarrow$|
  16935. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16936. \end{lstlisting}
  16937. \fi}
  16938. \end{minipage}
  16939. \end{center}
  16940. {\if\edition\pythonEd
  16941. %
  16942. The introduction of \code{make\_any} makes it difficult to use
  16943. bidirectional type checking because we no longer have an expected type
  16944. to use for type checking the expression $e'$. Thus, we run into
  16945. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16946. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16947. annotated lambda) whose parameters have type annotations and that
  16948. records the return type.
  16949. %
  16950. \fi}
  16951. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16952. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16953. translation of \code{Project}.}
  16954. {\if\edition\racketEd
  16955. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16956. combine the projection action with the vector operation. Also, the
  16957. read and write operations allow arbitrary expressions for the index so
  16958. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Lany})
  16959. cannot guarantee that the index is within bounds. Thus, we insert code
  16960. to perform bounds checking at runtime. The translation for
  16961. \code{any-vector-ref} is as follows and the other two operations are
  16962. translated in a similar way.
  16963. \begin{center}
  16964. \begin{minipage}{0.95\textwidth}
  16965. \begin{lstlisting}
  16966. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16967. |$\Rightarrow$|
  16968. (Let |$v$| |$e'_1$|
  16969. (Let |$i$| |$e'_2$|
  16970. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16971. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16972. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16973. (Exit))
  16974. (Exit))))
  16975. \end{lstlisting}
  16976. \end{minipage}
  16977. \end{center}
  16978. \fi}
  16979. %
  16980. {\if\edition\pythonEd
  16981. %
  16982. The \code{any\_tuple\_load} operation combines the projection action
  16983. with the load operation. Also, the load operation allows arbitrary
  16984. expressions for the index so the type checker for \LangAny{}
  16985. (Figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  16986. within bounds. Thus, we insert code to perform bounds checking at
  16987. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16988. \begin{lstlisting}
  16989. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16990. |$\Rightarrow$|
  16991. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16992. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16993. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16994. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  16995. Call(Name('exit'), [])),
  16996. Call(Name('exit'), [])))
  16997. \end{lstlisting}
  16998. \fi}
  16999. {\if\edition\pythonEd
  17000. \section{Assignment Conversion}
  17001. \label{sec:convert-assignments-Lany}
  17002. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17003. \code{AnnLambda} AST classes.
  17004. \section{Closure Conversion}
  17005. \label{sec:closure-conversion-Lany}
  17006. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17007. \code{AnnLambda} AST classes.
  17008. \fi}
  17009. \section{Remove Complex Operands}
  17010. \label{sec:rco-Lany}
  17011. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17012. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17013. %
  17014. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17015. complex expressions. Their subexpressions must be atomic.}
  17016. \section{Explicate Control and \LangCAny{}}
  17017. \label{sec:explicate-Lany}
  17018. The output of \code{explicate\_control} is the \LangCAny{} language
  17019. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  17020. %
  17021. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17022. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17023. note that the index argument of \code{vector-ref} and
  17024. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  17025. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  17026. %
  17027. \python{
  17028. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17029. and \code{explicate\_pred} as appropriately to handle the new expressions
  17030. in \LangCAny{}.
  17031. }
  17032. \newcommand{\CanyASTPython}{
  17033. \begin{array}{lcl}
  17034. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17035. &\MID& \key{TagOf}\LP \Atm \RP
  17036. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17037. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17038. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17039. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17040. \end{array}
  17041. }
  17042. \newcommand{\CanyASTRacket}{
  17043. \begin{array}{lcl}
  17044. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17045. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17046. &\MID& \VALUEOF{\Atm}{\FType} \\
  17047. \Tail &::= & \LP\key{Exit}\RP
  17048. \end{array}
  17049. }
  17050. \begin{figure}[tp]
  17051. \begin{tcolorbox}[colback=white]
  17052. \small
  17053. {\if\edition\racketEd
  17054. \[
  17055. \begin{array}{l}
  17056. \gray{\CvarASTRacket} \\ \hline
  17057. \gray{\CifASTRacket} \\ \hline
  17058. \gray{\CloopASTRacket} \\ \hline
  17059. \gray{\CtupASTRacket} \\ \hline
  17060. \gray{\CfunASTRacket} \\ \hline
  17061. \gray{\ClambdaASTRacket} \\ \hline
  17062. \CanyASTRacket \\
  17063. \begin{array}{lcl}
  17064. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17065. \end{array}
  17066. \end{array}
  17067. \]
  17068. \fi}
  17069. {\if\edition\pythonEd
  17070. \[
  17071. \begin{array}{l}
  17072. \gray{\CifASTPython} \\ \hline
  17073. \gray{\CtupASTPython} \\ \hline
  17074. \gray{\CfunASTPython} \\ \hline
  17075. \gray{\ClambdaASTPython} \\ \hline
  17076. \CanyASTPython \\
  17077. \begin{array}{lcl}
  17078. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17079. \end{array}
  17080. \end{array}
  17081. \]
  17082. \fi}
  17083. \end{tcolorbox}
  17084. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  17085. \label{fig:c5-syntax}
  17086. \end{figure}
  17087. \section{Select Instructions}
  17088. \label{sec:select-Lany}
  17089. In the \code{select\_instructions} pass we translate the primitive
  17090. operations on the \ANYTY{} type to x86 instructions that manipulate
  17091. the 3 tag bits of the tagged value. In the following descriptions,
  17092. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17093. of translating $e$ into an x86 argument.
  17094. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17095. We recommend compiling the
  17096. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17097. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17098. shifts the destination to the left by the number of bits specified its
  17099. source argument (in this case $3$, the length of the tag) and it
  17100. preserves the sign of the integer. We use the \key{orq} instruction to
  17101. combine the tag and the value to form the tagged value. \\
  17102. %
  17103. {\if\edition\racketEd
  17104. \begin{lstlisting}
  17105. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17106. |$\Rightarrow$|
  17107. movq |$e'$|, |\itm{lhs'}|
  17108. salq $3, |\itm{lhs'}|
  17109. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17110. \end{lstlisting}
  17111. \fi}
  17112. %
  17113. {\if\edition\pythonEd
  17114. \begin{lstlisting}
  17115. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17116. |$\Rightarrow$|
  17117. movq |$e'$|, |\itm{lhs'}|
  17118. salq $3, |\itm{lhs'}|
  17119. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17120. \end{lstlisting}
  17121. \fi}
  17122. %
  17123. The instruction selection for tuples and procedures is different
  17124. because their is no need to shift them to the left. The rightmost 3
  17125. bits are already zeros so we simply combine the value and the tag
  17126. using \key{orq}. \\
  17127. %
  17128. {\if\edition\racketEd
  17129. \begin{center}
  17130. \begin{minipage}{\textwidth}
  17131. \begin{lstlisting}
  17132. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17133. |$\Rightarrow$|
  17134. movq |$e'$|, |\itm{lhs'}|
  17135. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17136. \end{lstlisting}
  17137. \end{minipage}
  17138. \end{center}
  17139. \fi}
  17140. %
  17141. {\if\edition\pythonEd
  17142. \begin{lstlisting}
  17143. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17144. |$\Rightarrow$|
  17145. movq |$e'$|, |\itm{lhs'}|
  17146. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17147. \end{lstlisting}
  17148. \fi}
  17149. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17150. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17151. operation extracts the type tag from a value of type \ANYTY{}. The
  17152. type tag is the bottom three bits, so we obtain the tag by taking the
  17153. bitwise-and of the value with $111$ ($7$ in decimal).
  17154. %
  17155. {\if\edition\racketEd
  17156. \begin{lstlisting}
  17157. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17158. |$\Rightarrow$|
  17159. movq |$e'$|, |\itm{lhs'}|
  17160. andq $7, |\itm{lhs'}|
  17161. \end{lstlisting}
  17162. \fi}
  17163. %
  17164. {\if\edition\pythonEd
  17165. \begin{lstlisting}
  17166. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17167. |$\Rightarrow$|
  17168. movq |$e'$|, |\itm{lhs'}|
  17169. andq $7, |\itm{lhs'}|
  17170. \end{lstlisting}
  17171. \fi}
  17172. \paragraph{\code{ValueOf}}
  17173. The instructions for \key{ValueOf} also differ depending on whether
  17174. the type $T$ is a pointer (tuple or function) or not (integer or
  17175. Boolean). The following shows the instruction selection for integers
  17176. and Booleans. We produce an untagged value by shifting it to the
  17177. right by 3 bits.
  17178. %
  17179. {\if\edition\racketEd
  17180. \begin{lstlisting}
  17181. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17182. |$\Rightarrow$|
  17183. movq |$e'$|, |\itm{lhs'}|
  17184. sarq $3, |\itm{lhs'}|
  17185. \end{lstlisting}
  17186. \fi}
  17187. %
  17188. {\if\edition\pythonEd
  17189. \begin{lstlisting}
  17190. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17191. |$\Rightarrow$|
  17192. movq |$e'$|, |\itm{lhs'}|
  17193. sarq $3, |\itm{lhs'}|
  17194. \end{lstlisting}
  17195. \fi}
  17196. %
  17197. In the case for tuples and procedures, we zero-out the rightmost 3
  17198. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17199. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17200. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  17201. Finally, we apply \code{andq} with the tagged value to get the desired
  17202. result.
  17203. %
  17204. {\if\edition\racketEd
  17205. \begin{lstlisting}
  17206. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17207. |$\Rightarrow$|
  17208. movq $|$-8$|, |\itm{lhs'}|
  17209. andq |$e'$|, |\itm{lhs'}|
  17210. \end{lstlisting}
  17211. \fi}
  17212. %
  17213. {\if\edition\pythonEd
  17214. \begin{lstlisting}
  17215. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17216. |$\Rightarrow$|
  17217. movq $|$-8$|, |\itm{lhs'}|
  17218. andq |$e'$|, |\itm{lhs'}|
  17219. \end{lstlisting}
  17220. \fi}
  17221. %% \paragraph{Type Predicates} We leave it to the reader to
  17222. %% devise a sequence of instructions to implement the type predicates
  17223. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17224. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17225. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17226. operation combines the effect of \code{ValueOf} with accessing the
  17227. length of a tuple from the tag stored at the zero index of the tuple.
  17228. {\if\edition\racketEd
  17229. \begin{lstlisting}
  17230. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17231. |$\Longrightarrow$|
  17232. movq $|$-8$|, %r11
  17233. andq |$e_1'$|, %r11
  17234. movq 0(%r11), %r11
  17235. andq $126, %r11
  17236. sarq $1, %r11
  17237. movq %r11, |$\itm{lhs'}$|
  17238. \end{lstlisting}
  17239. \fi}
  17240. {\if\edition\pythonEd
  17241. \begin{lstlisting}
  17242. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17243. |$\Longrightarrow$|
  17244. movq $|$-8$|, %r11
  17245. andq |$e_1'$|, %r11
  17246. movq 0(%r11), %r11
  17247. andq $126, %r11
  17248. sarq $1, %r11
  17249. movq %r11, |$\itm{lhs'}$|
  17250. \end{lstlisting}
  17251. \fi}
  17252. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17253. This operation combines the effect of \code{ValueOf} with reading an
  17254. element of the tuple (see
  17255. Section~\ref{sec:select-instructions-gc}). However, the index may be
  17256. an arbitrary atom so instead of computing the offset at compile time,
  17257. we must generate instructions to compute the offset at runtime as
  17258. follows. Note the use of the new instruction \code{imulq}.
  17259. \begin{center}
  17260. \begin{minipage}{0.96\textwidth}
  17261. {\if\edition\racketEd
  17262. \begin{lstlisting}
  17263. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17264. |$\Longrightarrow$|
  17265. movq |$\neg 111$|, %r11
  17266. andq |$e_1'$|, %r11
  17267. movq |$e_2'$|, %rax
  17268. addq $1, %rax
  17269. imulq $8, %rax
  17270. addq %rax, %r11
  17271. movq 0(%r11) |$\itm{lhs'}$|
  17272. \end{lstlisting}
  17273. \fi}
  17274. %
  17275. {\if\edition\pythonEd
  17276. \begin{lstlisting}
  17277. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17278. |$\Longrightarrow$|
  17279. movq $|$-8$|, %r11
  17280. andq |$e_1'$|, %r11
  17281. movq |$e_2'$|, %rax
  17282. addq $1, %rax
  17283. imulq $8, %rax
  17284. addq %rax, %r11
  17285. movq 0(%r11) |$\itm{lhs'}$|
  17286. \end{lstlisting}
  17287. \fi}
  17288. \end{minipage}
  17289. \end{center}
  17290. % $ pacify font lock
  17291. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17292. %% The code generation for
  17293. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17294. %% analogous to the above translation for reading from a tuple.
  17295. \section{Register Allocation for \LangAny{}}
  17296. \label{sec:register-allocation-Lany}
  17297. \index{subject}{register allocation}
  17298. There is an interesting interaction between tagged values and garbage
  17299. collection that has an impact on register allocation. A variable of
  17300. type \ANYTY{} might refer to a tuple and therefore it might be a root
  17301. that needs to be inspected and copied during garbage collection. Thus,
  17302. we need to treat variables of type \ANYTY{} in a similar way to
  17303. variables of tuple type for purposes of register allocation. In
  17304. particular,
  17305. \begin{itemize}
  17306. \item If a variable of type \ANYTY{} is live during a function call,
  17307. then it must be spilled. This can be accomplished by changing
  17308. \code{build\_interference} to mark all variables of type \ANYTY{}
  17309. that are live after a \code{callq} as interfering with all the
  17310. registers.
  17311. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17312. the root stack instead of the normal procedure call stack.
  17313. \end{itemize}
  17314. Another concern regarding the root stack is that the garbage collector
  17315. needs to differentiate between (1) plain old pointers to tuples, (2) a
  17316. tagged value that points to a tuple, and (3) a tagged value that is
  17317. not a tuple. We enable this differentiation by choosing not to use the
  17318. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17319. reserved for identifying plain old pointers to tuples. That way, if
  17320. one of the first three bits is set, then we have a tagged value and
  17321. inspecting the tag can differentiate between tuples ($010$) and the
  17322. other kinds of values.
  17323. %% \begin{exercise}\normalfont
  17324. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17325. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17326. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17327. %% compiler on these new programs and all of your previously created test
  17328. %% programs.
  17329. %% \end{exercise}
  17330. \begin{exercise}\normalfont\normalsize
  17331. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17332. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17333. by removing type annotations. Add 5 more tests programs that
  17334. specifically rely on the language being dynamically typed. That is,
  17335. they should not be legal programs in a statically typed language, but
  17336. nevertheless, they should be valid \LangDyn{} programs that run to
  17337. completion without error.
  17338. \end{exercise}
  17339. \begin{figure}[p]
  17340. \begin{tcolorbox}[colback=white]
  17341. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17342. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17343. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  17344. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  17345. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  17346. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17347. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  17348. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  17349. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  17350. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  17351. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  17352. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  17353. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  17354. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  17355. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17356. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17357. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17358. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17359. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17360. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17361. \path[->,bend left=15] (Lfun) edge [above] node
  17362. {\ttfamily\footnotesize shrink} (Lfun-2);
  17363. \path[->,bend left=15] (Lfun-2) edge [above] node
  17364. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17365. \path[->,bend left=15] (Lfun-3) edge [above] node
  17366. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17367. \path[->,bend left=15] (Lfun-4) edge [left] node
  17368. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17369. \path[->,bend left=15] (Lfun-5) edge [below] node
  17370. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17371. \path[->,bend left=15] (Lfun-6) edge [below] node
  17372. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  17373. \path[->,bend right=15] (Lfun-7) edge [above] node
  17374. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17375. \path[->,bend right=15] (F1-2) edge [above] node
  17376. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17377. \path[->,bend right=15] (F1-3) edge [right] node
  17378. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17379. \path[->,bend right=15] (F1-4) edge [below] node
  17380. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17381. \path[->,bend left=15] (F1-5) edge [above] node
  17382. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  17383. \path[->,bend left=15] (F1-6) edge [right] node
  17384. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17385. \path[->,bend left=15] (C3-2) edge [left] node
  17386. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17387. \path[->,bend right=15] (x86-2) edge [left] node
  17388. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17389. \path[->,bend right=15] (x86-2-1) edge [below] node
  17390. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17391. \path[->,bend right=15] (x86-2-2) edge [left] node
  17392. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17393. \path[->,bend left=15] (x86-3) edge [above] node
  17394. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17395. \path[->,bend left=15] (x86-4) edge [right] node
  17396. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  17397. \end{tikzpicture}
  17398. \end{tcolorbox}
  17399. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17400. \label{fig:Ldyn-passes}
  17401. \end{figure}
  17402. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17403. for the compilation of \LangDyn{}.
  17404. % Further Reading
  17405. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17406. %% {\if\edition\pythonEd
  17407. %% \chapter{Objects}
  17408. %% \label{ch:Lobject}
  17409. %% \index{subject}{objects}
  17410. %% \index{subject}{classes}
  17411. %% \fi}
  17412. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17413. \chapter{Gradual Typing}
  17414. \label{ch:Lgrad}
  17415. \index{subject}{gradual typing}
  17416. This chapter studies a language, \LangGrad{}, in which the programmer
  17417. can choose between static and dynamic type checking in different parts
  17418. of a program, thereby mixing the statically typed \LangLam{} language
  17419. with the dynamically typed \LangDyn{}. There are several approaches to
  17420. mixing static and dynamic typing, including multi-language
  17421. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17422. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17423. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17424. programmer controls the amount of static versus dynamic checking by
  17425. adding or removing type annotations on parameters and
  17426. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17427. %
  17428. The concrete syntax of \LangGrad{} is defined in
  17429. Figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is
  17430. defined in Figure~\ref{fig:Lgrad-syntax}. The main syntactic
  17431. difference between \LangLam{} and \LangGrad{} is that type annotations
  17432. are optional, which is specified in the grammar using the \Param{} and
  17433. \itm{ret} non-terminals. In the abstract syntax, type annotations are
  17434. not optional but we use the \CANYTY{} type when a type annotation is
  17435. absent.
  17436. \newcommand{\LgradGrammarRacket}{
  17437. \begin{array}{lcl}
  17438. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17439. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17440. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17441. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17442. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17443. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17444. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17445. \end{array}
  17446. }
  17447. \newcommand{\LgradASTRacket}{
  17448. \begin{array}{lcl}
  17449. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  17450. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17451. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17452. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17453. \itm{op} &::=& \code{procedure-arity} \\
  17454. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17455. \end{array}
  17456. }
  17457. \newcommand{\LgradGrammarPython}{
  17458. \begin{array}{lcl}
  17459. \Type &::=& \key{Any}
  17460. \MID \key{int}
  17461. \MID \key{bool}
  17462. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17463. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17464. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17465. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17466. \MID \CARITY{\Exp} \\
  17467. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17468. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17469. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17470. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17471. \end{array}
  17472. }
  17473. \newcommand{\LgradASTPython}{
  17474. \begin{array}{lcl}
  17475. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17476. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17477. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17478. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17479. &\MID& \ARITY{\Exp} \\
  17480. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17481. \MID \RETURN{\Exp} \\
  17482. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17483. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17484. \end{array}
  17485. }
  17486. \begin{figure}[tp]
  17487. \centering
  17488. \begin{tcolorbox}[colback=white]
  17489. \small
  17490. {\if\edition\racketEd
  17491. \[
  17492. \begin{array}{l}
  17493. \gray{\LintGrammarRacket{}} \\ \hline
  17494. \gray{\LvarGrammarRacket{}} \\ \hline
  17495. \gray{\LifGrammarRacket{}} \\ \hline
  17496. \gray{\LwhileGrammarRacket} \\ \hline
  17497. \gray{\LtupGrammarRacket} \\ \hline
  17498. \LgradGrammarRacket \\
  17499. \begin{array}{lcl}
  17500. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17501. \end{array}
  17502. \end{array}
  17503. \]
  17504. \fi}
  17505. {\if\edition\pythonEd
  17506. \[
  17507. \begin{array}{l}
  17508. \gray{\LintGrammarPython{}} \\ \hline
  17509. \gray{\LvarGrammarPython{}} \\ \hline
  17510. \gray{\LifGrammarPython{}} \\ \hline
  17511. \gray{\LwhileGrammarPython} \\ \hline
  17512. \gray{\LtupGrammarPython} \\ \hline
  17513. \LgradGrammarPython \\
  17514. \begin{array}{lcl}
  17515. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17516. \end{array}
  17517. \end{array}
  17518. \]
  17519. \fi}
  17520. \end{tcolorbox}
  17521. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  17522. \label{fig:Lgrad-concrete-syntax}
  17523. \end{figure}
  17524. \begin{figure}[tp]
  17525. \centering
  17526. \begin{tcolorbox}[colback=white]
  17527. \small
  17528. {\if\edition\racketEd
  17529. \[
  17530. \begin{array}{l}
  17531. \gray{\LintOpAST} \\ \hline
  17532. \gray{\LvarASTRacket{}} \\ \hline
  17533. \gray{\LifASTRacket{}} \\ \hline
  17534. \gray{\LwhileASTRacket{}} \\ \hline
  17535. \gray{\LtupASTRacket{}} \\ \hline
  17536. \LgradASTRacket \\
  17537. \begin{array}{lcl}
  17538. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17539. \end{array}
  17540. \end{array}
  17541. \]
  17542. \fi}
  17543. {\if\edition\pythonEd
  17544. \[
  17545. \begin{array}{l}
  17546. \gray{\LintASTPython{}} \\ \hline
  17547. \gray{\LvarASTPython{}} \\ \hline
  17548. \gray{\LifASTPython{}} \\ \hline
  17549. \gray{\LwhileASTPython} \\ \hline
  17550. \gray{\LtupASTPython} \\ \hline
  17551. \LgradASTPython \\
  17552. \begin{array}{lcl}
  17553. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17554. \end{array}
  17555. \end{array}
  17556. \]
  17557. \fi}
  17558. \end{tcolorbox}
  17559. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  17560. \label{fig:Lgrad-syntax}
  17561. \end{figure}
  17562. Both the type checker and the interpreter for \LangGrad{} require some
  17563. interesting changes to enable gradual typing, which we discuss in the
  17564. next two sections.
  17565. % TODO: more road map -Jeremy
  17566. %\clearpage
  17567. \section{Type Checking \LangGrad{}}
  17568. \label{sec:gradual-type-check}
  17569. We begin by discussing the type checking of a partially-typed variant
  17570. of the \code{map} example from Chapter~\ref{ch:Lfun}, shown in
  17571. Figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17572. statically typed, so there is nothing special happening there with
  17573. respect to type checking. On the other hand, the \code{inc} function
  17574. does not have type annotations, so parameter \code{x} is given the
  17575. type \CANYTY{} and the return type of \code{inc} is \CANYTY{}. Now
  17576. consider the \code{+} operator inside \code{inc}. It expects both
  17577. arguments to have type \INTTY{}, but its first argument \code{x}
  17578. has type \CANYTY{}. In a gradually typed language, such differences
  17579. are allowed so long as the types are \emph{consistent}, that is, they
  17580. are equal except in places where there is an \CANYTY{} type. That is,
  17581. the type \CANYTY{} is consistent with every other type.
  17582. Figure~\ref{fig:consistent} defines the
  17583. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17584. %
  17585. So the type checker allows the \code{+} operator to be applied
  17586. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17587. %
  17588. Next consider the call to the \code{map} function in
  17589. Figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17590. tuple. The \code{inc} function has type
  17591. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17592. but parameter \code{f} of \code{map} has type
  17593. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17594. The type checker for \LangGrad{} accepts this call because the two types are
  17595. consistent.
  17596. \begin{figure}[btp]
  17597. % gradual_test_9.rkt
  17598. \begin{tcolorbox}[colback=white]
  17599. {\if\edition\racketEd
  17600. \begin{lstlisting}
  17601. (define (map [f : (Integer -> Integer)]
  17602. [v : (Vector Integer Integer)])
  17603. : (Vector Integer Integer)
  17604. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17605. (define (inc x) (+ x 1))
  17606. (vector-ref (map inc (vector 0 41)) 1)
  17607. \end{lstlisting}
  17608. \fi}
  17609. {\if\edition\pythonEd
  17610. \begin{lstlisting}
  17611. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17612. return f(v[0]), f(v[1])
  17613. def inc(x):
  17614. return x + 1
  17615. t = map(inc, (0, 41))
  17616. print(t[1])
  17617. \end{lstlisting}
  17618. \fi}
  17619. \end{tcolorbox}
  17620. \caption{A partially-typed version of the \code{map} example.}
  17621. \label{fig:gradual-map}
  17622. \end{figure}
  17623. \begin{figure}[tbp]
  17624. \begin{tcolorbox}[colback=white]
  17625. {\if\edition\racketEd
  17626. \begin{lstlisting}
  17627. (define/public (consistent? t1 t2)
  17628. (match* (t1 t2)
  17629. [('Integer 'Integer) #t]
  17630. [('Boolean 'Boolean) #t]
  17631. [('Void 'Void) #t]
  17632. [('Any t2) #t]
  17633. [(t1 'Any) #t]
  17634. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17635. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17636. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17637. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17638. (consistent? rt1 rt2))]
  17639. [(other wise) #f]))
  17640. \end{lstlisting}
  17641. \fi}
  17642. {\if\edition\pythonEd
  17643. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17644. def consistent(self, t1, t2):
  17645. match (t1, t2):
  17646. case (AnyType(), _):
  17647. return True
  17648. case (_, AnyType()):
  17649. return True
  17650. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17651. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17652. case (TupleType(ts1), TupleType(ts2)):
  17653. return all(map(self.consistent, ts1, ts2))
  17654. case (_, _):
  17655. return t1 == t2
  17656. \end{lstlisting}
  17657. \fi}
  17658. \end{tcolorbox}
  17659. \caption{The consistency method on types.}
  17660. \label{fig:consistent}
  17661. \end{figure}
  17662. It is also helpful to consider how gradual typing handles programs with an
  17663. error, such as applying \code{map} to a function that sometimes
  17664. returns a Boolean, as shown in Figure~\ref{fig:map-maybe_inc}. The
  17665. type checker for \LangGrad{} accepts this program because the type of
  17666. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17667. \code{map}, that is,
  17668. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17669. is consistent with
  17670. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17671. One might say that a gradual type checker is optimistic in that it
  17672. accepts programs that might execute without a runtime type error.
  17673. %
  17674. The type checker for \LangGrad{} is defined in
  17675. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17676. and \ref{fig:type-check-Lgradual-3}.
  17677. %% \begin{figure}[tp]
  17678. %% \centering
  17679. %% \fbox{
  17680. %% \begin{minipage}{0.96\textwidth}
  17681. %% \small
  17682. %% \[
  17683. %% \begin{array}{lcl}
  17684. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17685. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17686. %% \end{array}
  17687. %% \]
  17688. %% \end{minipage}
  17689. %% }
  17690. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (Figure~\ref{fig:Lwhile-syntax}).}
  17691. %% \label{fig:Lgrad-prime-syntax}
  17692. %% \end{figure}
  17693. \begin{figure}[tbp]
  17694. \begin{tcolorbox}[colback=white]
  17695. {\if\edition\racketEd
  17696. \begin{lstlisting}
  17697. (define (map [f : (Integer -> Integer)]
  17698. [v : (Vector Integer Integer)])
  17699. : (Vector Integer Integer)
  17700. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17701. (define (inc x) (+ x 1))
  17702. (define (true) #t)
  17703. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17704. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17705. \end{lstlisting}
  17706. \fi}
  17707. {\if\edition\pythonEd
  17708. \begin{lstlisting}
  17709. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17710. return f(v[0]), f(v[1])
  17711. def inc(x):
  17712. return x + 1
  17713. def true():
  17714. return True
  17715. def maybe_inc(x):
  17716. return inc(x) if input_int() == 0 else true()
  17717. t = map(maybe_inc, (0, 41))
  17718. print( t[1] )
  17719. \end{lstlisting}
  17720. \fi}
  17721. \end{tcolorbox}
  17722. \caption{A variant of the \code{map} example with an error.}
  17723. \label{fig:map-maybe_inc}
  17724. \end{figure}
  17725. Running this program with input \code{1} triggers an
  17726. error when the \code{maybe\_inc} function returns
  17727. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  17728. performs checking at runtime to ensure the integrity of the static
  17729. types, such as the
  17730. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  17731. annotation on
  17732. parameter \code{f} of \code{map}.
  17733. Here we give a preview of how the runtime checking is accomplished;
  17734. the following sections provide the details.
  17735. The runtime checking is carried out by a new \code{Cast} AST node that
  17736. is generate in a new pass named \code{cast\_insert}. The output of
  17737. \code{cast\_insert} is a program in the \LangCast{} language, which
  17738. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  17739. %
  17740. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  17741. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  17742. inserted every time the type checker sees two types that are
  17743. consistent but not equal. In the \code{inc} function, \code{x} is
  17744. cast to \INTTY{} and the result of the \code{+} is cast to
  17745. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  17746. is cast from
  17747. \racket{\code{(Any -> Any)}}
  17748. \python{\code{Callable[[Any], Any]}}
  17749. to
  17750. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17751. %
  17752. In the next section we see how to interpret the \code{Cast} node.
  17753. \begin{figure}[btp]
  17754. \begin{tcolorbox}[colback=white]
  17755. {\if\edition\racketEd
  17756. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17757. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17758. : (Vector Integer Integer)
  17759. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17760. (define (inc [x : Any]) : Any
  17761. (cast (+ (cast x Any Integer) 1) Integer Any))
  17762. (define (true) : Any (cast #t Boolean Any))
  17763. (define (maybe_inc [x : Any]) : Any
  17764. (if (eq? 0 (read)) (inc x) (true)))
  17765. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  17766. (vector 0 41)) 0)
  17767. \end{lstlisting}
  17768. \fi}
  17769. {\if\edition\pythonEd
  17770. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17771. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17772. return f(v[0]), f(v[1])
  17773. def inc(x : Any) -> Any:
  17774. return Cast(Cast(x, Any, int) + 1, int, Any)
  17775. def true() -> Any:
  17776. return Cast(True, bool, Any)
  17777. def maybe_inc(x : Any) -> Any:
  17778. return inc(x) if input_int() == 0 else true()
  17779. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  17780. (0, 41))
  17781. print(t[1])
  17782. \end{lstlisting}
  17783. \fi}
  17784. \end{tcolorbox}
  17785. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  17786. and \code{maybe\_inc} example.}
  17787. \label{fig:map-cast}
  17788. \end{figure}
  17789. {\if\edition\pythonEd
  17790. \begin{figure}[tbp]
  17791. \begin{tcolorbox}[colback=white]
  17792. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17793. class TypeCheckLgrad(TypeCheckLlambda):
  17794. def type_check_exp(self, e, env) -> Type:
  17795. match e:
  17796. case Name(id):
  17797. return env[id]
  17798. case Constant(value) if isinstance(value, bool):
  17799. return BoolType()
  17800. case Constant(value) if isinstance(value, int):
  17801. return IntType()
  17802. case Call(Name('input_int'), []):
  17803. return IntType()
  17804. case BinOp(left, op, right):
  17805. left_type = self.type_check_exp(left, env)
  17806. self.check_consistent(left_type, IntType(), left)
  17807. right_type = self.type_check_exp(right, env)
  17808. self.check_consistent(right_type, IntType(), right)
  17809. return IntType()
  17810. case IfExp(test, body, orelse):
  17811. test_t = self.type_check_exp(test, env)
  17812. self.check_consistent(test_t, BoolType(), test)
  17813. body_t = self.type_check_exp(body, env)
  17814. orelse_t = self.type_check_exp(orelse, env)
  17815. self.check_consistent(body_t, orelse_t, e)
  17816. return self.join_types(body_t, orelse_t)
  17817. case Call(func, args):
  17818. func_t = self.type_check_exp(func, env)
  17819. args_t = [self.type_check_exp(arg, env) for arg in args]
  17820. match func_t:
  17821. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  17822. for (arg_t, param_t) in zip(args_t, params_t):
  17823. self.check_consistent(param_t, arg_t, e)
  17824. return return_t
  17825. case AnyType():
  17826. return AnyType()
  17827. case _:
  17828. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  17829. ...
  17830. case _:
  17831. raise Exception('type_check_exp: unexpected ' + repr(e))
  17832. \end{lstlisting}
  17833. \end{tcolorbox}
  17834. \caption{Type checking expressions in the \LangGrad{} language.}
  17835. \label{fig:type-check-Lgradual-1}
  17836. \end{figure}
  17837. \begin{figure}[tbp]
  17838. \begin{tcolorbox}[colback=white]
  17839. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17840. def check_exp(self, e, expected_ty, env):
  17841. match e:
  17842. case Lambda(params, body):
  17843. match expected_ty:
  17844. case FunctionType(params_t, return_t):
  17845. new_env = env.copy().update(zip(params, params_t))
  17846. e.has_type = expected_ty
  17847. body_ty = self.type_check_exp(body, new_env)
  17848. self.check_consistent(body_ty, return_t)
  17849. case AnyType():
  17850. new_env = env.copy().update((p, AnyType()) for p in params)
  17851. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  17852. body_ty = self.type_check_exp(body, new_env)
  17853. case _:
  17854. raise Exception('lambda does not have type ' + str(expected_ty))
  17855. case _:
  17856. e_ty = self.type_check_exp(e, env)
  17857. self.check_consistent(e_ty, expected_ty, e)
  17858. \end{lstlisting}
  17859. \end{tcolorbox}
  17860. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  17861. \label{fig:type-check-Lgradual-2}
  17862. \end{figure}
  17863. \begin{figure}[tbp]
  17864. \begin{tcolorbox}[colback=white]
  17865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17866. def type_check_stmt(self, s, env, return_type):
  17867. match s:
  17868. case Assign([Name(id)], value):
  17869. value_ty = self.type_check_exp(value, env)
  17870. if id in env:
  17871. self.check_consistent(env[id], value_ty, value)
  17872. else:
  17873. env[id] = value_ty
  17874. ...
  17875. case _:
  17876. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  17877. def type_check_stmts(self, ss, env, return_type):
  17878. for s in ss:
  17879. self.type_check_stmt(s, env, return_type)
  17880. \end{lstlisting}
  17881. \end{tcolorbox}
  17882. \caption{Type checking statements in the \LangGrad{} language.}
  17883. \label{fig:type-check-Lgradual-3}
  17884. \end{figure}
  17885. \begin{figure}[tbp]
  17886. \begin{tcolorbox}[colback=white]
  17887. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17888. def join_types(self, t1, t2):
  17889. match (t1, t2):
  17890. case (AnyType(), _):
  17891. return t2
  17892. case (_, AnyType()):
  17893. return t1
  17894. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17895. return FunctionType(list(map(self.join_types, ps1, ps2)),
  17896. self.join_types(rt1,rt2))
  17897. case (TupleType(ts1), TupleType(ts2)):
  17898. return TupleType(list(map(self.join_types, ts1, ts2)))
  17899. case (_, _):
  17900. return t1
  17901. def check_consistent(self, t1, t2, e):
  17902. if not self.consistent(t1, t2):
  17903. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  17904. + ' in ' + repr(e))
  17905. \end{lstlisting}
  17906. \end{tcolorbox}
  17907. \caption{Auxiliary methods for type checking \LangGrad{}.}
  17908. \label{fig:type-check-Lgradual-aux}
  17909. \end{figure}
  17910. \fi}
  17911. {\if\edition\racketEd
  17912. \begin{figure}[tbp]
  17913. \begin{tcolorbox}[colback=white]
  17914. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17915. (define type-check-gradual-class
  17916. (class type-check-Llambda-class
  17917. (super-new)
  17918. (inherit operator-types type-predicates)
  17919. (define/override (type-check-exp env)
  17920. (lambda (e)
  17921. (define recur (type-check-exp env))
  17922. (match e
  17923. [(Prim 'vector-length (list e1))
  17924. (define-values (e1^ t) (recur e1))
  17925. (match t
  17926. [`(Vector ,ts ...)
  17927. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17928. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17929. [(Prim 'vector-ref (list e1 e2))
  17930. (define-values (e1^ t1) (recur e1))
  17931. (define-values (e2^ t2) (recur e2))
  17932. (check-consistent? t2 'Integer e)
  17933. (match t1
  17934. [`(Vector ,ts ...)
  17935. (match e2^
  17936. [(Int i)
  17937. (unless (and (0 . <= . i) (i . < . (length ts)))
  17938. (error 'type-check "invalid index ~a in ~a" i e))
  17939. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17940. [else (define e1^^ (make-cast e1^ t1 'Any))
  17941. (define e2^^ (make-cast e2^ t2 'Integer))
  17942. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17943. ['Any
  17944. (define e2^^ (make-cast e2^ t2 'Integer))
  17945. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17946. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17947. [(Prim 'vector-set! (list e1 e2 e3) )
  17948. (define-values (e1^ t1) (recur e1))
  17949. (define-values (e2^ t2) (recur e2))
  17950. (define-values (e3^ t3) (recur e3))
  17951. (check-consistent? t2 'Integer e)
  17952. (match t1
  17953. [`(Vector ,ts ...)
  17954. (match e2^
  17955. [(Int i)
  17956. (unless (and (0 . <= . i) (i . < . (length ts)))
  17957. (error 'type-check "invalid index ~a in ~a" i e))
  17958. (check-consistent? (list-ref ts i) t3 e)
  17959. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17960. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17961. [else
  17962. (define e1^^ (make-cast e1^ t1 'Any))
  17963. (define e2^^ (make-cast e2^ t2 'Integer))
  17964. (define e3^^ (make-cast e3^ t3 'Any))
  17965. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17966. ['Any
  17967. (define e2^^ (make-cast e2^ t2 'Integer))
  17968. (define e3^^ (make-cast e3^ t3 'Any))
  17969. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17970. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17971. \end{lstlisting}
  17972. \end{tcolorbox}
  17973. \caption{Type checker for the \LangGrad{} language, part 1.}
  17974. \label{fig:type-check-Lgradual-1}
  17975. \end{figure}
  17976. \begin{figure}[tbp]
  17977. \begin{tcolorbox}[colback=white]
  17978. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17979. [(Prim 'eq? (list e1 e2))
  17980. (define-values (e1^ t1) (recur e1))
  17981. (define-values (e2^ t2) (recur e2))
  17982. (check-consistent? t1 t2 e)
  17983. (define T (meet t1 t2))
  17984. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17985. 'Boolean)]
  17986. [(Prim 'not (list e1))
  17987. (define-values (e1^ t1) (recur e1))
  17988. (match t1
  17989. ['Any
  17990. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17991. (Bool #t) (Bool #f)))]
  17992. [else
  17993. (define-values (t-ret new-es^)
  17994. (type-check-op 'not (list t1) (list e1^) e))
  17995. (values (Prim 'not new-es^) t-ret)])]
  17996. [(Prim 'and (list e1 e2))
  17997. (recur (If e1 e2 (Bool #f)))]
  17998. [(Prim 'or (list e1 e2))
  17999. (define tmp (gensym 'tmp))
  18000. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18001. [(Prim op es)
  18002. #:when (not (set-member? explicit-prim-ops op))
  18003. (define-values (new-es ts)
  18004. (for/lists (exprs types) ([e es])
  18005. (recur e)))
  18006. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  18007. (values (Prim op new-es^) t-ret)]
  18008. [(If e1 e2 e3)
  18009. (define-values (e1^ T1) (recur e1))
  18010. (define-values (e2^ T2) (recur e2))
  18011. (define-values (e3^ T3) (recur e3))
  18012. (check-consistent? T2 T3 e)
  18013. (match T1
  18014. ['Boolean
  18015. (define Tif (join T2 T3))
  18016. (values (If e1^ (make-cast e2^ T2 Tif)
  18017. (make-cast e3^ T3 Tif)) Tif)]
  18018. ['Any
  18019. (define Tif (meet T2 T3))
  18020. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  18021. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  18022. Tif)]
  18023. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  18024. [(HasType e1 T)
  18025. (define-values (e1^ T1) (recur e1))
  18026. (check-consistent? T1 T)
  18027. (values (make-cast e1^ T1 T) T)]
  18028. [(SetBang x e1)
  18029. (define-values (e1^ T1) (recur e1))
  18030. (define varT (dict-ref env x))
  18031. (check-consistent? T1 varT e)
  18032. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  18033. [(WhileLoop e1 e2)
  18034. (define-values (e1^ T1) (recur e1))
  18035. (check-consistent? T1 'Boolean e)
  18036. (define-values (e2^ T2) ((type-check-exp env) e2))
  18037. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  18038. \end{lstlisting}
  18039. \end{tcolorbox}
  18040. \caption{Type checker for the \LangGrad{} language, part 2.}
  18041. \label{fig:type-check-Lgradual-2}
  18042. \end{figure}
  18043. \begin{figure}[tbp]
  18044. \begin{tcolorbox}[colback=white]
  18045. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18046. [(Apply e1 e2s)
  18047. (define-values (e1^ T1) (recur e1))
  18048. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18049. (match T1
  18050. [`(,T1ps ... -> ,T1rt)
  18051. (for ([T2 T2s] [Tp T1ps])
  18052. (check-consistent? T2 Tp e))
  18053. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  18054. (make-cast e2 src tgt)))
  18055. (values (Apply e1^ e2s^^) T1rt)]
  18056. [`Any
  18057. (define e1^^ (make-cast e1^ 'Any
  18058. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  18059. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  18060. (make-cast e2 src 'Any)))
  18061. (values (Apply e1^^ e2s^^) 'Any)]
  18062. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18063. [(Lambda params Tr e1)
  18064. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18065. (match p
  18066. [`[,x : ,T] (values x T)]
  18067. [(? symbol? x) (values x 'Any)])))
  18068. (define-values (e1^ T1)
  18069. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18070. (check-consistent? Tr T1 e)
  18071. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  18072. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  18073. [else ((super type-check-exp env) e)]
  18074. )))
  18075. \end{lstlisting}
  18076. \end{tcolorbox}
  18077. \caption{Type checker for the \LangGrad{} language, part 3.}
  18078. \label{fig:type-check-Lgradual-3}
  18079. \end{figure}
  18080. \begin{figure}[tbp]
  18081. \begin{tcolorbox}[colback=white]
  18082. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18083. (define/public (join t1 t2)
  18084. (match* (t1 t2)
  18085. [('Integer 'Integer) 'Integer]
  18086. [('Boolean 'Boolean) 'Boolean]
  18087. [('Void 'Void) 'Void]
  18088. [('Any t2) t2]
  18089. [(t1 'Any) t1]
  18090. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18091. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18092. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18093. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18094. -> ,(join rt1 rt2))]))
  18095. (define/public (meet t1 t2)
  18096. (match* (t1 t2)
  18097. [('Integer 'Integer) 'Integer]
  18098. [('Boolean 'Boolean) 'Boolean]
  18099. [('Void 'Void) 'Void]
  18100. [('Any t2) 'Any]
  18101. [(t1 'Any) 'Any]
  18102. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18103. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18104. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18105. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18106. -> ,(meet rt1 rt2))]))
  18107. (define/public (make-cast e src tgt)
  18108. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  18109. (define/public (check-consistent? t1 t2 e)
  18110. (unless (consistent? t1 t2)
  18111. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18112. (define/override (type-check-op op arg-types args e)
  18113. (match (dict-ref (operator-types) op)
  18114. [`(,param-types . ,return-type)
  18115. (for ([at arg-types] [pt param-types])
  18116. (check-consistent? at pt e))
  18117. (values return-type
  18118. (for/list ([e args] [s arg-types] [t param-types])
  18119. (make-cast e s t)))]
  18120. [else (error 'type-check-op "unrecognized ~a" op)]))
  18121. (define explicit-prim-ops
  18122. (set-union
  18123. (type-predicates)
  18124. (set 'procedure-arity 'eq?
  18125. 'vector 'vector-length 'vector-ref 'vector-set!
  18126. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18127. (define/override (fun-def-type d)
  18128. (match d
  18129. [(Def f params rt info body)
  18130. (define ps
  18131. (for/list ([p params])
  18132. (match p
  18133. [`[,x : ,T] T]
  18134. [(? symbol?) 'Any]
  18135. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18136. `(,@ps -> ,rt)]
  18137. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  18138. \end{lstlisting}
  18139. \end{tcolorbox}
  18140. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18141. \label{fig:type-check-Lgradual-aux}
  18142. \end{figure}
  18143. \fi}
  18144. \clearpage
  18145. \section{Interpreting \LangCast{}}
  18146. \label{sec:interp-casts}
  18147. The runtime behavior of casts involving simple types such as
  18148. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18149. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18150. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18151. tagged value (Figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18152. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18153. operator, that is, by checking the value's tag and either retrieving
  18154. the underlying integer or signalling an error if the tag is not the
  18155. one for integers (Figure~\ref{fig:interp-Lany-aux}).
  18156. %
  18157. Things get more interesting for casts involving function, tuple, or array
  18158. types.
  18159. Consider the cast of the function \code{maybe\_inc} from
  18160. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18161. to
  18162. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18163. in Figure~\ref{fig:map-maybe_inc}.
  18164. When the \code{maybe\_inc} function flows through
  18165. this cast at runtime, we don't know whether it will return
  18166. an integer, as that depends on the input from the user.
  18167. The \LangCast{} interpreter therefore delays the checking
  18168. of the cast until the function is applied. To do so it
  18169. wraps \code{maybe\_inc} in a new function that casts its parameter
  18170. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18171. casts the return value from \CANYTY{} to \INTTY{}.
  18172. {\if\edition\pythonEd
  18173. %
  18174. There are further complicatons regarding casts on mutable data
  18175. such as the \code{list} type introduced in
  18176. the challenge assignment of Section~\ref{sec:arrays}.
  18177. %
  18178. \fi}
  18179. %
  18180. Consider the example in Figure~\ref{fig:map-bang} that
  18181. defines a partially-typed version of \code{map} whose parameter
  18182. \code{v} has type
  18183. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18184. and that updates \code{v} in place
  18185. instead of returning a new tuple. So we name this function
  18186. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18187. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18188. cast from
  18189. \racket{\code{(Vector Integer Integer)}}
  18190. \python{\code{list[int]}}
  18191. to
  18192. \racket{\code{(Vector Any Any)}}
  18193. \python{\code{list[Any]}}.
  18194. A naive way for the \LangCast{} interpreter to cast between
  18195. \racket{tuple}\python{array} types would be a build a new
  18196. \racket{tuple}\python{array}
  18197. whose elements are the result
  18198. of casting each of the original elements to the appropriate target
  18199. type.
  18200. However, this approach is not valid for mutable data structures.
  18201. In the example of Figure~\ref{fig:map-bang},
  18202. if the cast created a new \racket{tuple}\python{array}, then the updates inside of
  18203. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18204. the original one.
  18205. \begin{figure}[tbp]
  18206. \begin{tcolorbox}[colback=white]
  18207. % gradual_test_11.rkt
  18208. {\if\edition\racketEd
  18209. \begin{lstlisting}
  18210. (define (map_inplace [f : (Any -> Any)]
  18211. [v : (Vector Any Any)]) : Void
  18212. (begin
  18213. (vector-set! v 0 (f (vector-ref v 0)))
  18214. (vector-set! v 1 (f (vector-ref v 1)))))
  18215. (define (inc x) (+ x 1))
  18216. (let ([v (vector 0 41)])
  18217. (begin (map_inplace inc v) (vector-ref v 1)))
  18218. \end{lstlisting}
  18219. \fi}
  18220. {\if\edition\pythonEd
  18221. \begin{lstlisting}
  18222. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18223. i = 0
  18224. while i != len(v):
  18225. v[i] = f(v[i])
  18226. i = i + 1
  18227. def inc(x : int) -> int:
  18228. return x + 1
  18229. v = [0, 41]
  18230. map_inplace(inc, v)
  18231. print( v[1] )
  18232. \end{lstlisting}
  18233. \fi}
  18234. \end{tcolorbox}
  18235. \caption{An example involving casts on arrays.}
  18236. \label{fig:map-bang}
  18237. \end{figure}
  18238. Instead the interpreter needs to create a new kind of value, a
  18239. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18240. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18241. and then applies a
  18242. cast to the resulting value. On a write, the proxy casts the argument
  18243. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18244. \racket{
  18245. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18246. \code{0} from \INTTY{} to \CANYTY{}.
  18247. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18248. from \CANYTY{} to \INTTY{}.
  18249. }
  18250. \python{
  18251. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18252. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18253. For the subscript on the left of the assignment,
  18254. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18255. }
  18256. The final category of cast that we need to consider are casts between
  18257. the \CANYTY{} type and higher-order types such as functions or
  18258. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18259. variant of \code{map\_inplace} in which parameter \code{v} does not
  18260. have a type annotation, so it is given type \CANYTY{}. In the call to
  18261. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18262. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18263. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18264. \code{Inject}, but that doesn't work because
  18265. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18266. a flat type. Instead, we must first cast to
  18267. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}} (which is flat)
  18268. and then inject to \CANYTY{}.
  18269. \begin{figure}[tbp]
  18270. \begin{tcolorbox}[colback=white]
  18271. {\if\edition\racketEd
  18272. \begin{lstlisting}
  18273. (define (map_inplace [f : (Any -> Any)] v) : Void
  18274. (begin
  18275. (vector-set! v 0 (f (vector-ref v 0)))
  18276. (vector-set! v 1 (f (vector-ref v 1)))))
  18277. (define (inc x) (+ x 1))
  18278. (let ([v (vector 0 41)])
  18279. (begin (map_inplace inc v) (vector-ref v 1)))
  18280. \end{lstlisting}
  18281. \fi}
  18282. {\if\edition\pythonEd
  18283. \begin{lstlisting}
  18284. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18285. i = 0
  18286. while i != len(v):
  18287. v[i] = f(v[i])
  18288. i = i + 1
  18289. def inc(x):
  18290. return x + 1
  18291. v = [0, 41]
  18292. map_inplace(inc, v)
  18293. print( v[1] )
  18294. \end{lstlisting}
  18295. \fi}
  18296. \end{tcolorbox}
  18297. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18298. \label{fig:map-any}
  18299. \end{figure}
  18300. \begin{figure}[tbp]
  18301. \begin{tcolorbox}[colback=white]
  18302. {\if\edition\racketEd
  18303. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18304. (define/public (apply_cast v s t)
  18305. (match* (s t)
  18306. [(t1 t2) #:when (equal? t1 t2) v]
  18307. [('Any t2)
  18308. (match t2
  18309. [`(,ts ... -> ,rt)
  18310. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18311. (define v^ (apply-project v any->any))
  18312. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18313. [`(Vector ,ts ...)
  18314. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18315. (define v^ (apply-project v vec-any))
  18316. (apply_cast v^ vec-any `(Vector ,@ts))]
  18317. [else (apply-project v t2)])]
  18318. [(t1 'Any)
  18319. (match t1
  18320. [`(,ts ... -> ,rt)
  18321. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18322. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18323. (apply-inject v^ (any-tag any->any))]
  18324. [`(Vector ,ts ...)
  18325. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18326. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18327. (apply-inject v^ (any-tag vec-any))]
  18328. [else (apply-inject v (any-tag t1))])]
  18329. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18330. (define x (gensym 'x))
  18331. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18332. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18333. (define cast-writes
  18334. (for/list ([t1 ts1] [t2 ts2])
  18335. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18336. `(vector-proxy ,(vector v (apply vector cast-reads)
  18337. (apply vector cast-writes)))]
  18338. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18339. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18340. `(function ,xs ,(Cast
  18341. (Apply (Value v)
  18342. (for/list ([x xs][t1 ts1][t2 ts2])
  18343. (Cast (Var x) t2 t1)))
  18344. rt1 rt2) ())]
  18345. ))
  18346. \end{lstlisting}
  18347. \fi}
  18348. {\if\edition\pythonEd
  18349. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18350. def apply_cast(self, value, src, tgt):
  18351. match (src, tgt):
  18352. case (AnyType(), FunctionType(ps2, rt2)):
  18353. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18354. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18355. case (AnyType(), TupleType(ts2)):
  18356. anytup = TupleType([AnyType() for t1 in ts2])
  18357. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18358. case (AnyType(), ListType(t2)):
  18359. anylist = ListType([AnyType() for t1 in ts2])
  18360. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18361. case (AnyType(), AnyType()):
  18362. return value
  18363. case (AnyType(), _):
  18364. return self.apply_project(value, tgt)
  18365. case (FunctionType(ps1,rt1), AnyType()):
  18366. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18367. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18368. case (TupleType(ts1), AnyType()):
  18369. anytup = TupleType([AnyType() for t1 in ts1])
  18370. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18371. case (ListType(t1), AnyType()):
  18372. anylist = ListType(AnyType())
  18373. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18374. case (_, AnyType()):
  18375. return self.apply_inject(value, src)
  18376. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18377. params = [generate_name('x') for p in ps2]
  18378. args = [Cast(Name(x), t2, t1)
  18379. for (x,t1,t2) in zip(params, ps1, ps2)]
  18380. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18381. return Function('cast', params, [Return(body)], {})
  18382. case (TupleType(ts1), TupleType(ts2)):
  18383. x = generate_name('x')
  18384. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18385. for (t1,t2) in zip(ts1,ts2)]
  18386. return ProxiedTuple(value, reads)
  18387. case (ListType(t1), ListType(t2)):
  18388. x = generate_name('x')
  18389. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18390. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18391. return ProxiedList(value, read, write)
  18392. case (t1, t2) if t1 == t2:
  18393. return value
  18394. case (t1, t2):
  18395. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18396. def apply_inject(self, value, src):
  18397. return Tagged(value, self.type_to_tag(src))
  18398. def apply_project(self, value, tgt):
  18399. match value:
  18400. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18401. return val
  18402. case _:
  18403. raise Exception('apply_project, unexpected ' + repr(value))
  18404. \end{lstlisting}
  18405. \fi}
  18406. \end{tcolorbox}
  18407. \caption{The \code{apply\_cast} auxiliary method.}
  18408. \label{fig:apply_cast}
  18409. \end{figure}
  18410. The \LangCast{} interpreter uses an auxiliary function named
  18411. \code{apply\_cast} to cast a value from a source type to a target type,
  18412. shown in Figure~\ref{fig:apply_cast}. You'll find that it handles all
  18413. of the kinds of casts that we've discussed in this section.
  18414. %
  18415. The interpreter for \LangCast{} is defined in
  18416. Figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18417. dispatching to \code{apply\_cast}.
  18418. \racket{To handle the addition of tuple
  18419. proxies, we update the tuple primitives in \code{interp-op} using the
  18420. functions in Figure~\ref{fig:guarded-tuple}.}
  18421. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18422. \begin{figure}[tbp]
  18423. \begin{tcolorbox}[colback=white]
  18424. {\if\edition\racketEd
  18425. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18426. (define interp-Lcast-class
  18427. (class interp-Llambda-class
  18428. (super-new)
  18429. (inherit apply-fun apply-inject apply-project)
  18430. (define/override (interp-op op)
  18431. (match op
  18432. ['vector-length guarded-vector-length]
  18433. ['vector-ref guarded-vector-ref]
  18434. ['vector-set! guarded-vector-set!]
  18435. ['any-vector-ref (lambda (v i)
  18436. (match v [`(tagged ,v^ ,tg)
  18437. (guarded-vector-ref v^ i)]))]
  18438. ['any-vector-set! (lambda (v i a)
  18439. (match v [`(tagged ,v^ ,tg)
  18440. (guarded-vector-set! v^ i a)]))]
  18441. ['any-vector-length (lambda (v)
  18442. (match v [`(tagged ,v^ ,tg)
  18443. (guarded-vector-length v^)]))]
  18444. [else (super interp-op op)]
  18445. ))
  18446. (define/override ((interp-exp env) e)
  18447. (define (recur e) ((interp-exp env) e))
  18448. (match e
  18449. [(Value v) v]
  18450. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18451. [else ((super interp-exp env) e)]))
  18452. ))
  18453. (define (interp-Lcast p)
  18454. (send (new interp-Lcast-class) interp-program p))
  18455. \end{lstlisting}
  18456. \fi}
  18457. {\if\edition\pythonEd
  18458. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18459. class InterpLcast(InterpLany):
  18460. def interp_exp(self, e, env):
  18461. match e:
  18462. case Cast(value, src, tgt):
  18463. v = self.interp_exp(value, env)
  18464. return self.apply_cast(v, src, tgt)
  18465. case ValueExp(value):
  18466. return value
  18467. ...
  18468. case _:
  18469. return super().interp_exp(e, env)
  18470. \end{lstlisting}
  18471. \fi}
  18472. \end{tcolorbox}
  18473. \caption{The interpreter for \LangCast{}.}
  18474. \label{fig:interp-Lcast}
  18475. \end{figure}
  18476. {\if\edition\racketEd
  18477. \begin{figure}[tbp]
  18478. \begin{tcolorbox}[colback=white]
  18479. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18480. (define (guarded-vector-ref vec i)
  18481. (match vec
  18482. [`(vector-proxy ,proxy)
  18483. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18484. (define rd (vector-ref (vector-ref proxy 1) i))
  18485. (apply-fun rd (list val) 'guarded-vector-ref)]
  18486. [else (vector-ref vec i)]))
  18487. (define (guarded-vector-set! vec i arg)
  18488. (match vec
  18489. [`(vector-proxy ,proxy)
  18490. (define wr (vector-ref (vector-ref proxy 2) i))
  18491. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18492. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18493. [else (vector-set! vec i arg)]))
  18494. (define (guarded-vector-length vec)
  18495. (match vec
  18496. [`(vector-proxy ,proxy)
  18497. (guarded-vector-length (vector-ref proxy 0))]
  18498. [else (vector-length vec)]))
  18499. \end{lstlisting}
  18500. %% {\if\edition\pythonEd
  18501. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18502. %% UNDER CONSTRUCTION
  18503. %% \end{lstlisting}
  18504. %% \fi}
  18505. \end{tcolorbox}
  18506. \caption{The \code{guarded-vector} auxiliary functions.}
  18507. \label{fig:guarded-tuple}
  18508. \end{figure}
  18509. \fi}
  18510. {\if\edition\pythonEd
  18511. \section{Overload Resolution}
  18512. \label{sec:gradual-resolution}
  18513. Recall that when we added support for arrays in
  18514. Section~\ref{sec:arrays}, the syntax for the array operations were the
  18515. same as for tuple operations (e.g., accessing an element, getting the
  18516. length). So we performed overload resolution, with a pass named
  18517. \code{resolve}, to separate the array and tuple operations. In
  18518. particular, we introduced the primitives \code{array\_load},
  18519. \code{array\_store}, and \code{array\_len}.
  18520. For gradual typing, we further overload these operators to work on
  18521. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18522. updated with new cases for the \CANYTY{} type, translating the element
  18523. access and length operations to the primitives \code{any\_load},
  18524. \code{any\_store}, and \code{any\_len}.
  18525. \section{Cast Insertion}
  18526. \label{sec:gradual-insert-casts}
  18527. In our discussion of type checking of \LangGrad{}, we mentioned how
  18528. the runtime aspect of type checking is carried out by the \code{Cast}
  18529. AST node, which is added to the program by a new pass named
  18530. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18531. language. We now discuss the details of this pass.
  18532. The \code{cast\_insert} pass is closely related to the type checker
  18533. for \LangGrad{} (starting in Figure~\ref{fig:type-check-Lgradual-1}).
  18534. In particular, the type checker allows implicit casts between
  18535. consistent types. The job of the \code{cast\_insert} pass is to make
  18536. those casts explicit. It does so by inserting
  18537. \code{Cast} nodes into the AST.
  18538. %
  18539. For the most part, the implicit casts occur in places where the type
  18540. checker checks two types for consistency. Consider the case for
  18541. binary operators in Figure~\ref{fig:type-check-Lgradual-1}. The type
  18542. checker requires that the type of the left operand is consistent with
  18543. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18544. \code{Cast} around the left operand, converting from its type to
  18545. \INTTY{}. The story is similar for the right operand. It is not always
  18546. necessary to insert a cast, e.g., if the left operand already has type
  18547. \INTTY{} then there is no need for a \code{Cast}.
  18548. Some of the implicit casts are not as straightforward. One such case
  18549. arises with the
  18550. conditional expression. In Figure~\ref{fig:type-check-Lgradual-1} we
  18551. see that the type checker requires that the two branches have
  18552. consistent types and that type of the conditional expression is the
  18553. join of the branches' types. In the target language \LangCast{}, both
  18554. branches will need to have the same type, and that type
  18555. will be the type of the conditional expression. Thus, each branch requires
  18556. a \code{Cast} to convert from its type to the join type.
  18557. The case for the function call exhibits another interesting situation. If
  18558. the function expression is of type \CANYTY{}, then it needs to be cast
  18559. to a function type so that it can be used in a function call in
  18560. \LangCast{}. Which function type should it be cast to? The parameter
  18561. and return types are unknown, so we can simply use \CANYTY{} for all
  18562. of them. Futhermore, in \LangCast{} the argument types will need to
  18563. exactly match the parameter types, so we must cast all the arguments
  18564. to type \CANYTY{} (if they are not already of that type).
  18565. \fi}
  18566. \section{Lower Casts}
  18567. \label{sec:lower_casts}
  18568. The next step in the journey towards x86 is the \code{lower\_casts}
  18569. pass that translates the casts in \LangCast{} to the lower-level
  18570. \code{Inject} and \code{Project} operators and new operators for
  18571. proxies, extending the \LangLam{} language to \LangProxy{}.
  18572. The \LangProxy{} language can also be described as an extension of
  18573. \LangAny{}, with the addition of proxies. We recommend creating an
  18574. auxiliary function named \code{lower\_cast} that takes an expression
  18575. (in \LangCast{}), a source type, and a target type, and translates it
  18576. to expression in \LangProxy{}.
  18577. The \code{lower\_cast} function can follow a code structure similar to
  18578. the \code{apply\_cast} function (Figure~\ref{fig:apply_cast}) used in
  18579. the interpreter for \LangCast{} because it must handle the same cases
  18580. as \code{apply\_cast} and it needs to mimic the behavior of
  18581. \code{apply\_cast}. The most interesting cases are those concerning
  18582. the casts involving tuple, array, and function types.
  18583. As mentioned in Section~\ref{sec:interp-casts}, a cast from one array
  18584. type to another array type is accomplished by creating a proxy that
  18585. intercepts the operations on the underlying array. Here we make the
  18586. creation of the proxy explicit with the
  18587. \racket{\code{vectorof-proxy}}\python{\code{ListProxy}} AST node. It
  18588. takes fives arguments, the first is an expression for the array, the
  18589. second is a function for casting an element that is being read from
  18590. the array, the third is a function for casting an element that is
  18591. being written to the array, the fourth is the type of the underlying
  18592. array, and the fifth is the type of the proxied array. You can create
  18593. the functions for reading and writing using lambda expressions.
  18594. A cast between two tuple types can be handled in a similar manner.
  18595. We create a proxy with the
  18596. \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST node.
  18597. \python{Tuples are immutable, so there is no
  18598. need for a function to cast the value during a write.}
  18599. Because there is a separate element type for each slot in the tuple,
  18600. we need not just one function for casting during a read, but instead a tuple
  18601. of functions.
  18602. %
  18603. Also, as we shall see in the next section, we need to differentiate
  18604. these tuples from the user-created ones, so we recommend using a new
  18605. AST node named \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18606. instead of \racket{\code{vector}}\python{\code{Tuple}} to create the
  18607. tuples of functions.
  18608. %
  18609. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18610. \code{lower\_casts} on the example in Figure~\ref{fig:map-bang} that
  18611. involved casting an array of integers to an array of \CANYTY{}.
  18612. \begin{figure}[tbp]
  18613. \begin{tcolorbox}[colback=white]
  18614. {\if\edition\racketEd
  18615. \begin{lstlisting}
  18616. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18617. (begin
  18618. (vector-set! v 0 (f (vector-ref v 0)))
  18619. (vector-set! v 1 (f (vector-ref v 1)))))
  18620. (define (inc [x : Any]) : Any
  18621. (inject (+ (project x Integer) 1) Integer))
  18622. (let ([v (vector 0 41)])
  18623. (begin
  18624. (map_inplace inc (vector-proxy v
  18625. (raw-vector (lambda: ([x9 : Integer]) : Any
  18626. (inject x9 Integer))
  18627. (lambda: ([x9 : Integer]) : Any
  18628. (inject x9 Integer)))
  18629. (raw-vector (lambda: ([x9 : Any]) : Integer
  18630. (project x9 Integer))
  18631. (lambda: ([x9 : Any]) : Integer
  18632. (project x9 Integer)))))
  18633. (vector-ref v 1)))
  18634. \end{lstlisting}
  18635. \fi}
  18636. {\if\edition\pythonEd
  18637. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18638. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18639. i = 0
  18640. while i != array_len(v):
  18641. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18642. i = (i + 1)
  18643. def inc(x : int) -> int:
  18644. return (x + 1)
  18645. def main() -> int:
  18646. v = [0, 41]
  18647. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18648. print(array_load(v, 1))
  18649. return 0
  18650. \end{lstlisting}
  18651. \fi}
  18652. \end{tcolorbox}
  18653. \caption{Output of \code{lower\_casts} on the example in
  18654. Figure~\ref{fig:map-bang}.}
  18655. \label{fig:map-bang-lower-cast}
  18656. \end{figure}
  18657. A cast from one function type to another function type is accomplished
  18658. by generating a \code{lambda} whose parameter and return types match
  18659. the target function type. The body of the \code{lambda} should cast
  18660. the parameters from the target type to the source type. (Yes,
  18661. backwards! Functions are contravariant\index{subject}{contravariant}
  18662. in the parameters.). Afterwards, call the underlying function and then
  18663. cast the result from the source return type to the target return type.
  18664. Figure~\ref{fig:map-lower-cast} shows the output of the
  18665. \code{lower\_casts} pass on the \code{map} example in
  18666. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18667. call to \code{map} is wrapped in a \code{lambda}.
  18668. \begin{figure}[tbp]
  18669. \begin{tcolorbox}[colback=white]
  18670. {\if\edition\racketEd
  18671. \begin{lstlisting}
  18672. (define (map [f : (Integer -> Integer)]
  18673. [v : (Vector Integer Integer)])
  18674. : (Vector Integer Integer)
  18675. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18676. (define (inc [x : Any]) : Any
  18677. (inject (+ (project x Integer) 1) Integer))
  18678. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18679. (project (inc (inject x9 Integer)) Integer))
  18680. (vector 0 41)) 1)
  18681. \end{lstlisting}
  18682. \fi}
  18683. {\if\edition\pythonEd
  18684. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18685. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18686. return (f(v[0]), f(v[1]),)
  18687. def inc(x : any) -> any:
  18688. return inject((project(x, int) + 1), int)
  18689. def main() -> int:
  18690. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18691. print(t[1])
  18692. return 0
  18693. \end{lstlisting}
  18694. \fi}
  18695. \end{tcolorbox}
  18696. \caption{Output of \code{lower\_casts} on the example in
  18697. Figure~\ref{fig:gradual-map}.}
  18698. \label{fig:map-lower-cast}
  18699. \end{figure}
  18700. \section{Differentiate Proxies}
  18701. \label{sec:differentiate-proxies}
  18702. So far the responsibility of differentiating tuples and tuple proxies
  18703. has been the job of the interpreter.
  18704. %
  18705. \racket{For example, the interpreter for \LangCast{} implements
  18706. \code{vector-ref} using the \code{guarded-vector-ref} function in
  18707. Figure~\ref{fig:guarded-tuple}.}
  18708. %
  18709. In the \code{differentiate\_proxies} pass we shift this responsibility
  18710. to the generated code.
  18711. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18712. we used the type \TUPLETYPENAME{} for both
  18713. real tuples and tuple proxies.
  18714. \python{Similarly, we use the type \code{list} for both arrays and
  18715. array proxies.}
  18716. In \LangPVec{} we return the
  18717. \TUPLETYPENAME{} type to its original
  18718. meaning, as the type of just tuples, and we introduce a new type,
  18719. \PTUPLETYNAME{}, whose values
  18720. can be either real tuples or tuple
  18721. proxies.
  18722. Likewise, we return the
  18723. \ARRAYTYPENAME{} type to its original
  18724. meaning, as the type of arrays, and we introduce a new type,
  18725. \PARRAYTYNAME{}, whose values
  18726. can be either arrays or array proxies.
  18727. These new types come with a suite of new primitive operations.
  18728. {\if\edition\racketEd
  18729. A tuple proxy is represented by a tuple containing three things: 1) the
  18730. underlying tuple, 2) a tuple of functions for casting elements that
  18731. are read from the tuple, and 3) a tuple of functions for casting
  18732. values to be written to the tuple. So we define the following
  18733. abbreviation for the type of a tuple proxy:
  18734. \[
  18735. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  18736. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  18737. \]
  18738. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  18739. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  18740. %
  18741. Next we describe each of the new primitive operations.
  18742. \begin{description}
  18743. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  18744. (\key{PVector} $T \ldots$)]\ \\
  18745. %
  18746. This operation brands a vector as a value of the \code{PVector} type.
  18747. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  18748. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  18749. %
  18750. This operation brands a vector proxy as value of the \code{PVector} type.
  18751. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  18752. \BOOLTY{}] \ \\
  18753. %
  18754. This returns true if the value is a tuple proxy and false if it is a
  18755. real tuple.
  18756. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  18757. (\key{Vector} $T \ldots$)]\ \\
  18758. %
  18759. Assuming that the input is a tuple, this operation returns the
  18760. tuple.
  18761. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  18762. $\to$ \BOOLTY{}]\ \\
  18763. %
  18764. Given a tuple proxy, this operation returns the length of the tuple.
  18765. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  18766. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  18767. %
  18768. Given a tuple proxy, this operation returns the $i$th element of the
  18769. tuple.
  18770. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  18771. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  18772. Given a tuple proxy, this operation writes a value to the $i$th element
  18773. of the tuple.
  18774. \end{description}
  18775. \fi}
  18776. {\if\edition\pythonEd
  18777. A tuple proxy is represented by a tuple containing 1) the underlying
  18778. tuple and 2) a tuple of functions for casting elements that are read
  18779. from the tuple. The \LangPVec{} language includes the following AST
  18780. classes and primitive functions.
  18781. \begin{description}
  18782. \item[\code{InjectTuple}] \ \\
  18783. %
  18784. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  18785. \item[\code{InjectTupleProxy}]\ \\
  18786. %
  18787. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  18788. \item[\code{is\_tuple\_proxy}]\ \\
  18789. %
  18790. This primitive returns true if the value is a tuple proxy and false
  18791. if it is a tuple.
  18792. \item[\code{project\_tuple}]\ \\
  18793. %
  18794. Converts a tuple that is branded as \PTUPLETYNAME{}
  18795. back to a tuple.
  18796. \item[\code{proxy\_tuple\_len}]\ \\
  18797. %
  18798. Given a tuple proxy, returns the length of the underlying tuple.
  18799. \item[\code{proxy\_tuple\_load}]\ \\
  18800. %
  18801. Given a tuple proxy, returns the $i$th element of the underlying
  18802. tuple.
  18803. \end{description}
  18804. An array proxy is represented by a tuple containing 1) the underlying
  18805. array, 2) a function for casting elements that are read from the
  18806. array, and 3) a function for casting elements that are written to the
  18807. array. The \LangPVec{} language includes the following AST classes
  18808. and primitive functions.
  18809. \begin{description}
  18810. \item[\code{InjectList}]\ \\
  18811. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  18812. \item[\code{InjectListProxy}]\ \\
  18813. %
  18814. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  18815. \item[\code{is\_array\_proxy}]\ \\
  18816. %
  18817. Returns true if the value is a array proxy and false if it is an
  18818. array.
  18819. \item[\code{project\_array}]\ \\
  18820. %
  18821. Converts an array that is branded as \PARRAYTYNAME{} back to an
  18822. array.
  18823. \item[\code{proxy\_array\_len}]\ \\
  18824. %
  18825. Given a array proxy, returns the length of the underlying array.
  18826. \item[\code{proxy\_array\_load}]\ \\
  18827. %
  18828. Given a array proxy, returns the $i$th element of the underlying
  18829. array.
  18830. \item[\code{proxy\_array\_store}]\ \\
  18831. %
  18832. Given an array proxy, writes a value to the $i$th element of the
  18833. underlying array.
  18834. \end{description}
  18835. \fi}
  18836. Now we discuss the translation that differentiates tuples and arrays
  18837. from proxies. First, every type annotation in the program is
  18838. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  18839. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  18840. places. For example, we wrap every tuple creation with an
  18841. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  18842. {\if\edition\racketEd
  18843. \begin{lstlisting}
  18844. (vector |$e_1 \ldots e_n$|)
  18845. |$\Rightarrow$|
  18846. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  18847. \end{lstlisting}
  18848. \fi}
  18849. {\if\edition\pythonEd
  18850. \begin{lstlisting}
  18851. Tuple(|$e_1, \ldots, e_n$|)
  18852. |$\Rightarrow$|
  18853. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  18854. \end{lstlisting}
  18855. \fi}
  18856. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  18857. AST node that we introduced in the previous
  18858. section does not get injected.
  18859. {\if\edition\racketEd
  18860. \begin{lstlisting}
  18861. (raw-vector |$e_1 \ldots e_n$|)
  18862. |$\Rightarrow$|
  18863. (vector |$e'_1 \ldots e'_n$|)
  18864. \end{lstlisting}
  18865. \fi}
  18866. {\if\edition\pythonEd
  18867. \begin{lstlisting}
  18868. RawTuple(|$e_1, \ldots, e_n$|)
  18869. |$\Rightarrow$|
  18870. Tuple(|$e'_1, \ldots, e'_n$|)
  18871. \end{lstlisting}
  18872. \fi}
  18873. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST translates as follows.
  18874. {\if\edition\racketEd
  18875. \begin{lstlisting}
  18876. (vector-proxy |$e_1~e_2~e_3$|)
  18877. |$\Rightarrow$|
  18878. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  18879. \end{lstlisting}
  18880. \fi}
  18881. {\if\edition\pythonEd
  18882. \begin{lstlisting}
  18883. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  18884. |$\Rightarrow$|
  18885. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  18886. \end{lstlisting}
  18887. \fi}
  18888. We translate the element access operations into conditional
  18889. expressions that check whether the value is a proxy and then dispatch
  18890. to either the appropriate proxy tuple operation or the regular tuple
  18891. operation.
  18892. {\if\edition\racketEd
  18893. \begin{lstlisting}
  18894. (vector-ref |$e_1$| |$i$|)
  18895. |$\Rightarrow$|
  18896. (let ([|$v~e_1$|])
  18897. (if (proxy? |$v$|)
  18898. (proxy-vector-ref |$v$| |$i$|)
  18899. (vector-ref (project-vector |$v$|) |$i$|)
  18900. \end{lstlisting}
  18901. \fi}
  18902. %
  18903. Note that in the branch for a tuple, we must apply
  18904. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  18905. from the tuple.
  18906. The translation of array operations is similar to the ones for tuples.
  18907. \section{Reveal Casts}
  18908. \label{sec:reveal-casts-gradual}
  18909. {\if\edition\racketEd
  18910. Recall that the \code{reveal\_casts} pass
  18911. (Section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  18912. \code{Inject} and \code{Project} into lower-level operations.
  18913. %
  18914. In particular, \code{Project} turns into a conditional expression that
  18915. inspects the tag and retrieves the underlying value. Here we need to
  18916. augment the translation of \code{Project} to handle the situation when
  18917. the target type is \code{PVector}. Instead of using
  18918. \code{vector-length} we need to use \code{proxy-vector-length}.
  18919. \begin{lstlisting}
  18920. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  18921. |$\Rightarrow$|
  18922. (let |$\itm{tmp}$| |$e'$|
  18923. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  18924. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  18925. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  18926. (exit)))
  18927. \end{lstlisting}
  18928. \fi}
  18929. %
  18930. {\if\edition\pythonEd
  18931. Recall that the $\itm{tagof}$ function determines the bits used to
  18932. identify values of different types and it is used in the \code{reveal\_casts}
  18933. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  18934. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  18935. decimal), just like the tuple and array types.
  18936. \fi}
  18937. %
  18938. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18939. \section{Closure Conversion}
  18940. \label{sec:closure-conversion-gradual}
  18941. The auxiliary function that translates type annotations needs to be
  18942. updated to handle the \PTUPLETYNAME{} and \PARRAYTYNAME{} types.
  18943. %
  18944. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  18945. \section{Select Instructions}
  18946. \label{sec:select-instructions-gradual}
  18947. Recall that the \code{select\_instructions} pass is responsible for
  18948. lowering the primitive operations into x86 instructions. So we need
  18949. to translate the new operations on \PTUPLETYNAME{} and \PARRAYTYNAME{}
  18950. to x86. To do so, the first question we need to answer is how to
  18951. differentiate between tuple and tuples proxies, and likewise for
  18952. arrays and array proxies. We need just one bit to accomplish this,
  18953. and use the bit in position $63$ of the 64-bit tag at the front of
  18954. every tuple (see Figure~\ref{fig:tuple-rep}) or array
  18955. (Section~\ref{sec:array-rep}). So far, this bit has been set to $0$,
  18956. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  18957. it that way.
  18958. {\if\edition\racketEd
  18959. \begin{lstlisting}
  18960. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  18961. |$\Rightarrow$|
  18962. movq |$e'_1$|, |$\itm{lhs'}$|
  18963. \end{lstlisting}
  18964. \fi}
  18965. {\if\edition\pythonEd
  18966. \begin{lstlisting}
  18967. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  18968. |$\Rightarrow$|
  18969. movq |$e'_1$|, |$\itm{lhs'}$|
  18970. \end{lstlisting}
  18971. \fi}
  18972. \python{The translation for \code{InjectList} is also a move instruction.}
  18973. \noindent On the other hand,
  18974. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  18975. $63$ to $1$.
  18976. %
  18977. {\if\edition\racketEd
  18978. \begin{lstlisting}
  18979. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  18980. |$\Rightarrow$|
  18981. movq |$e'_1$|, %r11
  18982. movq |$(1 << 63)$|, %rax
  18983. orq 0(%r11), %rax
  18984. movq %rax, 0(%r11)
  18985. movq %r11, |$\itm{lhs'}$|
  18986. \end{lstlisting}
  18987. \fi}
  18988. {\if\edition\pythonEd
  18989. \begin{lstlisting}
  18990. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  18991. |$\Rightarrow$|
  18992. movq |$e'_1$|, %r11
  18993. movq |$(1 << 63)$|, %rax
  18994. orq 0(%r11), %rax
  18995. movq %rax, 0(%r11)
  18996. movq %r11, |$\itm{lhs'}$|
  18997. \end{lstlisting}
  18998. \fi}
  18999. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19000. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19001. The \racket{\code{proxy?} operation consumes}
  19002. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations consume}
  19003. the information so carefully
  19004. stashed away by the injections. It
  19005. isolates the $63$rd bit to tell whether the value is a tuple/array or
  19006. a proxy.
  19007. %
  19008. {\if\edition\racketEd
  19009. \begin{lstlisting}
  19010. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19011. |$\Rightarrow$|
  19012. movq |$e_1'$|, %r11
  19013. movq 0(%r11), %rax
  19014. sarq $63, %rax
  19015. andq $1, %rax
  19016. movq %rax, |$\itm{lhs'}$|
  19017. \end{lstlisting}
  19018. \fi}%
  19019. %
  19020. {\if\edition\pythonEd
  19021. \begin{lstlisting}
  19022. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19023. |$\Rightarrow$|
  19024. movq |$e_1'$|, %r11
  19025. movq 0(%r11), %rax
  19026. sarq $63, %rax
  19027. andq $1, %rax
  19028. movq %rax, |$\itm{lhs'}$|
  19029. \end{lstlisting}
  19030. \fi}%
  19031. %
  19032. The \racket{\code{project-vector} operation is}
  19033. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19034. straightforward to translate, so we leave that to the reader.
  19035. Regarding the element access operations for tuples and arrays, the
  19036. runtime provides procedures that implement them (they are recursive
  19037. functions!) so here we simply need to translate these tuple
  19038. operations into the appropriate function call. For example, here is
  19039. the translation for
  19040. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19041. {\if\edition\racketEd
  19042. \begin{lstlisting}
  19043. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19044. |$\Rightarrow$|
  19045. movq |$e_1'$|, %rdi
  19046. movq |$e_2'$|, %rsi
  19047. callq proxy_vector_ref
  19048. movq %rax, |$\itm{lhs'}$|
  19049. \end{lstlisting}
  19050. \fi}
  19051. {\if\edition\pythonEd
  19052. \begin{lstlisting}
  19053. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19054. |$\Rightarrow$|
  19055. movq |$e_1'$|, %rdi
  19056. movq |$e_2'$|, %rsi
  19057. callq proxy_vector_ref
  19058. movq %rax, |$\itm{lhs'}$|
  19059. \end{lstlisting}
  19060. \fi}
  19061. We translate
  19062. \racket{\code{proxy-vectof-ref}}\python{\code{proxy\_array\_load}}
  19063. to \code{proxy\_vecof\_ref},
  19064. \racket{\code{proxy-vectof-set!}}\python{\code{proxy\_array\_store}}
  19065. to \code{proxy\_vecof\_set}, and
  19066. \racket{\code{proxy-vectof-length}}\python{\code{proxy\_array\_len}}
  19067. to \code{proxy\_vecof\_length}.
  19068. We have another batch of operations to deal with, those for the
  19069. \CANYTY{} type. Recall that overload resolution
  19070. (Section~\ref{sec:gradual-resolution}) generates an
  19071. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19072. there is a element access on something of type \CANYTY{}, and
  19073. similarly for
  19074. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19075. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19076. Section~\ref{sec:select-Lany} we selected instructions for these
  19077. operations based on the idea that the underlying value was a tuple or
  19078. array. But in the current setting, the underlying value is of type
  19079. \PTUPLETYNAME{} or \PARRAYTYNAME{}. We have added two runtime
  19080. functions to deal with this: \code{proxy\_vec\_ref},
  19081. \code{proxy\_vec\_set}, and
  19082. \code{proxy\_vec\_length}, that inspect bit $62$ of the tag
  19083. to determine whether the value is a tuple or array, and then
  19084. dispatches to the the appropriate function for
  19085. tuples (e.g. \code{proxy\_vector\_ref}) or arrays
  19086. (e.g. \code{proxy\_vecof\_ref}).
  19087. %
  19088. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19089. can be translated follows.
  19090. We begin by projecting the underlying value out of the tagged value and
  19091. then call the \code{proxy\_vec\_ref} procedure in the runtime.
  19092. {\if\edition\racketEd
  19093. \begin{lstlisting}
  19094. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19095. |$\Rightarrow$|
  19096. movq |$\neg 111$|, %rdi
  19097. andq |$e_1'$|, %rdi
  19098. movq |$e_2'$|, %rsi
  19099. callq proxy_vec_ref
  19100. movq %rax, |$\itm{lhs'}$|
  19101. \end{lstlisting}
  19102. \fi}
  19103. {\if\edition\pythonEd
  19104. \begin{lstlisting}
  19105. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19106. |$\Rightarrow$|
  19107. movq |$\neg 111$|, %rdi
  19108. andq |$e_1'$|, %rdi
  19109. movq |$e_2'$|, %rsi
  19110. callq proxy_vec_ref
  19111. movq %rax, |$\itm{lhs'}$|
  19112. \end{lstlisting}
  19113. \fi}
  19114. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19115. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19116. are translated in a similar way. Alternatively, you could generate
  19117. instructions to open-code
  19118. the \code{proxy\_vec\_ref}, \code{proxy\_vec\_set},
  19119. and \code{proxy\_vec\_length} functions.
  19120. \begin{exercise}\normalfont\normalsize
  19121. Implement a compiler for the gradually-typed \LangGrad{} language by
  19122. extending and adapting your compiler for \LangLam{}. Create 10 new
  19123. partially-typed test programs. In addition to testing with these
  19124. new programs, also test your compiler on all the tests for \LangLam{}
  19125. and for \LangDyn{}.
  19126. %
  19127. \racket{Sometimes you may get a type checking error on the
  19128. \LangDyn{} programs but you can adapt them by inserting a cast to
  19129. the \CANYTY{} type around each subexpression causing a type
  19130. error. While \LangDyn{} does not have explicit casts, you can
  19131. induce one by wrapping the subexpression \code{e} with a call to
  19132. an un-annotated identity function, like this: \code{((lambda (x) x) e)}.}
  19133. %
  19134. \python{Sometimes you may get a type checking error on the
  19135. \LangDyn{} programs but you can adapt them by inserting a
  19136. temporary variable of type \CANYTY{} that is initialized with the
  19137. troublesome expression.}
  19138. \end{exercise}
  19139. \begin{figure}[p]
  19140. \begin{tcolorbox}[colback=white]
  19141. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19142. \node (Lgradual) at (12,4) {\large \LangGrad{}};
  19143. \node (Lgradualr) at (9,4) {\large \LangGrad{}};
  19144. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  19145. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  19146. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  19147. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  19148. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  19149. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  19150. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  19151. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  19152. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  19153. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  19154. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  19155. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  19156. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  19157. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  19158. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  19159. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  19160. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  19161. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  19162. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  19163. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  19164. \path[->,bend right=15] (Lgradual) edge [above] node
  19165. {\ttfamily\footnotesize resolve} (Lgradualr);
  19166. \path[->,bend right=15] (Lgradualr) edge [above] node
  19167. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19168. \path[->,bend right=15] (Lgradualp) edge [above] node
  19169. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19170. \path[->,bend right=15] (Llambdapp) edge [above] node
  19171. {\ttfamily\footnotesize differentiate.} (Llambdaproxy);
  19172. \path[->,bend left=15] (Llambdaproxy) edge [left] node
  19173. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  19174. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  19175. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  19176. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  19177. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  19178. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  19179. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19180. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  19181. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19182. \path[->,bend left=15] (F1-1) edge [left] node
  19183. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  19184. \path[->,bend left=15] (F1-2) edge [below] node
  19185. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  19186. \path[->,bend right=15] (F1-3) edge [above] node
  19187. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  19188. \path[->,bend right=15] (F1-4) edge [above] node
  19189. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19190. \path[->,bend right=15] (F1-5) edge [above] node
  19191. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  19192. \path[->,bend right=15] (F1-6) edge [right] node
  19193. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19194. \path[->,bend left=15] (C3-2) edge [left] node
  19195. {\ttfamily\footnotesize select\_instr.} (x86-2);
  19196. \path[->,bend right=15] (x86-2) edge [left] node
  19197. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19198. \path[->,bend right=15] (x86-2-1) edge [below] node
  19199. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  19200. \path[->,bend right=15] (x86-2-2) edge [left] node
  19201. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  19202. \path[->,bend left=15] (x86-3) edge [above] node
  19203. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  19204. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  19205. \end{tikzpicture}
  19206. \end{tcolorbox}
  19207. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19208. \label{fig:Lgradual-passes}
  19209. \end{figure}
  19210. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19211. needed for the compilation of \LangGrad{}.
  19212. \section{Further Reading}
  19213. This chapter just scratches the surface of gradual typing. The basic
  19214. approach described here is missing two key ingredients that one would
  19215. want in a implementation of gradual typing: blame
  19216. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19217. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19218. problem addressed by blame tracking is that when a cast on a
  19219. higher-order value fails, it often does so at a point in the program
  19220. that is far removed from the original cast. Blame tracking is a
  19221. technique for propagating extra information through casts and proxies
  19222. so that when a cast fails, the error message can point back to the
  19223. original location of the cast in the source program.
  19224. The problem addressed by space-efficient casts also relates to
  19225. higher-order casts. It turns out that in partially typed programs, a
  19226. function or tuple can flow through very many casts at runtime. With
  19227. the approach described in this chapter, each cast adds another
  19228. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19229. considerable space, but it also makes the function calls and tuple
  19230. operations slow. For example, a partially-typed version of quicksort
  19231. could, in the worst case, build a chain of proxies of length $O(n)$
  19232. around the tuple, changing the overall time complexity of the
  19233. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19234. solution to this problem by representing casts using the coercion
  19235. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19236. long chains of proxies by compressing them into a concise normal
  19237. form. \citet{Siek:2015ab} give an algorithm for compressing coercions
  19238. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19239. the Grift compiler.
  19240. \begin{center}
  19241. \url{https://github.com/Gradual-Typing/Grift}
  19242. \end{center}
  19243. There are also interesting interactions between gradual typing and
  19244. other language features, such as parametetric polymorphism,
  19245. information-flow types, and type inference, to name a few. We
  19246. recommend the reader to consult the online gradual typing bibliography
  19247. for more material:
  19248. \begin{center}
  19249. \url{http://samth.github.io/gradual-typing-bib/}
  19250. \end{center}
  19251. % TODO: challenge problem:
  19252. % type analysis and type specialization?
  19253. % coercions?
  19254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19255. \chapter{Generics}
  19256. \label{ch:Lpoly}
  19257. \index{subject}{parametric polymorphism}
  19258. \index{subject}{generics}
  19259. This chapter studies the compilation of
  19260. generics\index{subject}{generics} (aka. parametric
  19261. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19262. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19263. enable programmers to make code more reusable by parameterizing
  19264. functions and data structures with respect to the types that they
  19265. operate on. For example, Figure~\ref{fig:map-poly} revisits the
  19266. \code{map} example but this time gives it a more fitting type. This
  19267. \code{map} function is parameterized with respect to the element type
  19268. of the tuple. The type of \code{map} is the following generic type
  19269. specified by the \code{All} type with parameter \code{T}.
  19270. \if\edition\racketEd
  19271. \begin{lstlisting}
  19272. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19273. \end{lstlisting}
  19274. \fi
  19275. \if\edition\pythonEd
  19276. \begin{lstlisting}
  19277. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19278. \end{lstlisting}
  19279. \fi
  19280. The idea is that \code{map} can be used at \emph{all} choices of a
  19281. type for parameter \code{T}. In Figure~\ref{fig:map-poly} we apply
  19282. \code{map} to a tuple of integers, choosing
  19283. \racket{\code{Integer}}\python{\code{int}} for \code{T}, but we could
  19284. have just as well applied \code{map} to a tuple of Booleans.
  19285. %
  19286. \if\edition\pythonEd
  19287. %
  19288. In Python, when writing a generic function such as \code{map}, one
  19289. does not explicitly write down its generic type (using \code{All}).
  19290. Instead, the fact that it is generic is implied by the use of type
  19291. variables (such as \code{T}) in the type annotations of its
  19292. parameters.
  19293. %
  19294. \fi
  19295. \begin{figure}[tbp]
  19296. % poly_test_2.rkt
  19297. \begin{tcolorbox}[colback=white]
  19298. \if\edition\racketEd
  19299. \begin{lstlisting}
  19300. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19301. (define (map f v)
  19302. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19303. (define (inc [x : Integer]) : Integer (+ x 1))
  19304. (vector-ref (map inc (vector 0 41)) 1)
  19305. \end{lstlisting}
  19306. \fi
  19307. \if\edition\pythonEd
  19308. \begin{lstlisting}
  19309. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19310. return (f(tup[0]), f(tup[1]))
  19311. def add1(x : int) -> int:
  19312. return x + 1
  19313. t = map(add1, (0, 41))
  19314. print(t[1])
  19315. \end{lstlisting}
  19316. \fi
  19317. \end{tcolorbox}
  19318. \caption{The \code{map} example using parametric polymorphism.}
  19319. \label{fig:map-poly}
  19320. \end{figure}
  19321. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  19322. \LangPoly{} and Figure~\ref{fig:Lpoly-syntax} defines the abstract
  19323. syntax.
  19324. %
  19325. \if\edition\racketEd
  19326. We add a second form for function definitions in which a type
  19327. declaration comes before the \code{define}. In the abstract syntax,
  19328. the return type in the \code{Def} is \CANYTY{}, but that should be
  19329. ignored in favor of the return type in the type declaration. (The
  19330. \CANYTY{} comes from using the same parser as in
  19331. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19332. enables the use of an \code{All} type for a function, thereby making
  19333. it polymorphic.
  19334. \fi
  19335. %
  19336. The grammar for types is extended to include generic types and type
  19337. variables.
  19338. \newcommand{\LpolyGrammarRacket}{
  19339. \begin{array}{lcl}
  19340. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19341. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19342. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19343. \end{array}
  19344. }
  19345. \newcommand{\LpolyASTRacket}{
  19346. \begin{array}{lcl}
  19347. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19348. \Def &::=& \DECL{\Var}{\Type} \\
  19349. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19350. \end{array}
  19351. }
  19352. \newcommand{\LpolyGrammarPython}{
  19353. \begin{array}{lcl}
  19354. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19355. \end{array}
  19356. }
  19357. \newcommand{\LpolyASTPython}{
  19358. \begin{array}{lcl}
  19359. \Type &::=& \key{GenericType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var
  19360. \end{array}
  19361. }
  19362. \begin{figure}[tp]
  19363. \centering
  19364. \begin{tcolorbox}[colback=white]
  19365. \footnotesize
  19366. \if\edition\racketEd
  19367. \[
  19368. \begin{array}{l}
  19369. \gray{\LintGrammarRacket{}} \\ \hline
  19370. \gray{\LvarGrammarRacket{}} \\ \hline
  19371. \gray{\LifGrammarRacket{}} \\ \hline
  19372. \gray{\LwhileGrammarRacket} \\ \hline
  19373. \gray{\LtupGrammarRacket} \\ \hline
  19374. \gray{\LfunGrammarRacket} \\ \hline
  19375. \gray{\LlambdaGrammarRacket} \\ \hline
  19376. \LpolyGrammarRacket \\
  19377. \begin{array}{lcl}
  19378. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19379. \end{array}
  19380. \end{array}
  19381. \]
  19382. \fi
  19383. \if\edition\pythonEd
  19384. \[
  19385. \begin{array}{l}
  19386. \gray{\LintGrammarPython{}} \\ \hline
  19387. \gray{\LvarGrammarPython{}} \\ \hline
  19388. \gray{\LifGrammarPython{}} \\ \hline
  19389. \gray{\LwhileGrammarPython} \\ \hline
  19390. \gray{\LtupGrammarPython} \\ \hline
  19391. \gray{\LfunGrammarPython} \\ \hline
  19392. \gray{\LlambdaGrammarPython} \\\hline
  19393. \LpolyGrammarPython \\
  19394. \begin{array}{lcl}
  19395. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19396. \end{array}
  19397. \end{array}
  19398. \]
  19399. \fi
  19400. \end{tcolorbox}
  19401. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19402. (Figure~\ref{fig:Llam-concrete-syntax}).}
  19403. \label{fig:Lpoly-concrete-syntax}
  19404. \end{figure}
  19405. \begin{figure}[tp]
  19406. \centering
  19407. \begin{tcolorbox}[colback=white]
  19408. \footnotesize
  19409. \if\edition\racketEd
  19410. \[
  19411. \begin{array}{l}
  19412. \gray{\LintOpAST} \\ \hline
  19413. \gray{\LvarASTRacket{}} \\ \hline
  19414. \gray{\LifASTRacket{}} \\ \hline
  19415. \gray{\LwhileASTRacket{}} \\ \hline
  19416. \gray{\LtupASTRacket{}} \\ \hline
  19417. \gray{\LfunASTRacket} \\ \hline
  19418. \gray{\LlambdaASTRacket} \\ \hline
  19419. \LpolyASTRacket \\
  19420. \begin{array}{lcl}
  19421. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19422. \end{array}
  19423. \end{array}
  19424. \]
  19425. \fi
  19426. \if\edition\pythonEd
  19427. \[
  19428. \begin{array}{l}
  19429. \gray{\LintASTPython} \\ \hline
  19430. \gray{\LvarASTPython{}} \\ \hline
  19431. \gray{\LifASTPython{}} \\ \hline
  19432. \gray{\LwhileASTPython{}} \\ \hline
  19433. \gray{\LtupASTPython{}} \\ \hline
  19434. \gray{\LfunASTPython} \\ \hline
  19435. \gray{\LlambdaASTPython} \\ \hline
  19436. \LpolyASTPython \\
  19437. \begin{array}{lcl}
  19438. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19439. \end{array}
  19440. \end{array}
  19441. \]
  19442. \fi
  19443. \end{tcolorbox}
  19444. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19445. (Figure~\ref{fig:Llam-syntax}).}
  19446. \label{fig:Lpoly-syntax}
  19447. \end{figure}
  19448. By including the \code{All} type in the $\Type$ non-terminal of the
  19449. grammar we choose to make generics first-class, which has interesting
  19450. repercussions on the compiler.\footnote{The Python typing library does
  19451. not include the \code{All} type, we are taking the liberty to add
  19452. the \code{All} type.} Many languages with generics, such as
  19453. C++~\citep{stroustrup88:_param_types} and Standard
  19454. ML~\citep{Milner:1990fk}, only support second-class generics, so it
  19455. may be helpful to see an example of first-class generics in action. In
  19456. Figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19457. whose parameter is a generic function. Indeed, because the grammar for
  19458. $\Type$ includes the \code{All} type, a generic function may also be
  19459. returned from a function or stored inside a tuple. The body of
  19460. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19461. and also to an integer, which would not be possible if \code{f} were
  19462. not generic.
  19463. \begin{figure}[tbp]
  19464. \begin{tcolorbox}[colback=white]
  19465. \if\edition\racketEd
  19466. \begin{lstlisting}
  19467. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19468. (define (apply_twice f)
  19469. (if (f #t) (f 42) (f 777)))
  19470. (: id (All (T) (T -> T)))
  19471. (define (id x) x)
  19472. (apply_twice id)
  19473. \end{lstlisting}
  19474. \fi
  19475. \if\edition\pythonEd
  19476. \begin{lstlisting}
  19477. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19478. if f(True):
  19479. return f(42)
  19480. else:
  19481. return f(777)
  19482. def id(x: T) -> T:
  19483. return x
  19484. print(apply_twice(id))
  19485. \end{lstlisting}
  19486. \fi
  19487. \end{tcolorbox}
  19488. \caption{An example illustrating first-class polymorphism.}
  19489. \label{fig:apply-twice}
  19490. \end{figure}
  19491. \if\edition\pythonEd
  19492. UNDER CONSTRUCTION
  19493. \fi
  19494. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  19495. three new responsibilities (compared to \LangLam{}). The type checking of
  19496. function application is extended to handle the case where the operator
  19497. expression is a polymorphic function. In that case the type arguments
  19498. are deduced by matching the type of the parameters with the types of
  19499. the arguments.
  19500. %
  19501. The \code{match-types} auxiliary function carries out this deduction
  19502. by recursively descending through a parameter type \code{pt} and the
  19503. corresponding argument type \code{at}, making sure that they are equal
  19504. except when there is a type parameter on the left (in the parameter
  19505. type). If it is the first time that the type parameter has been
  19506. encountered, then the algorithm deduces an association of the type
  19507. parameter to the corresponding type on the right (in the argument
  19508. type). If it is not the first time that the type parameter has been
  19509. encountered, the algorithm looks up its deduced type and makes sure
  19510. that it is equal to the type on the right.
  19511. %
  19512. Once the type arguments are deduced, the operator expression is
  19513. wrapped in an \code{Inst} AST node (for instantiate) that records the
  19514. type of the operator, but more importantly, records the deduced type
  19515. arguments. The return type of the application is the return type of
  19516. the polymorphic function, but with the type parameters replaced by the
  19517. deduced type arguments, using the \code{subst-type} function.
  19518. The second responsibility of the type checker to extend the
  19519. \code{type-equal?} function to handle the \code{All} type. This is
  19520. not quite as simple as for other types, such as function and tuple
  19521. types, because two polymorphic types can be syntactically different
  19522. even though they are equivalent types. For example, \code{(All (a) (a
  19523. -> a))} is equivalent to \code{(All (b) (b -> b))}. Two polymorphic
  19524. types should be considered equal if they differ only in the choice of
  19525. the names of the type parameters. The \code{type-equal?} function in
  19526. Figure~\ref{fig:type-check-Lvar0-aux} renames the type parameters of
  19527. the first type to match the type parameters of the second type.
  19528. The third responsibility of the type checker is to make sure that only
  19529. defined type variables appear in type annotations. The
  19530. \code{check-well-formed} function defined in
  19531. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  19532. sure that each type variable has been defined.
  19533. The output language of the type checker is \LangInst{}, defined in
  19534. Figure~\ref{fig:Lpoly-prime-syntax}. The type checker combines the type
  19535. declaration and polymorphic function into a single definition, using
  19536. the \code{Poly} form, to make polymorphic functions more convenient to
  19537. process in next pass of the compiler.
  19538. \begin{figure}[tp]
  19539. \centering
  19540. \begin{tcolorbox}[colback=white]
  19541. \small
  19542. \if\edition\racketEd
  19543. \[
  19544. \begin{array}{lcl}
  19545. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19546. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  19547. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  19548. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  19549. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19550. \end{array}
  19551. \]
  19552. \fi
  19553. \if\edition\pythonEd
  19554. UNDER CONSTURCTION
  19555. \fi
  19556. \end{tcolorbox}
  19557. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  19558. (Figure~\ref{fig:Llam-syntax}).}
  19559. \label{fig:Lpoly-prime-syntax}
  19560. \end{figure}
  19561. The output of the type checker on the polymorphic \code{map}
  19562. example is listed in Figure~\ref{fig:map-type-check}.
  19563. \begin{figure}[tbp]
  19564. % poly_test_2.rkt
  19565. \begin{tcolorbox}[colback=white]
  19566. \begin{lstlisting}
  19567. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  19568. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  19569. (define (inc [x : Integer]) : Integer (+ x 1))
  19570. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  19571. (Integer))
  19572. inc (vector 0 41)) 1)
  19573. \end{lstlisting}
  19574. \end{tcolorbox}
  19575. \caption{Output of the type checker on the \code{map} example.}
  19576. \label{fig:map-type-check}
  19577. \end{figure}
  19578. \begin{figure}[tbp]
  19579. \begin{tcolorbox}[colback=white]
  19580. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19581. (define type-check-poly-class
  19582. (class type-check-Llambda-class
  19583. (super-new)
  19584. (inherit check-type-equal?)
  19585. (define/override (type-check-apply env e1 es)
  19586. (define-values (e^ ty) ((type-check-exp env) e1))
  19587. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19588. ((type-check-exp env) e)))
  19589. (match ty
  19590. [`(,ty^* ... -> ,rt)
  19591. (for ([arg-ty ty*] [param-ty ty^*])
  19592. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19593. (values e^ es^ rt)]
  19594. [`(All ,xs (,tys ... -> ,rt))
  19595. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19596. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19597. (match-types env^^ param-ty arg-ty)))
  19598. (define targs
  19599. (for/list ([x xs])
  19600. (match (dict-ref env^^ x (lambda () #f))
  19601. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19602. x (Apply e1 es))]
  19603. [ty ty])))
  19604. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  19605. [else (error 'type-check "expected a function, not ~a" ty)]))
  19606. (define/override ((type-check-exp env) e)
  19607. (match e
  19608. [(Lambda `([,xs : ,Ts] ...) rT body)
  19609. (for ([T Ts]) ((check-well-formed env) T))
  19610. ((check-well-formed env) rT)
  19611. ((super type-check-exp env) e)]
  19612. [(HasType e1 ty)
  19613. ((check-well-formed env) ty)
  19614. ((super type-check-exp env) e)]
  19615. [else ((super type-check-exp env) e)]))
  19616. (define/override ((type-check-def env) d)
  19617. (verbose 'type-check "poly/def" d)
  19618. (match d
  19619. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19620. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19621. (for ([p ps]) ((check-well-formed ts-env) p))
  19622. ((check-well-formed ts-env) rt)
  19623. (define new-env (append ts-env (map cons xs ps) env))
  19624. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19625. (check-type-equal? ty^ rt body)
  19626. (Generic ts (Def f p:t* rt info body^))]
  19627. [else ((super type-check-def env) d)]))
  19628. (define/override (type-check-program p)
  19629. (match p
  19630. [(Program info body)
  19631. (type-check-program (ProgramDefsExp info '() body))]
  19632. [(ProgramDefsExp info ds body)
  19633. (define ds^ (combine-decls-defs ds))
  19634. (define new-env (for/list ([d ds^])
  19635. (cons (def-name d) (fun-def-type d))))
  19636. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19637. (define-values (body^ ty) ((type-check-exp new-env) body))
  19638. (check-type-equal? ty 'Integer body)
  19639. (ProgramDefsExp info ds^^ body^)]))
  19640. ))
  19641. \end{lstlisting}
  19642. \end{tcolorbox}
  19643. \caption{Type checker for the \LangPoly{} language.}
  19644. \label{fig:type-check-Lvar0}
  19645. \end{figure}
  19646. \begin{figure}[tbp]
  19647. \begin{tcolorbox}[colback=white]
  19648. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19649. (define/override (type-equal? t1 t2)
  19650. (match* (t1 t2)
  19651. [(`(All ,xs ,T1) `(All ,ys ,T2))
  19652. (define env (map cons xs ys))
  19653. (type-equal? (subst-type env T1) T2)]
  19654. [(other wise)
  19655. (super type-equal? t1 t2)]))
  19656. (define/public (match-types env pt at)
  19657. (match* (pt at)
  19658. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  19659. [('Void 'Void) env] [('Any 'Any) env]
  19660. [(`(Vector ,pts ...) `(Vector ,ats ...))
  19661. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  19662. (match-types env^ pt1 at1))]
  19663. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  19664. (define env^ (match-types env prt art))
  19665. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  19666. (match-types env^^ pt1 at1))]
  19667. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  19668. (define env^ (append (map cons pxs axs) env))
  19669. (match-types env^ pt1 at1)]
  19670. [((? symbol? x) at)
  19671. (match (dict-ref env x (lambda () #f))
  19672. [#f (error 'type-check "undefined type variable ~a" x)]
  19673. ['Type (cons (cons x at) env)]
  19674. [t^ (check-type-equal? at t^ 'matching) env])]
  19675. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  19676. (define/public (subst-type env pt)
  19677. (match pt
  19678. ['Integer 'Integer] ['Boolean 'Boolean]
  19679. ['Void 'Void] ['Any 'Any]
  19680. [`(Vector ,ts ...)
  19681. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  19682. [`(,ts ... -> ,rt)
  19683. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  19684. [`(All ,xs ,t)
  19685. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  19686. [(? symbol? x) (dict-ref env x)]
  19687. [else (error 'type-check "expected a type not ~a" pt)]))
  19688. (define/public (combine-decls-defs ds)
  19689. (match ds
  19690. ['() '()]
  19691. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  19692. (unless (equal? name f)
  19693. (error 'type-check "name mismatch, ~a != ~a" name f))
  19694. (match type
  19695. [`(All ,xs (,ps ... -> ,rt))
  19696. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19697. (cons (Generic xs (Def name params^ rt info body))
  19698. (combine-decls-defs ds^))]
  19699. [`(,ps ... -> ,rt)
  19700. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  19701. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  19702. [else (error 'type-check "expected a function type, not ~a" type) ])]
  19703. [`(,(Def f params rt info body) . ,ds^)
  19704. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  19705. \end{lstlisting}
  19706. \end{tcolorbox}
  19707. \caption{Auxiliary functions for type checking \LangPoly{}.}
  19708. \label{fig:type-check-Lvar0-aux}
  19709. \end{figure}
  19710. \begin{figure}[tbp]
  19711. \begin{tcolorbox}[colback=white]
  19712. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  19713. (define/public ((check-well-formed env) ty)
  19714. (match ty
  19715. ['Integer (void)]
  19716. ['Boolean (void)]
  19717. ['Void (void)]
  19718. [(? symbol? a)
  19719. (match (dict-ref env a (lambda () #f))
  19720. ['Type (void)]
  19721. [else (error 'type-check "undefined type variable ~a" a)])]
  19722. [`(Vector ,ts ...)
  19723. (for ([t ts]) ((check-well-formed env) t))]
  19724. [`(,ts ... -> ,t)
  19725. (for ([t ts]) ((check-well-formed env) t))
  19726. ((check-well-formed env) t)]
  19727. [`(All ,xs ,t)
  19728. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19729. ((check-well-formed env^) t)]
  19730. [else (error 'type-check "unrecognized type ~a" ty)]))
  19731. \end{lstlisting}
  19732. \end{tcolorbox}
  19733. \caption{Well-formed types.}
  19734. \label{fig:well-formed-types}
  19735. \end{figure}
  19736. % TODO: interpreter for R'_10
  19737. \clearpage
  19738. \section{Compiling Polymorphism}
  19739. \label{sec:compiling-poly}
  19740. Broadly speaking, there are four approaches to compiling parametric
  19741. polymorphism, which we describe below.
  19742. \begin{description}
  19743. \item[Monomorphization] generates a different version of a polymorphic
  19744. function for each set of type arguments that it is used with,
  19745. producing type-specialized code. This approach results in the most
  19746. efficient code but requires whole-program compilation (no separate
  19747. compilation) and increases code size. For our current purposes
  19748. monomorphization is a non-starter because, with first-class
  19749. polymorphism, it is sometimes not possible to determine which
  19750. generic functions are used with which type arguments during
  19751. compilation. (It can be done at runtime, with just-in-time
  19752. compilation.) Monomorphization is used to compile C++
  19753. templates~\citep{stroustrup88:_param_types} and polymorphic
  19754. functions in NESL~\citep{Blelloch:1993aa} and
  19755. ML~\citep{Weeks:2006aa}.
  19756. \item[Uniform representation] generates one version of each
  19757. polymorphic function but requires all values to have a common
  19758. ``boxed'' format, such as the tagged values of type \CANYTY{} in
  19759. \LangAny{}. Both polymorphic and non-polymorphic (i.e. monomorphic)
  19760. code is compiled similarly to code in a dynamically typed language
  19761. (like \LangDyn{}), in which primitive operators require their
  19762. arguments to be projected from \CANYTY{} and their results are
  19763. injected into \CANYTY{}. (In object-oriented languages, the
  19764. projection is accomplished via virtual method dispatch.) The uniform
  19765. representation approach is compatible with separate compilation and
  19766. with first-class polymorphism. However, it produces the
  19767. least-efficient code because it introduces overhead in the entire
  19768. program. This approach is used in implementations of
  19769. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  19770. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  19771. Java~\citep{Bracha:1998fk}.
  19772. \item[Mixed representation] generates one version of each polymorphic
  19773. function, using a boxed representation for type
  19774. variables. Monomorphic code is compiled as usual (as in \LangLam{})
  19775. and conversions are performed at the boundaries between monomorphic
  19776. and polymorphic (e.g. when a polymorphic function is instantiated
  19777. and called). This approach is compatible with separate compilation
  19778. and first-class polymorphism and maintains efficiency in monomorphic
  19779. code. The trade off is increased overhead at the boundary between
  19780. monomorphic and polymorphic code. This approach is used in
  19781. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  19782. Java 5 with the addition of autoboxing.
  19783. \item[Type passing] uses the unboxed representation in both
  19784. monomorphic and polymorphic code. Each polymorphic function is
  19785. compiled to a single function with extra parameters that describe
  19786. the type arguments. The type information is used by the generated
  19787. code to know how to access the unboxed values at runtime. This
  19788. approach is used in implementation of the Napier88
  19789. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  19790. passing is compatible with separate compilation and first-class
  19791. polymorphism and maintains the efficiency for monomorphic
  19792. code. There is runtime overhead in polymorphic code from dispatching
  19793. on type information.
  19794. \end{description}
  19795. In this chapter we use the mixed representation approach, partly
  19796. because of its favorable attributes, and partly because it is
  19797. straightforward to implement using the tools that we have already
  19798. built to support gradual typing. To compile polymorphic functions, we
  19799. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  19800. \LangCast{}.
  19801. \section{Erase Types}
  19802. \label{sec:erase-types}
  19803. We use the \CANYTY{} type from Chapter~\ref{ch:Ldyn} to
  19804. represent type variables. For example, Figure~\ref{fig:map-erase}
  19805. shows the output of the \code{erase-types} pass on the polymorphic
  19806. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  19807. type parameter \code{a} are replaced by \CANYTY{} and the polymorphic
  19808. \code{All} types are removed from the type of \code{map}.
  19809. \begin{figure}[tbp]
  19810. \begin{tcolorbox}[colback=white]
  19811. \begin{lstlisting}
  19812. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  19813. : (Vector Any Any)
  19814. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19815. (define (inc [x : Integer]) : Integer (+ x 1))
  19816. (vector-ref ((cast map
  19817. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  19818. ((Integer -> Integer) (Vector Integer Integer)
  19819. -> (Vector Integer Integer)))
  19820. inc (vector 0 41)) 1)
  19821. \end{lstlisting}
  19822. \end{tcolorbox}
  19823. \caption{The polymorphic \code{map} example after type erasure.}
  19824. \label{fig:map-erase}
  19825. \end{figure}
  19826. This process of type erasure creates a challenge at points of
  19827. instantiation. For example, consider the instantiation of
  19828. \code{map} in Figure~\ref{fig:map-type-check}.
  19829. The type of \code{map} is
  19830. \begin{lstlisting}
  19831. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  19832. \end{lstlisting}
  19833. and it is instantiated to
  19834. \begin{lstlisting}
  19835. ((Integer -> Integer) (Vector Integer Integer)
  19836. -> (Vector Integer Integer))
  19837. \end{lstlisting}
  19838. After erasure, the type of \code{map} is
  19839. \begin{lstlisting}
  19840. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  19841. \end{lstlisting}
  19842. but we need to convert it to the instantiated type. This is easy to
  19843. do in the language \LangCast{} with a single \code{cast}. In
  19844. Figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  19845. compiled to a \code{cast} from the type of \code{map} to the
  19846. instantiated type. The source and target type of a cast must be
  19847. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  19848. because both the source and target are obtained from the same
  19849. polymorphic type of \code{map}, replacing the type parameters with
  19850. \CANYTY{} in the former and with the deduced type arguments in the
  19851. later. (Recall that the \CANYTY{} type is consistent with any type.)
  19852. To implement the \code{erase-types} pass, we recommend defining a
  19853. recursive auxiliary function named \code{erase-type} that applies the
  19854. following two transformations. It replaces type variables with
  19855. \CANYTY{}
  19856. \begin{lstlisting}
  19857. |$x$|
  19858. |$\Rightarrow$|
  19859. Any
  19860. \end{lstlisting}
  19861. and it removes the polymorphic \code{All} types.
  19862. \begin{lstlisting}
  19863. (All |$xs$| |$T_1$|)
  19864. |$\Rightarrow$|
  19865. |$T'_1$|
  19866. \end{lstlisting}
  19867. Apply the \code{erase-type} function to all of the type annotations in
  19868. the program.
  19869. Regarding the translation of expressions, the case for \code{Inst} is
  19870. the interesting one. We translate it into a \code{Cast}, as shown
  19871. below. The type of the subexpression $e$ is the polymorphic type
  19872. $\LP\key{All}~\itm{xs}~T\RP$. The source type of the cast is the erasure of
  19873. $T$, the type $T'$. The target type $T''$ is the result of
  19874. substituting the argument types $ts$ for the type parameters $xs$ in
  19875. $T$ followed by doing type erasure.
  19876. \begin{lstlisting}
  19877. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  19878. |$\Rightarrow$|
  19879. (Cast |$e'$| |$T'$| |$T''$|)
  19880. \end{lstlisting}
  19881. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  19882. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  19883. Finally, each polymorphic function is translated to a regular
  19884. function in which type erasure has been applied to all the type
  19885. annotations and the body.
  19886. \begin{lstlisting}
  19887. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  19888. |$\Rightarrow$|
  19889. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  19890. \end{lstlisting}
  19891. \begin{exercise}\normalfont\normalsize
  19892. Implement a compiler for the polymorphic language \LangPoly{} by
  19893. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  19894. programs that use polymorphic functions. Some of them should make
  19895. use of first-class polymorphism.
  19896. \end{exercise}
  19897. \begin{figure}[p]
  19898. \begin{tcolorbox}[colback=white]
  19899. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19900. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  19901. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  19902. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  19903. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  19904. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  19905. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  19906. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  19907. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  19908. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  19909. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  19910. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  19911. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  19912. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  19913. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  19914. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  19915. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  19916. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  19917. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  19918. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  19919. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  19920. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  19921. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  19922. \path[->,bend right=15] (Lpoly) edge [above] node
  19923. {\ttfamily\footnotesize type\_check} (Lpolyp);
  19924. \path[->,bend right=15] (Lpolyp) edge [above] node
  19925. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  19926. \path[->,bend right=15] (Lgradualp) edge [above] node
  19927. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19928. \path[->,bend right=15] (Llambdapp) edge [above] node
  19929. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  19930. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  19931. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  19932. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  19933. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  19934. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  19935. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  19936. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  19937. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19938. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  19939. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19940. \path[->,bend left=15] (F1-1) edge [left] node
  19941. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  19942. \path[->,bend left=15] (F1-2) edge [below] node
  19943. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  19944. \path[->,bend right=15] (F1-3) edge [above] node
  19945. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  19946. \path[->,bend right=15] (F1-4) edge [above] node
  19947. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19948. \path[->,bend right=15] (F1-5) edge [above] node
  19949. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  19950. \path[->,bend right=15] (F1-6) edge [right] node
  19951. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19952. \path[->,bend left=15] (C3-2) edge [left] node
  19953. {\ttfamily\footnotesize select\_instr.} (x86-2);
  19954. \path[->,bend right=15] (x86-2) edge [left] node
  19955. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19956. \path[->,bend right=15] (x86-2-1) edge [below] node
  19957. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  19958. \path[->,bend right=15] (x86-2-2) edge [left] node
  19959. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  19960. \path[->,bend left=15] (x86-3) edge [above] node
  19961. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  19962. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  19963. \end{tikzpicture}
  19964. \end{tcolorbox}
  19965. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  19966. \label{fig:Lpoly-passes}
  19967. \end{figure}
  19968. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  19969. needed to compile \LangPoly{}.
  19970. % TODO: challenge problem: specialization of instantiations
  19971. % Further Reading
  19972. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19973. \clearpage
  19974. \appendix
  19975. \chapter{Appendix}
  19976. \if\edition\racketEd
  19977. \section{Interpreters}
  19978. \label{appendix:interp}
  19979. \index{subject}{interpreter}
  19980. We provide interpreters for each of the source languages \LangInt{},
  19981. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  19982. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  19983. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  19984. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  19985. and x86 are in the \key{interp.rkt} file.
  19986. \section{Utility Functions}
  19987. \label{appendix:utilities}
  19988. The utility functions described in this section are in the
  19989. \key{utilities.rkt} file of the support code.
  19990. \paragraph{\code{interp-tests}}
  19991. The \key{interp-tests} function runs the compiler passes and the
  19992. interpreters on each of the specified tests to check whether each pass
  19993. is correct. The \key{interp-tests} function has the following
  19994. parameters:
  19995. \begin{description}
  19996. \item[name (a string)] a name to identify the compiler,
  19997. \item[typechecker] a function of exactly one argument that either
  19998. raises an error using the \code{error} function when it encounters a
  19999. type error, or returns \code{\#f} when it encounters a type
  20000. error. If there is no type error, the type checker returns the
  20001. program.
  20002. \item[passes] a list with one entry per pass. An entry is a list with
  20003. four things:
  20004. \begin{enumerate}
  20005. \item a string giving the name of the pass,
  20006. \item the function that implements the pass (a translator from AST
  20007. to AST),
  20008. \item a function that implements the interpreter (a function from
  20009. AST to result value) for the output language,
  20010. \item and a type checker for the output language. Type checkers for
  20011. the $R$ and $C$ languages are provided in the support code. For
  20012. example, the type checkers for \LangVar{} and \LangCVar{} are in
  20013. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20014. type checker entry is optional. The support code does not provide
  20015. type checkers for the x86 languages.
  20016. \end{enumerate}
  20017. \item[source-interp] an interpreter for the source language. The
  20018. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  20019. \item[test-family (a string)] for example, \code{"var"}, \code{"cond"}, etc.
  20020. \item[tests] a list of test numbers that specifies which tests to
  20021. run. (see below)
  20022. \end{description}
  20023. %
  20024. The \key{interp-tests} function assumes that the subdirectory
  20025. \key{tests} has a collection of Racket programs whose names all start
  20026. with the family name, followed by an underscore and then the test
  20027. number, ending with the file extension \key{.rkt}. Also, for each test
  20028. program that calls \code{read} one or more times, there is a file with
  20029. the same name except that the file extension is \key{.in} that
  20030. provides the input for the Racket program. If the test program is
  20031. expected to fail type checking, then there should be an empty file of
  20032. the same name but with extension \key{.tyerr}.
  20033. \paragraph{\code{compiler-tests}}
  20034. runs the compiler passes to generate x86 (a \key{.s} file) and then
  20035. runs the GNU C compiler (gcc) to generate machine code. It runs the
  20036. machine code and checks that the output is $42$. The parameters to the
  20037. \code{compiler-tests} function are similar to those of the
  20038. \code{interp-tests} function, and consist of
  20039. \begin{itemize}
  20040. \item a compiler name (a string),
  20041. \item a type checker,
  20042. \item description of the passes,
  20043. \item name of a test-family, and
  20044. \item a list of test numbers.
  20045. \end{itemize}
  20046. \paragraph{\code{compile-file}}
  20047. takes a description of the compiler passes (see the comment for
  20048. \key{interp-tests}) and returns a function that, given a program file
  20049. name (a string ending in \key{.rkt}), applies all of the passes and
  20050. writes the output to a file whose name is the same as the program file
  20051. name but with \key{.rkt} replaced with \key{.s}.
  20052. \paragraph{\code{read-program}}
  20053. takes a file path and parses that file (it must be a Racket program)
  20054. into an abstract syntax tree.
  20055. \paragraph{\code{parse-program}}
  20056. takes an S-expression representation of an abstract syntax tree and converts it into
  20057. the struct-based representation.
  20058. \paragraph{\code{assert}}
  20059. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  20060. and displays the message \key{msg} if the Boolean \key{bool} is false.
  20061. \paragraph{\code{lookup}}
  20062. % remove discussion of lookup? -Jeremy
  20063. takes a key and an alist, and returns the first value that is
  20064. associated with the given key, if there is one. If not, an error is
  20065. triggered. The alist may contain both immutable pairs (built with
  20066. \key{cons}) and mutable pairs (built with \key{mcons}).
  20067. %The \key{map2} function ...
  20068. \fi %\racketEd
  20069. \section{x86 Instruction Set Quick-Reference}
  20070. \label{sec:x86-quick-reference}
  20071. \index{subject}{x86}
  20072. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20073. do. We write $A \to B$ to mean that the value of $A$ is written into
  20074. location $B$. Address offsets are given in bytes. The instruction
  20075. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20076. registers (such as \code{\%rax}), or memory references (such as
  20077. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  20078. reference per instruction. Other operands must be immediates or
  20079. registers.
  20080. \begin{table}[tbp]
  20081. \centering
  20082. \begin{tabular}{l|l}
  20083. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20084. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20085. \texttt{negq} $A$ & $- A \to A$ \\
  20086. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20087. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20088. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20089. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20090. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20091. \texttt{retq} & Pops the return address and jumps to it \\
  20092. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20093. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20094. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20095. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  20096. be an immediate) \\
  20097. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20098. matches the condition code of the instruction, otherwise go to the
  20099. next instructions. The condition codes are \key{e} for ``equal'',
  20100. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  20101. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  20102. \texttt{jl} $L$ & \\
  20103. \texttt{jle} $L$ & \\
  20104. \texttt{jg} $L$ & \\
  20105. \texttt{jge} $L$ & \\
  20106. \texttt{jmp} $L$ & Jump to label $L$ \\
  20107. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20108. \texttt{movzbq} $A$, $B$ &
  20109. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20110. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  20111. and the extra bytes of $B$ are set to zero.} \\
  20112. & \\
  20113. & \\
  20114. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20115. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20116. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20117. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20118. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20119. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20120. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  20121. description of the condition codes. $A$ must be a single byte register
  20122. (e.g., \texttt{al} or \texttt{cl}).} \\
  20123. \texttt{setl} $A$ & \\
  20124. \texttt{setle} $A$ & \\
  20125. \texttt{setg} $A$ & \\
  20126. \texttt{setge} $A$ &
  20127. \end{tabular}
  20128. \vspace{5pt}
  20129. \caption{Quick-reference for the x86 instructions used in this book.}
  20130. \label{tab:x86-instr}
  20131. \end{table}
  20132. %% \if\edition\racketEd
  20133. %% \cleardoublepage
  20134. %% \section{Concrete Syntax for Intermediate Languages}
  20135. %% The concrete syntax of \LangAny{} is defined in
  20136. %% Figure~\ref{fig:Lany-concrete-syntax}.
  20137. %% \begin{figure}[tp]
  20138. %% \centering
  20139. %% \fbox{
  20140. %% \begin{minipage}{0.97\textwidth}\small
  20141. %% \[
  20142. %% \begin{array}{lcl}
  20143. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20144. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20145. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20146. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20147. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20148. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20149. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20150. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20151. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20152. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20153. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20154. %% \MID \LP\key{void?}\;\Exp\RP \\
  20155. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20156. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20157. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20158. %% \end{array}
  20159. %% \]
  20160. %% \end{minipage}
  20161. %% }
  20162. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20163. %% (Figure~\ref{fig:Llam-syntax}).}
  20164. %% \label{fig:Lany-concrete-syntax}
  20165. %% \end{figure}
  20166. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20167. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  20168. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20169. %% \ref{fig:c3-concrete-syntax}, respectively.
  20170. %% \begin{figure}[tbp]
  20171. %% \fbox{
  20172. %% \begin{minipage}{0.96\textwidth}
  20173. %% \small
  20174. %% \[
  20175. %% \begin{array}{lcl}
  20176. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20177. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20178. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20179. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20180. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20181. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20182. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20183. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20184. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20185. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20186. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20187. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20188. %% \end{array}
  20189. %% \]
  20190. %% \end{minipage}
  20191. %% }
  20192. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20193. %% \label{fig:c2-concrete-syntax}
  20194. %% \end{figure}
  20195. %% \begin{figure}[tp]
  20196. %% \fbox{
  20197. %% \begin{minipage}{0.96\textwidth}
  20198. %% \small
  20199. %% \[
  20200. %% \begin{array}{lcl}
  20201. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20202. %% \\
  20203. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20204. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20205. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20206. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20207. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20208. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20209. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20210. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20211. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20212. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20213. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20214. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20215. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20216. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20217. %% \LangCFunM{} & ::= & \Def\ldots
  20218. %% \end{array}
  20219. %% \]
  20220. %% \end{minipage}
  20221. %% }
  20222. %% \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20223. %% \label{fig:c3-concrete-syntax}
  20224. %% \end{figure}
  20225. %% \fi % racketEd
  20226. \backmatter
  20227. \addtocontents{toc}{\vspace{11pt}}
  20228. %% \addtocontents{toc}{\vspace{11pt}}
  20229. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20230. \nocite{*}\let\bibname\refname
  20231. \addcontentsline{toc}{fmbm}{\refname}
  20232. \printbibliography
  20233. %\printindex{authors}{Author Index}
  20234. \printindex{subject}{Index}
  20235. \end{document}
  20236. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20237. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20238. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20239. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20240. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20241. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20242. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20243. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20244. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20245. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20246. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20247. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20248. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20249. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20250. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20251. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20252. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20253. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  20254. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20255. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20256. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20257. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20258. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20259. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20260. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20261. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20262. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20263. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20264. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20265. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20266. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20267. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20268. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20269. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20270. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20271. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20272. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20273. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20274. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20275. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20276. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20277. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20278. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20279. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20280. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20281. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20282. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20283. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20284. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20285. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20286. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20287. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20288. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20289. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20290. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20291. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20292. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20293. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20294. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20295. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20296. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20297. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20298. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20299. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20300. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20301. % LocalWords: notq setle setg setge