BackwardPass.cpp 305 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "Backend.h"
  6. #define INLINEEMETAARG_COUNT 3
  7. BackwardPass::BackwardPass(Func * func, GlobOpt * globOpt, Js::Phase tag)
  8. : func(func), globOpt(globOpt), tag(tag), currentPrePassLoop(nullptr), tempAlloc(nullptr),
  9. preOpBailOutInstrToProcess(nullptr),
  10. considerSymAsRealUseInNoImplicitCallUses(nullptr),
  11. isCollectionPass(false), currentRegion(nullptr)
  12. {
  13. // Those are the only two phase dead store will be used currently
  14. Assert(tag == Js::BackwardPhase || tag == Js::DeadStorePhase);
  15. this->implicitCallBailouts = 0;
  16. this->fieldOpts = 0;
  17. #if DBG_DUMP
  18. this->numDeadStore = 0;
  19. this->numMarkTempNumber = 0;
  20. this->numMarkTempNumberTransferred = 0;
  21. this->numMarkTempObject = 0;
  22. #endif
  23. }
  24. void
  25. BackwardPass::DoSetDead(IR::Opnd * opnd, bool isDead) const
  26. {
  27. // Note: Dead bit on the Opnd records flow-based liveness.
  28. // This is distinct from isLastUse, which records lexical last-ness.
  29. if (isDead && this->tag == Js::BackwardPhase && !this->IsPrePass())
  30. {
  31. opnd->SetIsDead();
  32. }
  33. else if (this->tag == Js::DeadStorePhase)
  34. {
  35. // Set or reset in DeadStorePhase.
  36. // CSE could make previous dead operand not the last use, so reset it.
  37. opnd->SetIsDead(isDead);
  38. }
  39. }
  40. bool
  41. BackwardPass::DoByteCodeUpwardExposedUsed() const
  42. {
  43. return (this->tag == Js::DeadStorePhase && this->func->hasBailout) ||
  44. (this->func->HasTry() && this->func->DoOptimizeTryCatch() && this->tag == Js::BackwardPhase);
  45. }
  46. bool
  47. BackwardPass::DoFieldHoistCandidates() const
  48. {
  49. return DoFieldHoistCandidates(this->currentBlock->loop);
  50. }
  51. bool
  52. BackwardPass::DoFieldHoistCandidates(Loop * loop) const
  53. {
  54. // We only need to do one pass to generate this data
  55. return this->tag == Js::BackwardPhase
  56. && !this->IsPrePass() && loop && GlobOpt::DoFieldHoisting(loop);
  57. }
  58. bool
  59. BackwardPass::DoMarkTempNumbers() const
  60. {
  61. #if FLOATVAR
  62. return false;
  63. #else
  64. // only mark temp number on the dead store phase
  65. return (tag == Js::DeadStorePhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  66. !PHASE_OFF(Js::MarkTempNumberPhase, this->func) && func->DoFastPaths() && (!this->func->HasTry());
  67. #endif
  68. }
  69. bool
  70. BackwardPass::DoMarkTempObjects() const
  71. {
  72. // only mark temp object on the backward store phase
  73. return (tag == Js::BackwardPhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  74. !PHASE_OFF(Js::MarkTempObjectPhase, this->func) && func->DoGlobOpt() && func->GetHasTempObjectProducingInstr() &&
  75. !func->IsJitInDebugMode() &&
  76. func->DoGlobOptsForGeneratorFunc();
  77. // Why MarkTempObject is disabled under debugger:
  78. // We add 'identified so far dead non-temp locals' to byteCodeUpwardExposedUsed in ProcessBailOutInfo,
  79. // this may cause MarkTempObject to convert some temps back to non-temp when it sees a 'transferred exposed use'
  80. // from a temp to non-temp. That's in general not a supported conversion (while non-temp -> temp is fine).
  81. }
  82. bool
  83. BackwardPass::DoMarkTempNumbersOnTempObjects() const
  84. {
  85. return !PHASE_OFF(Js::MarkTempNumberOnTempObjectPhase, this->func) && DoMarkTempNumbers() && this->func->GetHasMarkTempObjects();
  86. }
  87. #if DBG
  88. bool
  89. BackwardPass::DoMarkTempObjectVerify() const
  90. {
  91. // only mark temp object on the backward store phase
  92. return (tag == Js::DeadStorePhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  93. !PHASE_OFF(Js::MarkTempObjectPhase, this->func) && func->DoGlobOpt() && func->GetHasTempObjectProducingInstr();
  94. }
  95. #endif
  96. // static
  97. bool
  98. BackwardPass::DoDeadStore(Func* func)
  99. {
  100. return
  101. !PHASE_OFF(Js::DeadStorePhase, func) &&
  102. (!func->HasTry() || func->DoOptimizeTryCatch());
  103. }
  104. bool
  105. BackwardPass::DoDeadStore() const
  106. {
  107. return
  108. this->tag == Js::DeadStorePhase &&
  109. DoDeadStore(this->func);
  110. }
  111. bool
  112. BackwardPass::DoDeadStoreSlots() const
  113. {
  114. // only dead store fields if glob opt is on to generate the trackable fields bitvector
  115. return (tag == Js::DeadStorePhase && this->func->DoGlobOpt()
  116. && (!this->func->HasTry()));
  117. }
  118. // Whether dead store is enabled for given func and sym.
  119. // static
  120. bool
  121. BackwardPass::DoDeadStore(Func* func, StackSym* sym)
  122. {
  123. // Dead store is disabled under debugger for non-temp local vars.
  124. return
  125. DoDeadStore(func) &&
  126. !(func->IsJitInDebugMode() && sym->HasByteCodeRegSlot() && func->IsNonTempLocalVar(sym->GetByteCodeRegSlot())) &&
  127. func->DoGlobOptsForGeneratorFunc();
  128. }
  129. bool
  130. BackwardPass::DoTrackNegativeZero() const
  131. {
  132. return
  133. !PHASE_OFF(Js::TrackIntUsagePhase, func) &&
  134. !PHASE_OFF(Js::TrackNegativeZeroPhase, func) &&
  135. func->DoGlobOpt() &&
  136. !IsPrePass() &&
  137. !func->IsJitInDebugMode() &&
  138. func->DoGlobOptsForGeneratorFunc();
  139. }
  140. bool
  141. BackwardPass::DoTrackBitOpsOrNumber() const
  142. {
  143. #if _WIN64
  144. return
  145. !PHASE_OFF1(Js::TypedArrayVirtualPhase) &&
  146. tag == Js::BackwardPhase &&
  147. func->DoGlobOpt() &&
  148. !IsPrePass() &&
  149. !func->IsJitInDebugMode() &&
  150. func->DoGlobOptsForGeneratorFunc();
  151. #else
  152. return false;
  153. #endif
  154. }
  155. bool
  156. BackwardPass::DoTrackIntOverflow() const
  157. {
  158. return
  159. !PHASE_OFF(Js::TrackIntUsagePhase, func) &&
  160. !PHASE_OFF(Js::TrackIntOverflowPhase, func) &&
  161. tag == Js::BackwardPhase &&
  162. !IsPrePass() &&
  163. globOpt->DoLossyIntTypeSpec() &&
  164. !func->IsJitInDebugMode() &&
  165. func->DoGlobOptsForGeneratorFunc();
  166. }
  167. bool
  168. BackwardPass::DoTrackCompoundedIntOverflow() const
  169. {
  170. return
  171. !PHASE_OFF(Js::TrackCompoundedIntOverflowPhase, func) &&
  172. DoTrackIntOverflow() &&
  173. (!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsTrackCompoundedIntOverflowDisabled());
  174. }
  175. bool
  176. BackwardPass::DoTrackNon32BitOverflow() const
  177. {
  178. // enabled only for IA
  179. #if defined(_M_IX86) || defined(_M_X64)
  180. return true;
  181. #else
  182. return false;
  183. #endif
  184. }
  185. void
  186. BackwardPass::CleanupBackwardPassInfoInFlowGraph()
  187. {
  188. if (!this->func->m_fg->hasBackwardPassInfo)
  189. {
  190. // No information to clean up
  191. return;
  192. }
  193. // The backward pass temp arena has already been deleted, we can just reset the data
  194. FOREACH_BLOCK_IN_FUNC_DEAD_OR_ALIVE(block, this->func)
  195. {
  196. block->upwardExposedUses = nullptr;
  197. block->upwardExposedFields = nullptr;
  198. block->typesNeedingKnownObjectLayout = nullptr;
  199. block->fieldHoistCandidates = nullptr;
  200. block->slotDeadStoreCandidates = nullptr;
  201. block->byteCodeUpwardExposedUsed = nullptr;
  202. #if DBG
  203. block->byteCodeRestoreSyms = nullptr;
  204. #endif
  205. block->tempNumberTracker = nullptr;
  206. block->tempObjectTracker = nullptr;
  207. #if DBG
  208. block->tempObjectVerifyTracker = nullptr;
  209. #endif
  210. block->stackSymToFinalType = nullptr;
  211. block->stackSymToGuardedProperties = nullptr;
  212. block->stackSymToWriteGuardsMap = nullptr;
  213. block->cloneStrCandidates = nullptr;
  214. block->noImplicitCallUses = nullptr;
  215. block->noImplicitCallNoMissingValuesUses = nullptr;
  216. block->noImplicitCallNativeArrayUses = nullptr;
  217. block->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  218. block->noImplicitCallArrayLengthSymUses = nullptr;
  219. block->couldRemoveNegZeroBailoutForDef = nullptr;
  220. if (block->loop != nullptr)
  221. {
  222. block->loop->hasDeadStoreCollectionPass = false;
  223. block->loop->hasDeadStorePrepass = false;
  224. }
  225. }
  226. NEXT_BLOCK_IN_FUNC_DEAD_OR_ALIVE;
  227. }
  228. /*
  229. * We Insert ArgIns at the start of the function for all the formals.
  230. * Unused formals will be deadstored during the deadstore pass.
  231. * We need ArgIns only for the outermost function(inliner).
  232. */
  233. void
  234. BackwardPass::InsertArgInsForFormals()
  235. {
  236. if (func->IsStackArgsEnabled() && !func->GetJITFunctionBody()->HasImplicitArgIns())
  237. {
  238. IR::Instr * insertAfterInstr = func->m_headInstr->m_next;
  239. AssertMsg(insertAfterInstr->IsLabelInstr(), "First Instr of the first block should always have a label");
  240. Js::ArgSlot paramsCount = insertAfterInstr->m_func->GetJITFunctionBody()->GetInParamsCount() - 1;
  241. IR::Instr * argInInstr = nullptr;
  242. for (Js::ArgSlot argumentIndex = 1; argumentIndex <= paramsCount; argumentIndex++)
  243. {
  244. IR::SymOpnd * srcOpnd;
  245. StackSym * symSrc = StackSym::NewParamSlotSym(argumentIndex + 1, func);
  246. StackSym * symDst = StackSym::New(func);
  247. IR::RegOpnd * dstOpnd = IR::RegOpnd::New(symDst, TyVar, func);
  248. func->SetArgOffset(symSrc, (argumentIndex + LowererMD::GetFormalParamOffset()) * MachPtr);
  249. srcOpnd = IR::SymOpnd::New(symSrc, TyVar, func);
  250. argInInstr = IR::Instr::New(Js::OpCode::ArgIn_A, dstOpnd, srcOpnd, func);
  251. insertAfterInstr->InsertAfter(argInInstr);
  252. insertAfterInstr = argInInstr;
  253. AssertMsg(!func->HasStackSymForFormal(argumentIndex - 1), "Already has a stack sym for this formal?");
  254. this->func->TrackStackSymForFormalIndex(argumentIndex - 1, symDst);
  255. }
  256. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && paramsCount > 0)
  257. {
  258. Output::Print(_u("StackArgFormals : %s (%d) :Inserting ArgIn_A for LdSlot (formals) in the start of Deadstore pass. \n"), func->GetJITFunctionBody()->GetDisplayName(), func->GetFunctionNumber());
  259. Output::Flush();
  260. }
  261. }
  262. }
  263. void
  264. BackwardPass::MarkScopeObjSymUseForStackArgOpt()
  265. {
  266. IR::Instr * instr = this->currentInstr;
  267. if (tag == Js::DeadStorePhase)
  268. {
  269. if (instr->DoStackArgsOpt(this->func) && instr->m_func->GetScopeObjSym() != nullptr)
  270. {
  271. if (this->currentBlock->byteCodeUpwardExposedUsed == nullptr)
  272. {
  273. this->currentBlock->byteCodeUpwardExposedUsed = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  274. }
  275. this->currentBlock->byteCodeUpwardExposedUsed->Set(instr->m_func->GetScopeObjSym()->m_id);
  276. }
  277. }
  278. }
  279. void
  280. BackwardPass::ProcessBailOnStackArgsOutOfActualsRange()
  281. {
  282. IR::Instr * instr = this->currentInstr;
  283. if (tag == Js::DeadStorePhase &&
  284. (instr->m_opcode == Js::OpCode::LdElemI_A || instr->m_opcode == Js::OpCode::TypeofElem) &&
  285. instr->HasBailOutInfo() && !IsPrePass())
  286. {
  287. if (instr->DoStackArgsOpt(this->func))
  288. {
  289. AssertMsg(instr->GetBailOutKind() & IR::BailOnStackArgsOutOfActualsRange, "Stack args bail out is not set when the optimization is turned on? ");
  290. if (instr->GetBailOutKind() & ~IR::BailOnStackArgsOutOfActualsRange)
  291. {
  292. Assert(instr->GetBailOutKind() == (IR::BailOnStackArgsOutOfActualsRange | IR::BailOutOnImplicitCallsPreOp));
  293. //We are sure at this point, that we will not have any implicit calls as we wouldn't have done this optimization in the first place.
  294. instr->SetBailOutKind(IR::BailOnStackArgsOutOfActualsRange);
  295. }
  296. }
  297. else if (instr->GetBailOutKind() & IR::BailOnStackArgsOutOfActualsRange)
  298. {
  299. //If we don't decide to do StackArgs, then remove the bail out at this point.
  300. //We would have optimistically set the bailout in the forward pass, and by the end of forward pass - we
  301. //turned off stack args for some reason. So we are removing it in the deadstore pass.
  302. IR::BailOutKind bailOutKind = instr->GetBailOutKind() & ~IR::BailOnStackArgsOutOfActualsRange;
  303. if (bailOutKind == IR::BailOutInvalid)
  304. {
  305. instr->ClearBailOutInfo();
  306. }
  307. else
  308. {
  309. instr->SetBailOutKind(bailOutKind);
  310. }
  311. }
  312. }
  313. }
  314. void
  315. BackwardPass::Optimize()
  316. {
  317. if (tag == Js::BackwardPhase && PHASE_OFF(tag, this->func))
  318. {
  319. return;
  320. }
  321. if (tag == Js::DeadStorePhase)
  322. {
  323. if (!this->func->DoLoopFastPaths() || !this->func->DoFastPaths())
  324. {
  325. //arguments[] access is similar to array fast path hence disable when array fastpath is disabled.
  326. //loopFastPath is always true except explicitly disabled
  327. //defaultDoFastPath can be false when we the source code size is huge
  328. func->SetHasStackArgs(false);
  329. }
  330. InsertArgInsForFormals();
  331. }
  332. NoRecoverMemoryJitArenaAllocator localAlloc(tag == Js::BackwardPhase? _u("BE-Backward") : _u("BE-DeadStore"),
  333. this->func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  334. this->tempAlloc = &localAlloc;
  335. #if DBG_DUMP
  336. if (this->IsTraceEnabled())
  337. {
  338. this->func->DumpHeader();
  339. }
  340. #endif
  341. this->CleanupBackwardPassInfoInFlowGraph();
  342. // Info about whether a sym is used in a way in which -0 differs from +0, or whether the sym is used in a way in which an
  343. // int32 overflow when generating the value of the sym matters, in the current block. The info is transferred to
  344. // instructions that define the sym in the current block as they are encountered. The info in these bit vectors is discarded
  345. // after optimizing each block, so the only info that remains for GlobOpt is that which is transferred to instructions.
  346. BVSparse<JitArenaAllocator> localNegativeZeroDoesNotMatterBySymId(tempAlloc);
  347. negativeZeroDoesNotMatterBySymId = &localNegativeZeroDoesNotMatterBySymId;
  348. BVSparse<JitArenaAllocator> localSymUsedOnlyForBitOpsBySymId(tempAlloc);
  349. symUsedOnlyForBitOpsBySymId = &localSymUsedOnlyForBitOpsBySymId;
  350. BVSparse<JitArenaAllocator> localSymUsedOnlyForNumberBySymId(tempAlloc);
  351. symUsedOnlyForNumberBySymId = &localSymUsedOnlyForNumberBySymId;
  352. BVSparse<JitArenaAllocator> localIntOverflowDoesNotMatterBySymId(tempAlloc);
  353. intOverflowDoesNotMatterBySymId = &localIntOverflowDoesNotMatterBySymId;
  354. BVSparse<JitArenaAllocator> localIntOverflowDoesNotMatterInRangeBySymId(tempAlloc);
  355. intOverflowDoesNotMatterInRangeBySymId = &localIntOverflowDoesNotMatterInRangeBySymId;
  356. BVSparse<JitArenaAllocator> localCandidateSymsRequiredToBeInt(tempAlloc);
  357. candidateSymsRequiredToBeInt = &localCandidateSymsRequiredToBeInt;
  358. BVSparse<JitArenaAllocator> localCandidateSymsRequiredToBeLossyInt(tempAlloc);
  359. candidateSymsRequiredToBeLossyInt = &localCandidateSymsRequiredToBeLossyInt;
  360. intOverflowCurrentlyMattersInRange = true;
  361. FloatSymEquivalenceMap localFloatSymEquivalenceMap(tempAlloc);
  362. floatSymEquivalenceMap = &localFloatSymEquivalenceMap;
  363. NumberTempRepresentativePropertySymMap localNumberTempRepresentativePropertySym(tempAlloc);
  364. numberTempRepresentativePropertySym = &localNumberTempRepresentativePropertySym;
  365. FOREACH_BLOCK_BACKWARD_IN_FUNC_DEAD_OR_ALIVE(block, this->func)
  366. {
  367. this->OptBlock(block);
  368. }
  369. NEXT_BLOCK_BACKWARD_IN_FUNC_DEAD_OR_ALIVE;
  370. if (this->tag == Js::DeadStorePhase && !PHASE_OFF(Js::MemOpPhase, this->func))
  371. {
  372. this->RemoveEmptyLoops();
  373. }
  374. this->func->m_fg->hasBackwardPassInfo = true;
  375. if(DoTrackCompoundedIntOverflow())
  376. {
  377. // Tracking int overflow makes use of a scratch field in stack syms, which needs to be cleared
  378. func->m_symTable->ClearStackSymScratch();
  379. }
  380. #if DBG_DUMP
  381. if (PHASE_STATS(this->tag, this->func))
  382. {
  383. this->func->DumpHeader();
  384. Output::Print(this->tag == Js::BackwardPhase? _u("Backward Phase Stats:\n") : _u("Deadstore Phase Stats:\n"));
  385. if (this->DoDeadStore())
  386. {
  387. Output::Print(_u(" Deadstore : %3d\n"), this->numDeadStore);
  388. }
  389. if (this->DoMarkTempNumbers())
  390. {
  391. Output::Print(_u(" Temp Number : %3d\n"), this->numMarkTempNumber);
  392. Output::Print(_u(" Transferred Temp Number: %3d\n"), this->numMarkTempNumberTransferred);
  393. }
  394. if (this->DoMarkTempObjects())
  395. {
  396. Output::Print(_u(" Temp Object : %3d\n"), this->numMarkTempObject);
  397. }
  398. }
  399. #endif
  400. }
  401. void
  402. BackwardPass::MergeSuccBlocksInfo(BasicBlock * block)
  403. {
  404. // Can't reuse the bv in the current block, because its successor can be itself.
  405. TempNumberTracker * tempNumberTracker = nullptr;
  406. TempObjectTracker * tempObjectTracker = nullptr;
  407. #if DBG
  408. TempObjectVerifyTracker * tempObjectVerifyTracker = nullptr;
  409. #endif
  410. HashTable<AddPropertyCacheBucket> * stackSymToFinalType = nullptr;
  411. HashTable<ObjTypeGuardBucket> * stackSymToGuardedProperties = nullptr;
  412. HashTable<ObjWriteGuardBucket> * stackSymToWriteGuardsMap = nullptr;
  413. BVSparse<JitArenaAllocator> * cloneStrCandidates = nullptr;
  414. BVSparse<JitArenaAllocator> * noImplicitCallUses = nullptr;
  415. BVSparse<JitArenaAllocator> * noImplicitCallNoMissingValuesUses = nullptr;
  416. BVSparse<JitArenaAllocator> * noImplicitCallNativeArrayUses = nullptr;
  417. BVSparse<JitArenaAllocator> * noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  418. BVSparse<JitArenaAllocator> * noImplicitCallArrayLengthSymUses = nullptr;
  419. BVSparse<JitArenaAllocator> * upwardExposedUses = nullptr;
  420. BVSparse<JitArenaAllocator> * upwardExposedFields = nullptr;
  421. BVSparse<JitArenaAllocator> * typesNeedingKnownObjectLayout = nullptr;
  422. BVSparse<JitArenaAllocator> * fieldHoistCandidates = nullptr;
  423. BVSparse<JitArenaAllocator> * slotDeadStoreCandidates = nullptr;
  424. BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = nullptr;
  425. BVSparse<JitArenaAllocator> * couldRemoveNegZeroBailoutForDef = nullptr;
  426. #if DBG
  427. uint byteCodeLocalsCount = func->GetJITFunctionBody()->GetLocalsCount();
  428. StackSym ** byteCodeRestoreSyms = nullptr;
  429. #endif
  430. Assert(!block->isDead || block->GetSuccList()->Empty());
  431. if (this->DoByteCodeUpwardExposedUsed())
  432. {
  433. byteCodeUpwardExposedUsed = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  434. #if DBG
  435. byteCodeRestoreSyms = JitAnewArrayZ(this->tempAlloc, StackSym *, byteCodeLocalsCount);
  436. #endif
  437. }
  438. #if DBG
  439. if (!IsCollectionPass() && this->DoMarkTempObjectVerify())
  440. {
  441. tempObjectVerifyTracker = JitAnew(this->tempAlloc, TempObjectVerifyTracker, this->tempAlloc, block->loop != nullptr);
  442. }
  443. #endif
  444. if (!block->isDead)
  445. {
  446. bool keepUpwardExposed = (this->tag == Js::BackwardPhase);
  447. JitArenaAllocator *upwardExposedArena = nullptr;
  448. if(!IsCollectionPass())
  449. {
  450. upwardExposedArena = keepUpwardExposed ? this->globOpt->alloc : this->tempAlloc;
  451. upwardExposedUses = JitAnew(upwardExposedArena, BVSparse<JitArenaAllocator>, upwardExposedArena);
  452. upwardExposedFields = JitAnew(upwardExposedArena, BVSparse<JitArenaAllocator>, upwardExposedArena);
  453. if (this->tag == Js::DeadStorePhase)
  454. {
  455. typesNeedingKnownObjectLayout = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  456. }
  457. if (this->DoFieldHoistCandidates())
  458. {
  459. fieldHoistCandidates = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  460. }
  461. if (this->DoDeadStoreSlots())
  462. {
  463. slotDeadStoreCandidates = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  464. }
  465. if (this->DoMarkTempNumbers())
  466. {
  467. tempNumberTracker = JitAnew(this->tempAlloc, TempNumberTracker, this->tempAlloc, block->loop != nullptr);
  468. }
  469. if (this->DoMarkTempObjects())
  470. {
  471. tempObjectTracker = JitAnew(this->tempAlloc, TempObjectTracker, this->tempAlloc, block->loop != nullptr);
  472. }
  473. noImplicitCallUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  474. noImplicitCallNoMissingValuesUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  475. noImplicitCallNativeArrayUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  476. noImplicitCallJsArrayHeadSegmentSymUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  477. noImplicitCallArrayLengthSymUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  478. if (this->tag == Js::BackwardPhase)
  479. {
  480. cloneStrCandidates = JitAnew(this->globOpt->alloc, BVSparse<JitArenaAllocator>, this->globOpt->alloc);
  481. }
  482. else
  483. {
  484. couldRemoveNegZeroBailoutForDef = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  485. }
  486. }
  487. bool firstSucc = true;
  488. FOREACH_SUCCESSOR_BLOCK(blockSucc, block)
  489. {
  490. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  491. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  492. #endif
  493. // save the byteCodeUpwardExposedUsed from deleting for the block right after the memop loop
  494. if (this->tag == Js::DeadStorePhase && !this->IsPrePass() && globOpt->HasMemOp(block->loop) && blockSucc->loop != block->loop)
  495. {
  496. Assert(block->loop->memOpInfo->inductionVariablesUsedAfterLoop == nullptr);
  497. block->loop->memOpInfo->inductionVariablesUsedAfterLoop = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  498. block->loop->memOpInfo->inductionVariablesUsedAfterLoop->Or(blockSucc->byteCodeUpwardExposedUsed);
  499. block->loop->memOpInfo->inductionVariablesUsedAfterLoop->Or(blockSucc->upwardExposedUses);
  500. }
  501. bool deleteData = false;
  502. if (!blockSucc->isLoopHeader && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  503. {
  504. Assert(blockSucc->GetDataUseCount() != 0);
  505. deleteData = (blockSucc->DecrementDataUseCount() == 0);
  506. }
  507. Assert((byteCodeUpwardExposedUsed == nullptr) == !this->DoByteCodeUpwardExposedUsed());
  508. if (byteCodeUpwardExposedUsed && blockSucc->byteCodeUpwardExposedUsed)
  509. {
  510. byteCodeUpwardExposedUsed->Or(blockSucc->byteCodeUpwardExposedUsed);
  511. if (this->tag == Js::DeadStorePhase)
  512. {
  513. #if DBG
  514. for (uint i = 0; i < byteCodeLocalsCount; i++)
  515. {
  516. if (byteCodeRestoreSyms[i] == nullptr)
  517. {
  518. byteCodeRestoreSyms[i] = blockSucc->byteCodeRestoreSyms[i];
  519. }
  520. else
  521. {
  522. Assert(blockSucc->byteCodeRestoreSyms[i] == nullptr
  523. || byteCodeRestoreSyms[i] == blockSucc->byteCodeRestoreSyms[i]);
  524. }
  525. }
  526. #endif
  527. if (deleteData)
  528. {
  529. // byteCodeUpwardExposedUsed is required to populate the writeThroughSymbolsSet for the try region. So, don't delete it in the backwards pass.
  530. JitAdelete(this->tempAlloc, blockSucc->byteCodeUpwardExposedUsed);
  531. blockSucc->byteCodeUpwardExposedUsed = nullptr;
  532. }
  533. }
  534. #if DBG
  535. if (deleteData)
  536. {
  537. JitAdeleteArray(this->tempAlloc, byteCodeLocalsCount, blockSucc->byteCodeRestoreSyms);
  538. blockSucc->byteCodeRestoreSyms = nullptr;
  539. }
  540. #endif
  541. }
  542. else
  543. {
  544. Assert(blockSucc->byteCodeUpwardExposedUsed == nullptr);
  545. Assert(blockSucc->byteCodeRestoreSyms == nullptr);
  546. }
  547. if(IsCollectionPass())
  548. {
  549. continue;
  550. }
  551. Assert((blockSucc->upwardExposedUses != nullptr)
  552. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop))));
  553. Assert((blockSucc->upwardExposedFields != nullptr)
  554. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop))));
  555. Assert((blockSucc->typesNeedingKnownObjectLayout != nullptr)
  556. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  557. || this->tag != Js::DeadStorePhase);
  558. Assert((blockSucc->fieldHoistCandidates != nullptr)
  559. || blockSucc->isLoopHeader
  560. || !this->DoFieldHoistCandidates(blockSucc->loop));
  561. Assert((blockSucc->slotDeadStoreCandidates != nullptr)
  562. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  563. || !this->DoDeadStoreSlots());
  564. Assert((blockSucc->tempNumberTracker != nullptr)
  565. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  566. || !this->DoMarkTempNumbers());
  567. Assert((blockSucc->tempObjectTracker != nullptr)
  568. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  569. || !this->DoMarkTempObjects());
  570. Assert((blockSucc->tempObjectVerifyTracker != nullptr)
  571. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  572. || !this->DoMarkTempObjectVerify());
  573. if (blockSucc->upwardExposedUses != nullptr)
  574. {
  575. upwardExposedUses->Or(blockSucc->upwardExposedUses);
  576. if (deleteData && (!keepUpwardExposed
  577. || (this->IsPrePass() && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)))
  578. {
  579. JitAdelete(upwardExposedArena, blockSucc->upwardExposedUses);
  580. blockSucc->upwardExposedUses = nullptr;
  581. }
  582. }
  583. if (blockSucc->upwardExposedFields != nullptr)
  584. {
  585. upwardExposedFields->Or(blockSucc->upwardExposedFields);
  586. if (deleteData && (!keepUpwardExposed
  587. || (this->IsPrePass() && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)))
  588. {
  589. JitAdelete(upwardExposedArena, blockSucc->upwardExposedFields);
  590. blockSucc->upwardExposedFields = nullptr;
  591. }
  592. }
  593. if (blockSucc->typesNeedingKnownObjectLayout != nullptr)
  594. {
  595. typesNeedingKnownObjectLayout->Or(blockSucc->typesNeedingKnownObjectLayout);
  596. if (deleteData)
  597. {
  598. JitAdelete(this->tempAlloc, blockSucc->typesNeedingKnownObjectLayout);
  599. blockSucc->typesNeedingKnownObjectLayout = nullptr;
  600. }
  601. }
  602. if (fieldHoistCandidates && blockSucc->fieldHoistCandidates != nullptr)
  603. {
  604. fieldHoistCandidates->Or(blockSucc->fieldHoistCandidates);
  605. if (deleteData)
  606. {
  607. JitAdelete(this->tempAlloc, blockSucc->fieldHoistCandidates);
  608. blockSucc->fieldHoistCandidates = nullptr;
  609. }
  610. }
  611. if (blockSucc->slotDeadStoreCandidates != nullptr)
  612. {
  613. slotDeadStoreCandidates->And(blockSucc->slotDeadStoreCandidates);
  614. if (deleteData)
  615. {
  616. JitAdelete(this->tempAlloc, blockSucc->slotDeadStoreCandidates);
  617. blockSucc->slotDeadStoreCandidates = nullptr;
  618. }
  619. }
  620. if (blockSucc->tempNumberTracker != nullptr)
  621. {
  622. Assert((blockSucc->loop != nullptr) == blockSucc->tempNumberTracker->HasTempTransferDependencies());
  623. tempNumberTracker->MergeData(blockSucc->tempNumberTracker, deleteData);
  624. if (deleteData)
  625. {
  626. blockSucc->tempNumberTracker = nullptr;
  627. }
  628. }
  629. if (blockSucc->tempObjectTracker != nullptr)
  630. {
  631. Assert((blockSucc->loop != nullptr) == blockSucc->tempObjectTracker->HasTempTransferDependencies());
  632. tempObjectTracker->MergeData(blockSucc->tempObjectTracker, deleteData);
  633. if (deleteData)
  634. {
  635. blockSucc->tempObjectTracker = nullptr;
  636. }
  637. }
  638. #if DBG
  639. if (blockSucc->tempObjectVerifyTracker != nullptr)
  640. {
  641. Assert((blockSucc->loop != nullptr) == blockSucc->tempObjectVerifyTracker->HasTempTransferDependencies());
  642. tempObjectVerifyTracker->MergeData(blockSucc->tempObjectVerifyTracker, deleteData);
  643. if (deleteData)
  644. {
  645. blockSucc->tempObjectVerifyTracker = nullptr;
  646. }
  647. }
  648. #endif
  649. PHASE_PRINT_TRACE(Js::ObjTypeSpecStorePhase, this->func,
  650. _u("ObjTypeSpecStore: func %s, edge %d => %d: "),
  651. this->func->GetDebugNumberSet(debugStringBuffer),
  652. block->GetBlockNum(), blockSucc->GetBlockNum());
  653. auto fixupFrom = [block, blockSucc, this](Bucket<AddPropertyCacheBucket> &bucket)
  654. {
  655. AddPropertyCacheBucket *fromData = &bucket.element;
  656. if (fromData->GetInitialType() == nullptr ||
  657. fromData->GetFinalType() == fromData->GetInitialType())
  658. {
  659. return;
  660. }
  661. this->InsertTypeTransitionsAtPriorSuccessors(block, blockSucc, bucket.value, fromData);
  662. };
  663. auto fixupTo = [blockSucc, this](Bucket<AddPropertyCacheBucket> &bucket)
  664. {
  665. AddPropertyCacheBucket *toData = &bucket.element;
  666. if (toData->GetInitialType() == nullptr ||
  667. toData->GetFinalType() == toData->GetInitialType())
  668. {
  669. return;
  670. }
  671. this->InsertTypeTransitionAtBlock(blockSucc, bucket.value, toData);
  672. };
  673. if (blockSucc->stackSymToFinalType != nullptr)
  674. {
  675. #if DBG_DUMP
  676. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  677. {
  678. blockSucc->stackSymToFinalType->Dump();
  679. }
  680. #endif
  681. if (firstSucc)
  682. {
  683. stackSymToFinalType = blockSucc->stackSymToFinalType->Copy();
  684. }
  685. else if (stackSymToFinalType != nullptr)
  686. {
  687. if (this->IsPrePass())
  688. {
  689. stackSymToFinalType->And(blockSucc->stackSymToFinalType);
  690. }
  691. else
  692. {
  693. // Insert any type transitions that can't be merged past this point.
  694. stackSymToFinalType->AndWithFixup(blockSucc->stackSymToFinalType, fixupFrom, fixupTo);
  695. }
  696. }
  697. else if (!this->IsPrePass())
  698. {
  699. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, blockSucc->stackSymToFinalType)
  700. {
  701. fixupTo(bucket);
  702. }
  703. NEXT_HASHTABLE_ENTRY;
  704. }
  705. if (deleteData)
  706. {
  707. blockSucc->stackSymToFinalType->Delete();
  708. blockSucc->stackSymToFinalType = nullptr;
  709. }
  710. }
  711. else
  712. {
  713. PHASE_PRINT_TRACE(Js::ObjTypeSpecStorePhase, this->func, _u("null\n"));
  714. if (stackSymToFinalType)
  715. {
  716. if (!this->IsPrePass())
  717. {
  718. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, stackSymToFinalType)
  719. {
  720. fixupFrom(bucket);
  721. }
  722. NEXT_HASHTABLE_ENTRY;
  723. }
  724. stackSymToFinalType->Delete();
  725. stackSymToFinalType = nullptr;
  726. }
  727. }
  728. if (tag == Js::BackwardPhase)
  729. {
  730. if (blockSucc->cloneStrCandidates != nullptr)
  731. {
  732. Assert(cloneStrCandidates != nullptr);
  733. cloneStrCandidates->Or(blockSucc->cloneStrCandidates);
  734. if (deleteData)
  735. {
  736. JitAdelete(this->globOpt->alloc, blockSucc->cloneStrCandidates);
  737. blockSucc->cloneStrCandidates = nullptr;
  738. }
  739. }
  740. #if DBG_DUMP
  741. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  742. {
  743. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  744. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s), write guard symbols on edge %d => %d: "),
  745. this->func->GetTopFunc()->GetJITFunctionBody()->GetDisplayName(),
  746. this->func->GetTopFunc()->GetDebugNumberSet(debugStringBuffer),
  747. this->func->GetJITFunctionBody()->GetDisplayName(),
  748. this->func->GetDebugNumberSet(debugStringBuffer2), block->GetBlockNum(),
  749. blockSucc->GetBlockNum());
  750. }
  751. #endif
  752. if (blockSucc->stackSymToWriteGuardsMap != nullptr)
  753. {
  754. #if DBG_DUMP
  755. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  756. {
  757. Output::Print(_u("\n"));
  758. blockSucc->stackSymToWriteGuardsMap->Dump();
  759. }
  760. #endif
  761. if (stackSymToWriteGuardsMap == nullptr)
  762. {
  763. stackSymToWriteGuardsMap = blockSucc->stackSymToWriteGuardsMap->Copy();
  764. }
  765. else
  766. {
  767. stackSymToWriteGuardsMap->Or(
  768. blockSucc->stackSymToWriteGuardsMap, &BackwardPass::MergeWriteGuards);
  769. }
  770. if (deleteData)
  771. {
  772. blockSucc->stackSymToWriteGuardsMap->Delete();
  773. blockSucc->stackSymToWriteGuardsMap = nullptr;
  774. }
  775. }
  776. else
  777. {
  778. #if DBG_DUMP
  779. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  780. {
  781. Output::Print(_u("null\n"));
  782. }
  783. #endif
  784. }
  785. }
  786. else
  787. {
  788. #if DBG_DUMP
  789. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  790. {
  791. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  792. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s), guarded property operations on edge %d => %d: \n"),
  793. this->func->GetTopFunc()->GetJITFunctionBody()->GetDisplayName(),
  794. this->func->GetTopFunc()->GetDebugNumberSet(debugStringBuffer),
  795. this->func->GetJITFunctionBody()->GetDisplayName(),
  796. this->func->GetDebugNumberSet(debugStringBuffer2),
  797. block->GetBlockNum(), blockSucc->GetBlockNum());
  798. }
  799. #endif
  800. if (blockSucc->stackSymToGuardedProperties != nullptr)
  801. {
  802. #if DBG_DUMP
  803. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  804. {
  805. blockSucc->stackSymToGuardedProperties->Dump();
  806. Output::Print(_u("\n"));
  807. }
  808. #endif
  809. if (stackSymToGuardedProperties == nullptr)
  810. {
  811. stackSymToGuardedProperties = blockSucc->stackSymToGuardedProperties->Copy();
  812. }
  813. else
  814. {
  815. stackSymToGuardedProperties->Or(
  816. blockSucc->stackSymToGuardedProperties, &BackwardPass::MergeGuardedProperties);
  817. }
  818. if (deleteData)
  819. {
  820. blockSucc->stackSymToGuardedProperties->Delete();
  821. blockSucc->stackSymToGuardedProperties = nullptr;
  822. }
  823. }
  824. else
  825. {
  826. #if DBG_DUMP
  827. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  828. {
  829. Output::Print(_u("null\n"));
  830. }
  831. #endif
  832. }
  833. if (blockSucc->couldRemoveNegZeroBailoutForDef != nullptr)
  834. {
  835. couldRemoveNegZeroBailoutForDef->And(blockSucc->couldRemoveNegZeroBailoutForDef);
  836. if (deleteData)
  837. {
  838. JitAdelete(this->tempAlloc, blockSucc->couldRemoveNegZeroBailoutForDef);
  839. blockSucc->couldRemoveNegZeroBailoutForDef = nullptr;
  840. }
  841. }
  842. }
  843. if (blockSucc->noImplicitCallUses != nullptr)
  844. {
  845. noImplicitCallUses->Or(blockSucc->noImplicitCallUses);
  846. if (deleteData)
  847. {
  848. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallUses);
  849. blockSucc->noImplicitCallUses = nullptr;
  850. }
  851. }
  852. if (blockSucc->noImplicitCallNoMissingValuesUses != nullptr)
  853. {
  854. noImplicitCallNoMissingValuesUses->Or(blockSucc->noImplicitCallNoMissingValuesUses);
  855. if (deleteData)
  856. {
  857. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallNoMissingValuesUses);
  858. blockSucc->noImplicitCallNoMissingValuesUses = nullptr;
  859. }
  860. }
  861. if (blockSucc->noImplicitCallNativeArrayUses != nullptr)
  862. {
  863. noImplicitCallNativeArrayUses->Or(blockSucc->noImplicitCallNativeArrayUses);
  864. if (deleteData)
  865. {
  866. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallNativeArrayUses);
  867. blockSucc->noImplicitCallNativeArrayUses = nullptr;
  868. }
  869. }
  870. if (blockSucc->noImplicitCallJsArrayHeadSegmentSymUses != nullptr)
  871. {
  872. noImplicitCallJsArrayHeadSegmentSymUses->Or(blockSucc->noImplicitCallJsArrayHeadSegmentSymUses);
  873. if (deleteData)
  874. {
  875. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallJsArrayHeadSegmentSymUses);
  876. blockSucc->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  877. }
  878. }
  879. if (blockSucc->noImplicitCallArrayLengthSymUses != nullptr)
  880. {
  881. noImplicitCallArrayLengthSymUses->Or(blockSucc->noImplicitCallArrayLengthSymUses);
  882. if (deleteData)
  883. {
  884. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallArrayLengthSymUses);
  885. blockSucc->noImplicitCallArrayLengthSymUses = nullptr;
  886. }
  887. }
  888. firstSucc = false;
  889. }
  890. NEXT_SUCCESSOR_BLOCK;
  891. #if DBG_DUMP
  892. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  893. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  894. {
  895. Output::Print(_u("ObjTypeSpecStore: func %s, block %d: "),
  896. this->func->GetDebugNumberSet(debugStringBuffer),
  897. block->GetBlockNum());
  898. if (stackSymToFinalType)
  899. {
  900. stackSymToFinalType->Dump();
  901. }
  902. else
  903. {
  904. Output::Print(_u("null\n"));
  905. }
  906. }
  907. if (PHASE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  908. {
  909. Output::Print(_u("ObjTypeSpec: func %s, block %d, guarded properties:\n"),
  910. this->func->GetDebugNumberSet(debugStringBuffer), block->GetBlockNum());
  911. if (stackSymToGuardedProperties)
  912. {
  913. stackSymToGuardedProperties->Dump();
  914. Output::Print(_u("\n"));
  915. }
  916. else
  917. {
  918. Output::Print(_u("null\n"));
  919. }
  920. }
  921. if (PHASE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  922. {
  923. Output::Print(_u("ObjTypeSpec: func %s, block %d, write guards: "),
  924. this->func->GetDebugNumberSet(debugStringBuffer), block->GetBlockNum());
  925. if (stackSymToWriteGuardsMap)
  926. {
  927. Output::Print(_u("\n"));
  928. stackSymToWriteGuardsMap->Dump();
  929. Output::Print(_u("\n"));
  930. }
  931. else
  932. {
  933. Output::Print(_u("null\n"));
  934. }
  935. }
  936. #endif
  937. }
  938. #if DBG
  939. if (tempObjectVerifyTracker)
  940. {
  941. FOREACH_DEAD_SUCCESSOR_BLOCK(deadBlockSucc, block)
  942. {
  943. Assert(deadBlockSucc->tempObjectVerifyTracker || deadBlockSucc->isLoopHeader);
  944. if (deadBlockSucc->tempObjectVerifyTracker != nullptr)
  945. {
  946. Assert((deadBlockSucc->loop != nullptr) == deadBlockSucc->tempObjectVerifyTracker->HasTempTransferDependencies());
  947. // Dead block don't effect non temp use, we only need to carry the removed use bit vector forward
  948. // and put all the upward exposed use to the set that we might found out to be mark temp
  949. // after globopt
  950. tempObjectVerifyTracker->MergeDeadData(deadBlockSucc);
  951. }
  952. if (!byteCodeUpwardExposedUsed)
  953. {
  954. if (!deadBlockSucc->isLoopHeader && deadBlockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  955. {
  956. Assert(deadBlockSucc->GetDataUseCount() != 0);
  957. if (deadBlockSucc->DecrementDataUseCount() == 0)
  958. {
  959. this->DeleteBlockData(deadBlockSucc);
  960. }
  961. }
  962. }
  963. }
  964. NEXT_DEAD_SUCCESSOR_BLOCK;
  965. }
  966. #endif
  967. if (byteCodeUpwardExposedUsed)
  968. {
  969. FOREACH_DEAD_SUCCESSOR_BLOCK(deadBlockSucc, block)
  970. {
  971. Assert(deadBlockSucc->byteCodeUpwardExposedUsed || deadBlockSucc->isLoopHeader);
  972. if (deadBlockSucc->byteCodeUpwardExposedUsed)
  973. {
  974. byteCodeUpwardExposedUsed->Or(deadBlockSucc->byteCodeUpwardExposedUsed);
  975. if (this->tag == Js::DeadStorePhase)
  976. {
  977. #if DBG
  978. for (uint i = 0; i < byteCodeLocalsCount; i++)
  979. {
  980. if (byteCodeRestoreSyms[i] == nullptr)
  981. {
  982. byteCodeRestoreSyms[i] = deadBlockSucc->byteCodeRestoreSyms[i];
  983. }
  984. else
  985. {
  986. Assert(deadBlockSucc->byteCodeRestoreSyms[i] == nullptr
  987. || byteCodeRestoreSyms[i] == deadBlockSucc->byteCodeRestoreSyms[i]);
  988. }
  989. }
  990. #endif
  991. }
  992. }
  993. if (!deadBlockSucc->isLoopHeader && deadBlockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  994. {
  995. Assert(deadBlockSucc->GetDataUseCount() != 0);
  996. if (deadBlockSucc->DecrementDataUseCount() == 0)
  997. {
  998. this->DeleteBlockData(deadBlockSucc);
  999. }
  1000. }
  1001. }
  1002. NEXT_DEAD_SUCCESSOR_BLOCK;
  1003. }
  1004. if (block->isLoopHeader)
  1005. {
  1006. this->DeleteBlockData(block);
  1007. }
  1008. else
  1009. {
  1010. if(block->GetDataUseCount() == 0)
  1011. {
  1012. Assert(block->slotDeadStoreCandidates == nullptr);
  1013. Assert(block->tempNumberTracker == nullptr);
  1014. Assert(block->tempObjectTracker == nullptr);
  1015. Assert(block->tempObjectVerifyTracker == nullptr);
  1016. Assert(block->upwardExposedUses == nullptr);
  1017. Assert(block->upwardExposedFields == nullptr);
  1018. Assert(block->typesNeedingKnownObjectLayout == nullptr);
  1019. Assert(block->fieldHoistCandidates == nullptr);
  1020. // byteCodeUpwardExposedUsed is required to populate the writeThroughSymbolsSet for the try region in the backwards pass
  1021. Assert(block->byteCodeUpwardExposedUsed == nullptr || (this->tag == Js::BackwardPhase && this->func->HasTry() && this->func->DoOptimizeTryCatch()));
  1022. Assert(block->byteCodeRestoreSyms == nullptr);
  1023. Assert(block->stackSymToFinalType == nullptr);
  1024. Assert(block->stackSymToGuardedProperties == nullptr);
  1025. Assert(block->stackSymToWriteGuardsMap == nullptr);
  1026. Assert(block->cloneStrCandidates == nullptr);
  1027. Assert(block->noImplicitCallUses == nullptr);
  1028. Assert(block->noImplicitCallNoMissingValuesUses == nullptr);
  1029. Assert(block->noImplicitCallNativeArrayUses == nullptr);
  1030. Assert(block->noImplicitCallJsArrayHeadSegmentSymUses == nullptr);
  1031. Assert(block->noImplicitCallArrayLengthSymUses == nullptr);
  1032. Assert(block->couldRemoveNegZeroBailoutForDef == nullptr);
  1033. }
  1034. else
  1035. {
  1036. // The collection pass sometimes does not know whether it can delete a successor block's data, so it may leave some
  1037. // blocks with data intact. Delete the block data now.
  1038. Assert(block->backwardPassCurrentLoop);
  1039. Assert(block->backwardPassCurrentLoop->hasDeadStoreCollectionPass);
  1040. Assert(!block->backwardPassCurrentLoop->hasDeadStorePrepass);
  1041. DeleteBlockData(block);
  1042. }
  1043. block->backwardPassCurrentLoop = this->currentPrePassLoop;
  1044. if (this->DoByteCodeUpwardExposedUsed()
  1045. #if DBG
  1046. || this->DoMarkTempObjectVerify()
  1047. #endif
  1048. )
  1049. {
  1050. block->SetDataUseCount(block->GetPredList()->Count() + block->GetDeadPredList()->Count());
  1051. }
  1052. else
  1053. {
  1054. block->SetDataUseCount(block->GetPredList()->Count());
  1055. }
  1056. }
  1057. block->upwardExposedUses = upwardExposedUses;
  1058. block->upwardExposedFields = upwardExposedFields;
  1059. block->typesNeedingKnownObjectLayout = typesNeedingKnownObjectLayout;
  1060. block->fieldHoistCandidates = fieldHoistCandidates;
  1061. block->byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed;
  1062. #if DBG
  1063. block->byteCodeRestoreSyms = byteCodeRestoreSyms;
  1064. #endif
  1065. block->slotDeadStoreCandidates = slotDeadStoreCandidates;
  1066. block->tempNumberTracker = tempNumberTracker;
  1067. block->tempObjectTracker = tempObjectTracker;
  1068. #if DBG
  1069. block->tempObjectVerifyTracker = tempObjectVerifyTracker;
  1070. #endif
  1071. block->stackSymToFinalType = stackSymToFinalType;
  1072. block->stackSymToGuardedProperties = stackSymToGuardedProperties;
  1073. block->stackSymToWriteGuardsMap = stackSymToWriteGuardsMap;
  1074. block->cloneStrCandidates = cloneStrCandidates;
  1075. block->noImplicitCallUses = noImplicitCallUses;
  1076. block->noImplicitCallNoMissingValuesUses = noImplicitCallNoMissingValuesUses;
  1077. block->noImplicitCallNativeArrayUses = noImplicitCallNativeArrayUses;
  1078. block->noImplicitCallJsArrayHeadSegmentSymUses = noImplicitCallJsArrayHeadSegmentSymUses;
  1079. block->noImplicitCallArrayLengthSymUses = noImplicitCallArrayLengthSymUses;
  1080. block->couldRemoveNegZeroBailoutForDef = couldRemoveNegZeroBailoutForDef;
  1081. }
  1082. ObjTypeGuardBucket
  1083. BackwardPass::MergeGuardedProperties(ObjTypeGuardBucket bucket1, ObjTypeGuardBucket bucket2)
  1084. {
  1085. BVSparse<JitArenaAllocator> *guardedPropertyOps1 = bucket1.GetGuardedPropertyOps();
  1086. BVSparse<JitArenaAllocator> *guardedPropertyOps2 = bucket2.GetGuardedPropertyOps();
  1087. Assert(guardedPropertyOps1 || guardedPropertyOps2);
  1088. BVSparse<JitArenaAllocator> *mergedPropertyOps;
  1089. if (guardedPropertyOps1)
  1090. {
  1091. mergedPropertyOps = guardedPropertyOps1->CopyNew();
  1092. if (guardedPropertyOps2)
  1093. {
  1094. mergedPropertyOps->Or(guardedPropertyOps2);
  1095. }
  1096. }
  1097. else
  1098. {
  1099. mergedPropertyOps = guardedPropertyOps2->CopyNew();
  1100. }
  1101. ObjTypeGuardBucket bucket;
  1102. bucket.SetGuardedPropertyOps(mergedPropertyOps);
  1103. JITTypeHolder monoGuardType = bucket1.GetMonoGuardType();
  1104. if (monoGuardType != nullptr)
  1105. {
  1106. Assert(!bucket2.NeedsMonoCheck() || monoGuardType == bucket2.GetMonoGuardType());
  1107. }
  1108. else
  1109. {
  1110. monoGuardType = bucket2.GetMonoGuardType();
  1111. }
  1112. bucket.SetMonoGuardType(monoGuardType);
  1113. return bucket;
  1114. }
  1115. ObjWriteGuardBucket
  1116. BackwardPass::MergeWriteGuards(ObjWriteGuardBucket bucket1, ObjWriteGuardBucket bucket2)
  1117. {
  1118. BVSparse<JitArenaAllocator> *writeGuards1 = bucket1.GetWriteGuards();
  1119. BVSparse<JitArenaAllocator> *writeGuards2 = bucket2.GetWriteGuards();
  1120. Assert(writeGuards1 || writeGuards2);
  1121. BVSparse<JitArenaAllocator> *mergedWriteGuards;
  1122. if (writeGuards1)
  1123. {
  1124. mergedWriteGuards = writeGuards1->CopyNew();
  1125. if (writeGuards2)
  1126. {
  1127. mergedWriteGuards->Or(writeGuards2);
  1128. }
  1129. }
  1130. else
  1131. {
  1132. mergedWriteGuards = writeGuards2->CopyNew();
  1133. }
  1134. ObjWriteGuardBucket bucket;
  1135. bucket.SetWriteGuards(mergedWriteGuards);
  1136. return bucket;
  1137. }
  1138. void
  1139. BackwardPass::DeleteBlockData(BasicBlock * block)
  1140. {
  1141. if (block->slotDeadStoreCandidates != nullptr)
  1142. {
  1143. JitAdelete(this->tempAlloc, block->slotDeadStoreCandidates);
  1144. block->slotDeadStoreCandidates = nullptr;
  1145. }
  1146. if (block->tempNumberTracker != nullptr)
  1147. {
  1148. JitAdelete(this->tempAlloc, block->tempNumberTracker);
  1149. block->tempNumberTracker = nullptr;
  1150. }
  1151. if (block->tempObjectTracker != nullptr)
  1152. {
  1153. JitAdelete(this->tempAlloc, block->tempObjectTracker);
  1154. block->tempObjectTracker = nullptr;
  1155. }
  1156. #if DBG
  1157. if (block->tempObjectVerifyTracker != nullptr)
  1158. {
  1159. JitAdelete(this->tempAlloc, block->tempObjectVerifyTracker);
  1160. block->tempObjectVerifyTracker = nullptr;
  1161. }
  1162. #endif
  1163. if (block->stackSymToFinalType != nullptr)
  1164. {
  1165. block->stackSymToFinalType->Delete();
  1166. block->stackSymToFinalType = nullptr;
  1167. }
  1168. if (block->stackSymToGuardedProperties != nullptr)
  1169. {
  1170. block->stackSymToGuardedProperties->Delete();
  1171. block->stackSymToGuardedProperties = nullptr;
  1172. }
  1173. if (block->stackSymToWriteGuardsMap != nullptr)
  1174. {
  1175. block->stackSymToWriteGuardsMap->Delete();
  1176. block->stackSymToWriteGuardsMap = nullptr;
  1177. }
  1178. if (block->cloneStrCandidates != nullptr)
  1179. {
  1180. Assert(this->tag == Js::BackwardPhase);
  1181. JitAdelete(this->globOpt->alloc, block->cloneStrCandidates);
  1182. block->cloneStrCandidates = nullptr;
  1183. }
  1184. if (block->noImplicitCallUses != nullptr)
  1185. {
  1186. JitAdelete(this->tempAlloc, block->noImplicitCallUses);
  1187. block->noImplicitCallUses = nullptr;
  1188. }
  1189. if (block->noImplicitCallNoMissingValuesUses != nullptr)
  1190. {
  1191. JitAdelete(this->tempAlloc, block->noImplicitCallNoMissingValuesUses);
  1192. block->noImplicitCallNoMissingValuesUses = nullptr;
  1193. }
  1194. if (block->noImplicitCallNativeArrayUses != nullptr)
  1195. {
  1196. JitAdelete(this->tempAlloc, block->noImplicitCallNativeArrayUses);
  1197. block->noImplicitCallNativeArrayUses = nullptr;
  1198. }
  1199. if (block->noImplicitCallJsArrayHeadSegmentSymUses != nullptr)
  1200. {
  1201. JitAdelete(this->tempAlloc, block->noImplicitCallJsArrayHeadSegmentSymUses);
  1202. block->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  1203. }
  1204. if (block->noImplicitCallArrayLengthSymUses != nullptr)
  1205. {
  1206. JitAdelete(this->tempAlloc, block->noImplicitCallArrayLengthSymUses);
  1207. block->noImplicitCallArrayLengthSymUses = nullptr;
  1208. }
  1209. if (block->upwardExposedUses != nullptr)
  1210. {
  1211. JitArenaAllocator *upwardExposedArena = (this->tag == Js::BackwardPhase) ? this->globOpt->alloc : this->tempAlloc;
  1212. JitAdelete(upwardExposedArena, block->upwardExposedUses);
  1213. block->upwardExposedUses = nullptr;
  1214. }
  1215. if (block->upwardExposedFields != nullptr)
  1216. {
  1217. JitArenaAllocator *upwardExposedArena = (this->tag == Js::BackwardPhase) ? this->globOpt->alloc : this->tempAlloc;
  1218. JitAdelete(upwardExposedArena, block->upwardExposedFields);
  1219. block->upwardExposedFields = nullptr;
  1220. }
  1221. if (block->typesNeedingKnownObjectLayout != nullptr)
  1222. {
  1223. JitAdelete(this->tempAlloc, block->typesNeedingKnownObjectLayout);
  1224. block->typesNeedingKnownObjectLayout = nullptr;
  1225. }
  1226. if (block->fieldHoistCandidates != nullptr)
  1227. {
  1228. JitAdelete(this->tempAlloc, block->fieldHoistCandidates);
  1229. block->fieldHoistCandidates = nullptr;
  1230. }
  1231. if (block->byteCodeUpwardExposedUsed != nullptr)
  1232. {
  1233. JitAdelete(this->tempAlloc, block->byteCodeUpwardExposedUsed);
  1234. block->byteCodeUpwardExposedUsed = nullptr;
  1235. #if DBG
  1236. JitAdeleteArray(this->tempAlloc, func->GetJITFunctionBody()->GetLocalsCount(), block->byteCodeRestoreSyms);
  1237. block->byteCodeRestoreSyms = nullptr;
  1238. #endif
  1239. }
  1240. if (block->couldRemoveNegZeroBailoutForDef != nullptr)
  1241. {
  1242. JitAdelete(this->tempAlloc, block->couldRemoveNegZeroBailoutForDef);
  1243. block->couldRemoveNegZeroBailoutForDef = nullptr;
  1244. }
  1245. }
  1246. void
  1247. BackwardPass::ProcessLoopCollectionPass(BasicBlock *const lastBlock)
  1248. {
  1249. // The collection pass is done before the prepass, to collect and propagate a minimal amount of information into nested
  1250. // loops, for cases where the information is needed to make appropriate decisions on changing other state. For instance,
  1251. // bailouts in nested loops need to be able to see all byte-code uses that are exposed to the bailout so that the
  1252. // appropriate syms can be made upwards-exposed during the prepass. Byte-code uses that occur before the bailout in the
  1253. // flow, or byte-code uses after the current loop, are not seen by bailouts inside the loop. The collection pass collects
  1254. // byte-code uses and propagates them at least into each loop's header such that when bailouts are processed in the prepass,
  1255. // they will have full visibility of byte-code upwards-exposed uses.
  1256. //
  1257. // For the collection pass, one pass is needed to collect all byte-code uses of a loop to the loop header. If the loop has
  1258. // inner loops, another pass is needed to propagate byte-code uses in the outer loop into the inner loop's header, since
  1259. // some byte-code uses may occur before the inner loop in the flow. The process continues recursively for inner loops. The
  1260. // second pass only needs to walk as far as the first inner loop's header, since the purpose of that pass is only to
  1261. // propagate collected information into the inner loops' headers.
  1262. //
  1263. // Consider the following case:
  1264. // (Block 1, Loop 1 header)
  1265. // ByteCodeUses s1
  1266. // (Block 2, Loop 2 header)
  1267. // (Block 3, Loop 3 header)
  1268. // (Block 4)
  1269. // BailOut
  1270. // (Block 5, Loop 3 back-edge)
  1271. // (Block 6, Loop 2 back-edge)
  1272. // (Block 7, Loop 1 back-edge)
  1273. //
  1274. // Assume that the exit branch in each of these loops is in the loop's header block, like a 'while' loop. For the byte-code
  1275. // use of 's1' to become visible to the bailout in the innermost loop, we need to walk the following blocks:
  1276. // - Collection pass
  1277. // - 7, 6, 5, 4, 3, 2, 1, 7 - block 1 is the first block in loop 1 that sees 's1', and since block 7 has block 1 as its
  1278. // successor, block 7 sees 's1' now as well
  1279. // - 6, 5, 4, 3, 2, 6 - block 2 is the first block in loop 2 that sees 's1', and since block 6 has block 2 as its
  1280. // successor, block 6 sees 's1' now as well
  1281. // - 5, 4, 3 - block 3 is the first block in loop 3 that sees 's1'
  1282. // - The collection pass does not have to do another pass through the innermost loop because it does not have any inner
  1283. // loops of its own. It's sufficient to propagate the byte-code uses up to the loop header of each loop, as the
  1284. // prepass will do the remaining propagation.
  1285. // - Prepass
  1286. // - 7, 6, 5, 4, ... - since block 5 has block 3 as its successor, block 5 sees 's1', and so does block 4. So, the bailout
  1287. // finally sees 's1' as a byte-code upwards-exposed use.
  1288. //
  1289. // The collection pass walks as described above, and consists of one pass, followed by another pass if there are inner
  1290. // loops. The second pass only walks up to the first inner loop's header block, and during this pass upon reaching an inner
  1291. // loop, the algorithm goes recursively for that inner loop, and once it returns, the second pass continues from above that
  1292. // inner loop. Each bullet of the walk in the example above is a recursive call to ProcessLoopCollectionPass, except the
  1293. // first line, which is the initial call.
  1294. //
  1295. // Imagine the whole example above is inside another loop, and at the bottom of that loop there is an assignment to 's1'. If
  1296. // the bailout is the only use of 's1', then it needs to register 's1' as a use in the prepass to prevent treating the
  1297. // assignment to 's1' as a dead store.
  1298. Assert(tag == Js::DeadStorePhase);
  1299. Assert(IsCollectionPass());
  1300. Assert(lastBlock);
  1301. Loop *const collectionPassLoop = lastBlock->loop;
  1302. Assert(collectionPassLoop);
  1303. Assert(!collectionPassLoop->hasDeadStoreCollectionPass);
  1304. collectionPassLoop->hasDeadStoreCollectionPass = true;
  1305. Loop *const previousPrepassLoop = currentPrePassLoop;
  1306. currentPrePassLoop = collectionPassLoop;
  1307. Assert(IsPrePass());
  1308. // First pass
  1309. BasicBlock *firstInnerLoopHeader = nullptr;
  1310. {
  1311. #if DBG_DUMP
  1312. if(IsTraceEnabled())
  1313. {
  1314. Output::Print(_u("******* COLLECTION PASS 1 START: Loop %u ********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1315. }
  1316. #endif
  1317. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, nullptr)
  1318. {
  1319. ProcessBlock(block);
  1320. if(block->isLoopHeader)
  1321. {
  1322. if(block->loop == collectionPassLoop)
  1323. {
  1324. break;
  1325. }
  1326. // Keep track of the first inner loop's header for the second pass, which need only walk up to that block
  1327. firstInnerLoopHeader = block;
  1328. }
  1329. } NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1330. #if DBG_DUMP
  1331. if(IsTraceEnabled())
  1332. {
  1333. Output::Print(_u("******** COLLECTION PASS 1 END: Loop %u *********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1334. }
  1335. #endif
  1336. }
  1337. // Second pass, only needs to run if there are any inner loops, to propagate collected information into those loops
  1338. if(firstInnerLoopHeader)
  1339. {
  1340. #if DBG_DUMP
  1341. if(IsTraceEnabled())
  1342. {
  1343. Output::Print(_u("******* COLLECTION PASS 2 START: Loop %u ********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1344. }
  1345. #endif
  1346. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, firstInnerLoopHeader)
  1347. {
  1348. Loop *const loop = block->loop;
  1349. if(loop && loop != collectionPassLoop && !loop->hasDeadStoreCollectionPass)
  1350. {
  1351. // About to make a recursive call, so when jitting in the foreground, probe the stack
  1352. if(!func->IsBackgroundJIT())
  1353. {
  1354. PROBE_STACK(func->GetScriptContext(), Js::Constants::MinStackDefault);
  1355. }
  1356. ProcessLoopCollectionPass(block);
  1357. // The inner loop's collection pass would have propagated collected information to its header block. Skip to the
  1358. // inner loop's header block and continue from the block before it.
  1359. block = loop->GetHeadBlock();
  1360. Assert(block->isLoopHeader);
  1361. continue;
  1362. }
  1363. ProcessBlock(block);
  1364. } NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1365. #if DBG_DUMP
  1366. if(IsTraceEnabled())
  1367. {
  1368. Output::Print(_u("******** COLLECTION PASS 2 END: Loop %u *********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1369. }
  1370. #endif
  1371. }
  1372. currentPrePassLoop = previousPrepassLoop;
  1373. }
  1374. void
  1375. BackwardPass::ProcessLoop(BasicBlock * lastBlock)
  1376. {
  1377. #if DBG_DUMP
  1378. if (this->IsTraceEnabled())
  1379. {
  1380. Output::Print(_u("******* PREPASS START ********\n"));
  1381. }
  1382. #endif
  1383. Loop *loop = lastBlock->loop;
  1384. // This code doesn't work quite as intended. It is meant to capture fields that are live out of a loop to limit the
  1385. // number of implicit call bailouts the forward pass must create (only compiler throughput optimization, no impact
  1386. // on emitted code), but because it looks only at the lexically last block in the loop, it does the right thing only
  1387. // for do-while loops. For other loops (for and while) the last block does not exit the loop. Even for do-while loops
  1388. // this tracking can have the adverse effect of killing fields that should stay live after copy prop. Disabled by default.
  1389. // Left in under a flag, in case we find compiler throughput issues and want to do additional experiments.
  1390. if (PHASE_ON(Js::LiveOutFieldsPhase, this->func))
  1391. {
  1392. if (this->globOpt->DoFieldOpts(loop) || this->globOpt->DoFieldRefOpts(loop))
  1393. {
  1394. // Get the live-out set at the loop bottom.
  1395. // This may not be the only loop exit, but all loop exits either leave the function or pass through here.
  1396. // In the forward pass, we'll use this set to trim the live fields on exit from the loop
  1397. // in order to limit the number of bailout points following the loop.
  1398. BVSparse<JitArenaAllocator> *bv = JitAnew(this->func->m_fg->alloc, BVSparse<JitArenaAllocator>, this->func->m_fg->alloc);
  1399. FOREACH_SUCCESSOR_BLOCK(blockSucc, lastBlock)
  1400. {
  1401. if (blockSucc->loop != loop)
  1402. {
  1403. // Would like to assert this, but in strange exprgen cases involving "break LABEL" in nested
  1404. // loops the loop graph seems to get confused.
  1405. //Assert(!blockSucc->loop || blockSucc->loop->IsDescendentOrSelf(loop));
  1406. Assert(!blockSucc->loop || blockSucc->loop->hasDeadStorePrepass);
  1407. bv->Or(blockSucc->upwardExposedFields);
  1408. }
  1409. }
  1410. NEXT_SUCCESSOR_BLOCK;
  1411. lastBlock->loop->liveOutFields = bv;
  1412. }
  1413. }
  1414. if(tag == Js::DeadStorePhase && !loop->hasDeadStoreCollectionPass)
  1415. {
  1416. Assert(!IsCollectionPass());
  1417. Assert(!IsPrePass());
  1418. isCollectionPass = true;
  1419. ProcessLoopCollectionPass(lastBlock);
  1420. isCollectionPass = false;
  1421. }
  1422. Assert(!this->IsPrePass());
  1423. this->currentPrePassLoop = loop;
  1424. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, nullptr)
  1425. {
  1426. this->ProcessBlock(block);
  1427. if (block->isLoopHeader && block->loop == lastBlock->loop)
  1428. {
  1429. Assert(block->fieldHoistCandidates == nullptr);
  1430. break;
  1431. }
  1432. }
  1433. NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1434. this->currentPrePassLoop = nullptr;
  1435. Assert(lastBlock);
  1436. __analysis_assume(lastBlock);
  1437. lastBlock->loop->hasDeadStorePrepass = true;
  1438. #if DBG_DUMP
  1439. if (this->IsTraceEnabled())
  1440. {
  1441. Output::Print(_u("******** PREPASS END *********\n"));
  1442. }
  1443. #endif
  1444. }
  1445. void
  1446. BackwardPass::OptBlock(BasicBlock * block)
  1447. {
  1448. this->func->ThrowIfScriptClosed();
  1449. if (block->loop && !block->loop->hasDeadStorePrepass)
  1450. {
  1451. ProcessLoop(block);
  1452. }
  1453. this->ProcessBlock(block);
  1454. if(DoTrackNegativeZero())
  1455. {
  1456. negativeZeroDoesNotMatterBySymId->ClearAll();
  1457. }
  1458. if (DoTrackBitOpsOrNumber())
  1459. {
  1460. symUsedOnlyForBitOpsBySymId->ClearAll();
  1461. symUsedOnlyForNumberBySymId->ClearAll();
  1462. }
  1463. if(DoTrackIntOverflow())
  1464. {
  1465. intOverflowDoesNotMatterBySymId->ClearAll();
  1466. if(DoTrackCompoundedIntOverflow())
  1467. {
  1468. intOverflowDoesNotMatterInRangeBySymId->ClearAll();
  1469. }
  1470. }
  1471. }
  1472. void
  1473. BackwardPass::ProcessBailOutArgObj(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed)
  1474. {
  1475. Assert(this->tag != Js::BackwardPhase);
  1476. if (this->globOpt->TrackArgumentsObject() && bailOutInfo->capturedValues.argObjSyms)
  1477. {
  1478. FOREACH_BITSET_IN_SPARSEBV(symId, bailOutInfo->capturedValues.argObjSyms)
  1479. {
  1480. if (byteCodeUpwardExposedUsed->TestAndClear(symId))
  1481. {
  1482. if (bailOutInfo->usedCapturedValues.argObjSyms == nullptr)
  1483. {
  1484. bailOutInfo->usedCapturedValues.argObjSyms = JitAnew(this->func->m_alloc,
  1485. BVSparse<JitArenaAllocator>, this->func->m_alloc);
  1486. }
  1487. bailOutInfo->usedCapturedValues.argObjSyms->Set(symId);
  1488. }
  1489. }
  1490. NEXT_BITSET_IN_SPARSEBV;
  1491. }
  1492. if (bailOutInfo->usedCapturedValues.argObjSyms)
  1493. {
  1494. byteCodeUpwardExposedUsed->Minus(bailOutInfo->usedCapturedValues.argObjSyms);
  1495. }
  1496. }
  1497. void
  1498. BackwardPass::ProcessBailOutConstants(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed, BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv)
  1499. {
  1500. Assert(this->tag != Js::BackwardPhase);
  1501. // Remove constants that we are already going to restore
  1502. SListBase<ConstantStackSymValue> * usedConstantValues = &bailOutInfo->usedCapturedValues.constantValues;
  1503. FOREACH_SLISTBASE_ENTRY(ConstantStackSymValue, value, usedConstantValues)
  1504. {
  1505. byteCodeUpwardExposedUsed->Clear(value.Key()->m_id);
  1506. bailoutReferencedArgSymsBv->Clear(value.Key()->m_id);
  1507. }
  1508. NEXT_SLISTBASE_ENTRY;
  1509. // Find other constants that we need to restore
  1510. FOREACH_SLISTBASE_ENTRY_EDITING(ConstantStackSymValue, value, &bailOutInfo->capturedValues.constantValues, iter)
  1511. {
  1512. if (byteCodeUpwardExposedUsed->TestAndClear(value.Key()->m_id) || bailoutReferencedArgSymsBv->TestAndClear(value.Key()->m_id))
  1513. {
  1514. // Constant need to be restore, move it to the restore list
  1515. iter.MoveCurrentTo(usedConstantValues);
  1516. }
  1517. else if (!this->IsPrePass())
  1518. {
  1519. // Constants don't need to be restored, delete
  1520. iter.RemoveCurrent(this->func->m_alloc);
  1521. }
  1522. }
  1523. NEXT_SLISTBASE_ENTRY_EDITING;
  1524. }
  1525. void
  1526. BackwardPass::ProcessBailOutCopyProps(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed, BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv)
  1527. {
  1528. Assert(this->tag != Js::BackwardPhase);
  1529. Assert(!this->func->GetJITFunctionBody()->IsAsmJsMode());
  1530. // Remove copy prop that we were already going to restore
  1531. SListBase<CopyPropSyms> * usedCopyPropSyms = &bailOutInfo->usedCapturedValues.copyPropSyms;
  1532. FOREACH_SLISTBASE_ENTRY(CopyPropSyms, copyPropSyms, usedCopyPropSyms)
  1533. {
  1534. byteCodeUpwardExposedUsed->Clear(copyPropSyms.Key()->m_id);
  1535. this->currentBlock->upwardExposedUses->Set(copyPropSyms.Value()->m_id);
  1536. }
  1537. NEXT_SLISTBASE_ENTRY;
  1538. JitArenaAllocator * allocator = this->func->m_alloc;
  1539. BasicBlock * block = this->currentBlock;
  1540. BVSparse<JitArenaAllocator> * upwardExposedUses = block->upwardExposedUses;
  1541. // Find other copy prop that we need to restore
  1542. FOREACH_SLISTBASE_ENTRY_EDITING(CopyPropSyms, copyPropSyms, &bailOutInfo->capturedValues.copyPropSyms, iter)
  1543. {
  1544. // Copy prop syms should be vars
  1545. Assert(!copyPropSyms.Key()->IsTypeSpec());
  1546. Assert(!copyPropSyms.Value()->IsTypeSpec());
  1547. if (byteCodeUpwardExposedUsed->TestAndClear(copyPropSyms.Key()->m_id) || bailoutReferencedArgSymsBv->TestAndClear(copyPropSyms.Key()->m_id))
  1548. {
  1549. // This copy-prop sym needs to be restored; add it to the restore list.
  1550. /*
  1551. - copyPropSyms.Key() - original sym that is byte-code upwards-exposed, its corresponding byte-code register needs
  1552. to be restored
  1553. - copyPropSyms.Value() - copy-prop sym whose value the original sym has at the point of this instruction
  1554. Heuristic:
  1555. - By default, use the copy-prop sym to restore its corresponding byte code register
  1556. - This is typically better because that allows the value of the original sym, if it's not used after the copy-prop
  1557. sym is changed, to be discarded and we only have one lifetime (the copy-prop sym's lifetime) in to deal with for
  1558. register allocation
  1559. - Additionally, if the transferring store, which caused the original sym to have the same value as the copy-prop
  1560. sym, becomes a dead store, the original sym won't actually attain the value of the copy-prop sym. In that case,
  1561. the copy-prop sym must be used to restore the byte code register corresponding to original sym.
  1562. Special case for functional correctness:
  1563. - Consider that we always use the copy-prop sym to restore, and consider the following case:
  1564. b = a
  1565. a = c * d <Pre-op bail-out>
  1566. = b
  1567. - This is rewritten by the lowerer as follows:
  1568. b = a
  1569. a = c
  1570. a = a * d <Pre-op bail-out> (to make dst and src1 the same)
  1571. = b
  1572. - The problem here is that at the point of the bail-out instruction, 'a' would be used to restore the value of 'b',
  1573. but the value of 'a' has changed before the bail-out (at 'a = c').
  1574. - In this case, we need to use 'b' (the original sym) to restore the value of 'b'. Because 'b' is upwards-exposed,
  1575. 'b = a' cannot be a dead store, therefore making it valid to use 'b' to restore.
  1576. - Use the original sym to restore when all of the following are true:
  1577. - The bailout is a pre-op bailout, and the bailout check is done after overwriting the destination
  1578. - It's an int-specialized unary or binary operation that produces a value
  1579. - The copy-prop sym is the destination of this instruction
  1580. - None of the sources are the copy-prop sym. Otherwise, the value of the copy-prop sym will be saved as
  1581. necessary by the bailout code.
  1582. */
  1583. StackSym * stackSym = copyPropSyms.Key(); // assume that we'll use the original sym to restore
  1584. SymID symId = stackSym->m_id;
  1585. IR::Instr *const instr = bailOutInfo->bailOutInstr;
  1586. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  1587. if(instr->GetBailOutKind() & IR::BailOutOnResultConditions &&
  1588. instr->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset &&
  1589. bailOutInfo->bailOutOffset <= instr->GetByteCodeOffset() &&
  1590. dstSym &&
  1591. dstSym->IsInt32() &&
  1592. dstSym->IsTypeSpec() &&
  1593. dstSym->GetVarEquivSym(nullptr) == copyPropSyms.Value() &&
  1594. instr->GetSrc1() &&
  1595. !instr->GetDst()->IsEqual(instr->GetSrc1()) &&
  1596. !(instr->GetSrc2() && instr->GetDst()->IsEqual(instr->GetSrc2())))
  1597. {
  1598. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1599. // Need to use the original sym to restore. The original sym is byte-code upwards-exposed, which is why it needs
  1600. // to be restored. Because the original sym needs to be restored and the copy-prop sym is changing here, the
  1601. // original sym must be live in some fashion at the point of this instruction, that will be verified below. The
  1602. // original sym will also be made upwards-exposed from here, so the aforementioned transferring store of the
  1603. // copy-prop sym to the original sym will not be a dead store.
  1604. }
  1605. else if (block->upwardExposedUses->Test(stackSym->m_id) && !block->upwardExposedUses->Test(copyPropSyms.Value()->m_id))
  1606. {
  1607. // Don't use the copy prop sym if it is not used and the orig sym still has uses.
  1608. // No point in extending the lifetime of the copy prop sym unnecessarily.
  1609. }
  1610. else
  1611. {
  1612. // Need to use the copy-prop sym to restore
  1613. stackSym = copyPropSyms.Value();
  1614. symId = stackSym->m_id;
  1615. }
  1616. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially
  1617. // expensive ToVars that can more easily be eliminated due to being dead stores
  1618. StackSym * int32StackSym = nullptr;
  1619. StackSym * float64StackSym = nullptr;
  1620. StackSym * simd128StackSym = nullptr;
  1621. if (bailOutInfo->liveLosslessInt32Syms->Test(symId))
  1622. {
  1623. // Var version of the sym is not live, use the int32 version
  1624. int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  1625. Assert(int32StackSym);
  1626. }
  1627. else if(bailOutInfo->liveFloat64Syms->Test(symId))
  1628. {
  1629. // Var/int32 version of the sym is not live, use the float64 version
  1630. float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  1631. Assert(float64StackSym);
  1632. }
  1633. // SIMD_JS
  1634. else if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  1635. {
  1636. simd128StackSym = stackSym->GetSimd128F4EquivSym(nullptr);
  1637. }
  1638. else if (bailOutInfo->liveSimd128I4Syms->Test(symId))
  1639. {
  1640. simd128StackSym = stackSym->GetSimd128I4EquivSym(nullptr);
  1641. }
  1642. else
  1643. {
  1644. Assert(bailOutInfo->liveVarSyms->Test(symId));
  1645. }
  1646. // We did not end up using the copy prop sym. Let's make sure the use of the original sym by the bailout is captured.
  1647. if (stackSym != copyPropSyms.Value() && stackSym->HasArgSlotNum())
  1648. {
  1649. bailoutReferencedArgSymsBv->Set(stackSym->m_id);
  1650. }
  1651. if (int32StackSym != nullptr)
  1652. {
  1653. Assert(float64StackSym == nullptr);
  1654. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), int32StackSym);
  1655. iter.RemoveCurrent(allocator);
  1656. upwardExposedUses->Set(int32StackSym->m_id);
  1657. }
  1658. else if (float64StackSym != nullptr)
  1659. {
  1660. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  1661. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  1662. // specialized using BailOutNumberOnly.
  1663. float64StackSym->m_requiresBailOnNotNumber = true;
  1664. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), float64StackSym);
  1665. iter.RemoveCurrent(allocator);
  1666. upwardExposedUses->Set(float64StackSym->m_id);
  1667. }
  1668. // SIMD_JS
  1669. else if (simd128StackSym != nullptr)
  1670. {
  1671. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), simd128StackSym);
  1672. iter.RemoveCurrent(allocator);
  1673. upwardExposedUses->Set(simd128StackSym->m_id);
  1674. }
  1675. else
  1676. {
  1677. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), stackSym);
  1678. iter.RemoveCurrent(allocator);
  1679. upwardExposedUses->Set(symId);
  1680. }
  1681. }
  1682. else if (!this->IsPrePass())
  1683. {
  1684. // Copy prop sym doesn't need to be restored, delete.
  1685. iter.RemoveCurrent(allocator);
  1686. }
  1687. }
  1688. NEXT_SLISTBASE_ENTRY_EDITING;
  1689. }
  1690. bool
  1691. BackwardPass::ProcessBailOutInfo(IR::Instr * instr)
  1692. {
  1693. if (this->tag == Js::BackwardPhase)
  1694. {
  1695. // We don't need to fill in the bailout instruction in backward pass
  1696. Assert(this->func->hasBailout || !instr->HasBailOutInfo());
  1697. Assert(!instr->HasBailOutInfo() || instr->GetBailOutInfo()->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTryCatch()));
  1698. if (instr->IsByteCodeUsesInstr())
  1699. {
  1700. // FGPeeps inserts bytecodeuses instrs with srcs. We need to look at them to set the proper
  1701. // UpwardExposedUsed info and keep the defs alive.
  1702. // The inliner inserts bytecodeuses instrs withs dsts, but we don't want to look at them for upwardExposedUsed
  1703. // as it would cause real defs to look dead. We use these for bytecodeUpwardExposedUsed info only, which is needed
  1704. // in the dead-store pass only.
  1705. //
  1706. // Handle the source side.
  1707. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1708. const BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = byteCodeUsesInstr->GetByteCodeUpwardExposedUsed();
  1709. if (byteCodeUpwardExposedUsed != nullptr)
  1710. {
  1711. this->currentBlock->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  1712. }
  1713. return true;
  1714. }
  1715. return false;
  1716. }
  1717. if (instr->IsByteCodeUsesInstr())
  1718. {
  1719. Assert(instr->m_opcode == Js::OpCode::ByteCodeUses);
  1720. #if DBG
  1721. if (this->DoMarkTempObjectVerify() && (this->currentBlock->isDead || !this->func->hasBailout))
  1722. {
  1723. if (IsCollectionPass())
  1724. {
  1725. if (!this->func->hasBailout)
  1726. {
  1727. // Prevent byte code uses from being remove on collection pass for mark temp object verify
  1728. // if we don't have any bailout
  1729. return true;
  1730. }
  1731. }
  1732. else
  1733. {
  1734. this->currentBlock->tempObjectVerifyTracker->NotifyDeadByteCodeUses(instr);
  1735. }
  1736. }
  1737. #endif
  1738. if (this->func->hasBailout)
  1739. {
  1740. Assert(this->DoByteCodeUpwardExposedUsed());
  1741. // Just collect the byte code uses, and remove the instruction
  1742. // We are going backward, process the dst first and then the src
  1743. IR::Opnd * dst = instr->GetDst();
  1744. if (dst)
  1745. {
  1746. IR::RegOpnd * dstRegOpnd = dst->AsRegOpnd();
  1747. StackSym * dstStackSym = dstRegOpnd->m_sym->AsStackSym();
  1748. Assert(!dstRegOpnd->GetIsJITOptimizedReg());
  1749. Assert(dstStackSym->GetByteCodeRegSlot() != Js::Constants::NoRegister);
  1750. if (dstStackSym->GetType() != TyVar)
  1751. {
  1752. dstStackSym = dstStackSym->GetVarEquivSym(nullptr);
  1753. }
  1754. // If the current region is a Try, symbols in its write-through set shouldn't be cleared.
  1755. // Otherwise, symbols in the write-through set of the first try ancestor shouldn't be cleared.
  1756. if (!this->currentRegion ||
  1757. !this->CheckWriteThroughSymInRegion(this->currentRegion, dstStackSym))
  1758. {
  1759. this->currentBlock->byteCodeUpwardExposedUsed->Clear(dstStackSym->m_id);
  1760. #if DBG
  1761. // We can only track first level function stack syms right now
  1762. if (dstStackSym->GetByteCodeFunc() == this->func)
  1763. {
  1764. this->currentBlock->byteCodeRestoreSyms[dstStackSym->GetByteCodeRegSlot()] = nullptr;
  1765. }
  1766. #endif
  1767. }
  1768. }
  1769. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1770. if (byteCodeUsesInstr->GetByteCodeUpwardExposedUsed() != nullptr)
  1771. {
  1772. this->currentBlock->byteCodeUpwardExposedUsed->Or(byteCodeUsesInstr->GetByteCodeUpwardExposedUsed());
  1773. #if DBG
  1774. FOREACH_BITSET_IN_SPARSEBV(symId, byteCodeUsesInstr->GetByteCodeUpwardExposedUsed())
  1775. {
  1776. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  1777. Assert(!stackSym->IsTypeSpec());
  1778. // We can only track first level function stack syms right now
  1779. if (stackSym->GetByteCodeFunc() == this->func)
  1780. {
  1781. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  1782. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  1783. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  1784. {
  1785. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  1786. "Can't have two active lifetime for the same byte code register");
  1787. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  1788. }
  1789. }
  1790. }
  1791. NEXT_BITSET_IN_SPARSEBV;
  1792. #endif
  1793. }
  1794. if(IsCollectionPass())
  1795. {
  1796. return true;
  1797. }
  1798. ProcessPendingPreOpBailOutInfo(instr);
  1799. PropertySym *propertySymUse = byteCodeUsesInstr->propertySymUse;
  1800. if (propertySymUse && !this->currentBlock->isDead)
  1801. {
  1802. this->currentBlock->upwardExposedFields->Set(propertySymUse->m_id);
  1803. }
  1804. if (this->IsPrePass())
  1805. {
  1806. // Don't remove the instruction yet if we are in the prepass
  1807. // But tell the caller we don't need to process the instruction any more
  1808. return true;
  1809. }
  1810. }
  1811. this->currentBlock->RemoveInstr(instr);
  1812. return true;
  1813. }
  1814. if(IsCollectionPass())
  1815. {
  1816. return false;
  1817. }
  1818. if (instr->HasBailOutInfo())
  1819. {
  1820. Assert(this->func->hasBailout);
  1821. Assert(this->DoByteCodeUpwardExposedUsed());
  1822. BailOutInfo * bailOutInfo = instr->GetBailOutInfo();
  1823. // Only process the bailout info if this is the main bailout point (instead of shared)
  1824. if (bailOutInfo->bailOutInstr == instr)
  1825. {
  1826. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset ||
  1827. bailOutInfo->bailOutOffset > instr->GetByteCodeOffset())
  1828. {
  1829. // Currently, we only have post-op bailout with BailOutOnImplicitCalls
  1830. // or JIT inserted operation (which no byte code offsets).
  1831. // If there are other bailouts that we want to bailout after the operation,
  1832. // we have to make sure that it still doesn't do the implicit call
  1833. // if it is done on the stack object.
  1834. // Otherwise, the stack object will be passed to the implicit call functions.
  1835. Assert(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset
  1836. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCalls
  1837. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutInvalid);
  1838. // This instruction bails out to a later byte-code instruction, so process the bailout info now
  1839. ProcessBailOutInfo(instr, bailOutInfo);
  1840. }
  1841. else
  1842. {
  1843. // This instruction bails out to the equivalent byte code instruction. This instruction and ByteCodeUses
  1844. // instructions relevant to this instruction need to be processed before the bailout info for this instruction
  1845. // can be processed, so that it can be determined what byte code registers are used by the equivalent byte code
  1846. // instruction and need to be restored. Save the instruction for bailout info processing later.
  1847. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1848. Assert(!preOpBailOutInstrToProcess);
  1849. preOpBailOutInstrToProcess = instr;
  1850. }
  1851. }
  1852. }
  1853. return false;
  1854. }
  1855. bool
  1856. BackwardPass::IsImplicitCallBailOutCurrentlyNeeded(IR::Instr * instr, bool mayNeedImplicitCallBailOut, bool hasLiveFields)
  1857. {
  1858. return this->globOpt->IsImplicitCallBailOutCurrentlyNeeded(
  1859. instr, nullptr, nullptr, this->currentBlock, hasLiveFields, mayNeedImplicitCallBailOut, false);
  1860. }
  1861. void
  1862. BackwardPass::DeadStoreTypeCheckBailOut(IR::Instr * instr)
  1863. {
  1864. // Good news: There are cases where the forward pass installs BailOutFailedTypeCheck, but the dead store pass
  1865. // discovers that the checked type is dead.
  1866. // Bad news: We may still need implicit call bailout, and it's up to the dead store pass to figure this out.
  1867. // Worse news: BailOutFailedTypeCheck is pre-op, and BailOutOnImplicitCall is post-op. We'll use a special
  1868. // bailout kind to indicate implicit call bailout that targets its own instruction. The lowerer will emit
  1869. // code to disable/re-enable implicit calls around the operation.
  1870. Assert(this->tag == Js::DeadStorePhase);
  1871. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1872. {
  1873. return;
  1874. }
  1875. IR::BailOutKind oldBailOutKind = instr->GetBailOutKind();
  1876. if (!IR::IsTypeCheckBailOutKind(oldBailOutKind))
  1877. {
  1878. return;
  1879. }
  1880. // Either src1 or dst must be a property sym operand
  1881. Assert((instr->GetSrc1() && instr->GetSrc1()->IsSymOpnd() && instr->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd()) ||
  1882. (instr->GetDst() && instr->GetDst()->IsSymOpnd() && instr->GetDst()->AsSymOpnd()->IsPropertySymOpnd()));
  1883. IR::PropertySymOpnd *propertySymOpnd =
  1884. (instr->GetDst() && instr->GetDst()->IsSymOpnd()) ? instr->GetDst()->AsPropertySymOpnd() : instr->GetSrc1()->AsPropertySymOpnd();
  1885. bool isTypeCheckProtected = false;
  1886. IR::BailOutKind bailOutKind;
  1887. if (GlobOpt::NeedsTypeCheckBailOut(instr, propertySymOpnd, propertySymOpnd == instr->GetDst(), &isTypeCheckProtected, &bailOutKind))
  1888. {
  1889. // If we installed a failed type check bailout in the forward pass, but we are now discovering that the checked
  1890. // type is dead, we may still need a bailout on failed fixed field type check. These type checks are required
  1891. // regardless of whether the checked type is dead. Hence, the bailout kind may change here.
  1892. Assert((oldBailOutKind & ~IR::BailOutKindBits) == bailOutKind ||
  1893. bailOutKind == IR::BailOutFailedFixedFieldTypeCheck || bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck);
  1894. instr->SetBailOutKind(bailOutKind);
  1895. return;
  1896. }
  1897. else if (isTypeCheckProtected)
  1898. {
  1899. instr->ClearBailOutInfo();
  1900. if (preOpBailOutInstrToProcess == instr)
  1901. {
  1902. preOpBailOutInstrToProcess = nullptr;
  1903. }
  1904. return;
  1905. }
  1906. Assert(!propertySymOpnd->IsTypeCheckProtected());
  1907. // If all we're doing here is checking the type (e.g. because we've hoisted a field load or store out of the loop, but needed
  1908. // the type check to remain in the loop), and now it turns out we don't need the type checked, we can simply turn this into
  1909. // a NOP and remove the bailout.
  1910. if (instr->m_opcode == Js::OpCode::CheckObjType)
  1911. {
  1912. Assert(instr->GetDst() == nullptr && instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr);
  1913. instr->m_opcode = Js::OpCode::Nop;
  1914. instr->FreeSrc1();
  1915. instr->ClearBailOutInfo();
  1916. if (this->preOpBailOutInstrToProcess == instr)
  1917. {
  1918. this->preOpBailOutInstrToProcess = nullptr;
  1919. }
  1920. return;
  1921. }
  1922. // We don't need BailOutFailedTypeCheck but may need BailOutOnImplicitCall.
  1923. // Consider: are we in the loop landing pad? If so, no bailout, since implicit calls will be checked at
  1924. // the end of the block.
  1925. if (this->currentBlock->IsLandingPad())
  1926. {
  1927. // We're in the landing pad.
  1928. if (preOpBailOutInstrToProcess == instr)
  1929. {
  1930. preOpBailOutInstrToProcess = nullptr;
  1931. }
  1932. instr->UnlinkBailOutInfo();
  1933. return;
  1934. }
  1935. // If bailOutKind is equivTypeCheck then leave alone the bailout
  1936. if (bailOutKind == IR::BailOutFailedEquivalentTypeCheck ||
  1937. bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck)
  1938. {
  1939. return;
  1940. }
  1941. // We're not checking for polymorphism, so don't let the bailout indicate that we
  1942. // detected polymorphism.
  1943. instr->GetBailOutInfo()->polymorphicCacheIndex = (uint)-1;
  1944. // Keep the mark temp object bit if it is there so that we will not remove the implicit call check
  1945. instr->SetBailOutKind(IR::BailOutOnImplicitCallsPreOp | (oldBailOutKind & IR::BailOutMarkTempObject));
  1946. }
  1947. void
  1948. BackwardPass::DeadStoreImplicitCallBailOut(IR::Instr * instr, bool hasLiveFields)
  1949. {
  1950. Assert(this->tag == Js::DeadStorePhase);
  1951. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1952. {
  1953. // Don't do this in the pre-pass, because, for instance, we don't have live-on-back-edge fields yet.
  1954. return;
  1955. }
  1956. if (OpCodeAttr::BailOutRec(instr->m_opcode))
  1957. {
  1958. // This is something like OpCode::BailOutOnNotEqual. Assume it needs what it's got.
  1959. return;
  1960. }
  1961. UpdateArrayBailOutKind(instr);
  1962. // Install the implicit call PreOp for mark temp object if we need one.
  1963. IR::BailOutKind kind = instr->GetBailOutKind();
  1964. IR::BailOutKind kindNoBits = kind & ~IR::BailOutKindBits;
  1965. if ((kind & IR::BailOutMarkTempObject) != 0 && kindNoBits != IR::BailOutOnImplicitCallsPreOp)
  1966. {
  1967. Assert(kindNoBits != IR::BailOutOnImplicitCalls);
  1968. if (kindNoBits == IR::BailOutInvalid)
  1969. {
  1970. // We should only have combined with array bits
  1971. Assert((kind & ~IR::BailOutForArrayBits) == IR::BailOutMarkTempObject);
  1972. // Don't need to install if we are not going to do helper calls,
  1973. // or we are in the landingPad since implicit calls are already turned off.
  1974. if ((kind & IR::BailOutOnArrayAccessHelperCall) == 0 && !this->currentBlock->IsLandingPad())
  1975. {
  1976. kind += IR::BailOutOnImplicitCallsPreOp;
  1977. instr->SetBailOutKind(kind);
  1978. }
  1979. }
  1980. }
  1981. // Currently only try to eliminate these bailout kinds. The others are required in cases
  1982. // where we don't necessarily have live/hoisted fields.
  1983. const bool mayNeedBailOnImplicitCall = BailOutInfo::IsBailOutOnImplicitCalls(kind);
  1984. if (!mayNeedBailOnImplicitCall)
  1985. {
  1986. if (kind & IR::BailOutMarkTempObject)
  1987. {
  1988. if (kind == IR::BailOutMarkTempObject)
  1989. {
  1990. // Landing pad does not need per-instr implicit call bailouts.
  1991. Assert(this->currentBlock->IsLandingPad());
  1992. instr->ClearBailOutInfo();
  1993. if (this->preOpBailOutInstrToProcess == instr)
  1994. {
  1995. this->preOpBailOutInstrToProcess = nullptr;
  1996. }
  1997. }
  1998. else
  1999. {
  2000. // Mark temp object bit is not needed after dead store pass
  2001. instr->SetBailOutKind(kind & ~IR::BailOutMarkTempObject);
  2002. }
  2003. }
  2004. return;
  2005. }
  2006. // We have an implicit call bailout in the code, and we want to make sure that it's required.
  2007. // Do this now, because only in the dead store pass do we have complete forward and backward liveness info.
  2008. bool needsBailOutOnImplicitCall = this->IsImplicitCallBailOutCurrentlyNeeded(instr, mayNeedBailOnImplicitCall, hasLiveFields);
  2009. if(!UpdateImplicitCallBailOutKind(instr, needsBailOutOnImplicitCall))
  2010. {
  2011. instr->ClearBailOutInfo();
  2012. if (preOpBailOutInstrToProcess == instr)
  2013. {
  2014. preOpBailOutInstrToProcess = nullptr;
  2015. }
  2016. #if DBG
  2017. if (this->DoMarkTempObjectVerify())
  2018. {
  2019. this->currentBlock->tempObjectVerifyTracker->NotifyBailOutRemoval(instr, this);
  2020. }
  2021. #endif
  2022. }
  2023. }
  2024. void
  2025. BackwardPass::ProcessPendingPreOpBailOutInfo(IR::Instr *const currentInstr)
  2026. {
  2027. Assert(!IsCollectionPass());
  2028. if(!preOpBailOutInstrToProcess)
  2029. {
  2030. return;
  2031. }
  2032. IR::Instr *const prevInstr = currentInstr->m_prev;
  2033. if(prevInstr &&
  2034. prevInstr->IsByteCodeUsesInstr() &&
  2035. prevInstr->AsByteCodeUsesInstr()->GetByteCodeOffset() == preOpBailOutInstrToProcess->GetByteCodeOffset())
  2036. {
  2037. return;
  2038. }
  2039. // A pre-op bailout instruction was saved for bailout info processing after the instruction and relevant ByteCodeUses
  2040. // instructions before it have been processed. We can process the bailout info for that instruction now.
  2041. BailOutInfo *const bailOutInfo = preOpBailOutInstrToProcess->GetBailOutInfo();
  2042. Assert(bailOutInfo->bailOutInstr == preOpBailOutInstrToProcess);
  2043. Assert(bailOutInfo->bailOutOffset == preOpBailOutInstrToProcess->GetByteCodeOffset());
  2044. ProcessBailOutInfo(preOpBailOutInstrToProcess, bailOutInfo);
  2045. preOpBailOutInstrToProcess = nullptr;
  2046. }
  2047. void
  2048. BackwardPass::ProcessBailOutInfo(IR::Instr * instr, BailOutInfo * bailOutInfo)
  2049. {
  2050. /*
  2051. When we optimize functions having try-catch, we install a bailout at the starting of the catch block, namely, BailOnException.
  2052. We don't have flow edges from all the possible exception points in the try to the catch block. As a result, this bailout should
  2053. not try to restore from the constant values or copy-prop syms or the type specialized syms, as these may not necessarily be/have
  2054. the right values. For example,
  2055. //constant values
  2056. c =
  2057. try
  2058. {
  2059. <exception>
  2060. c = k (constant)
  2061. }
  2062. catch
  2063. {
  2064. BailOnException
  2065. = c <-- We need to restore c from the value outside the try.
  2066. }
  2067. //copy-prop syms
  2068. c =
  2069. try
  2070. {
  2071. b = a
  2072. <exception>
  2073. c = b
  2074. }
  2075. catch
  2076. {
  2077. BailOnException
  2078. = c <-- We really want to restore c from its original sym, and not from its copy-prop sym, a
  2079. }
  2080. //type specialized syms
  2081. a =
  2082. try
  2083. {
  2084. <exception>
  2085. a++ <-- type specializes a
  2086. }
  2087. catch
  2088. {
  2089. BailOnException
  2090. = a <-- We need to restore a from its var version.
  2091. }
  2092. */
  2093. BasicBlock * block = this->currentBlock;
  2094. BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = block->byteCodeUpwardExposedUsed;
  2095. Assert(bailOutInfo->bailOutInstr == instr);
  2096. // The byteCodeUpwardExposedUsed should only be assigned once. The only case which would break this
  2097. // assumption is when we are optimizing a function having try-catch. In that case, we need the
  2098. // byteCodeUpwardExposedUsed analysis in the initial backward pass too.
  2099. Assert(bailOutInfo->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTryCatch()));
  2100. // Make a copy of the byteCodeUpwardExposedUsed so we can remove the constants
  2101. if (!this->IsPrePass())
  2102. {
  2103. // Create the BV of symbols that need to be restored in the BailOutRecord
  2104. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->func->m_alloc);
  2105. bailOutInfo->byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed;
  2106. }
  2107. else
  2108. {
  2109. // Create a temporary byteCodeUpwardExposedUsed
  2110. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->tempAlloc);
  2111. }
  2112. // All the register-based argument syms need to be tracked. They are either:
  2113. // 1. Referenced as constants in bailOutInfo->usedcapturedValues.constantValues
  2114. // 2. Referenced using copy prop syms in bailOutInfo->usedcapturedValues.copyPropSyms
  2115. // 3. Marked as m_isBailOutReferenced = true & added to upwardExposedUsed bit vector to ensure we do not dead store their defs.
  2116. // The third set of syms is represented by the bailoutReferencedArgSymsBv.
  2117. BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2118. if (!this->IsPrePass())
  2119. {
  2120. bailOutInfo->IterateArgOutSyms([=](uint, uint, StackSym* sym) {
  2121. if (!sym->IsArgSlotSym())
  2122. {
  2123. bailoutReferencedArgSymsBv->Set(sym->m_id);
  2124. }
  2125. });
  2126. }
  2127. // Process Argument object first, as they can be found on the stack and don't need to rely on copy prop
  2128. this->ProcessBailOutArgObj(bailOutInfo, byteCodeUpwardExposedUsed);
  2129. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2130. {
  2131. this->ProcessBailOutConstants(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2132. this->ProcessBailOutCopyProps(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2133. }
  2134. BVSparse<JitArenaAllocator> * tempBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2135. if (bailOutInfo->liveVarSyms)
  2136. {
  2137. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially expensive
  2138. // ToVars that can more easily be eliminated due to being dead stores.
  2139. #if DBG
  2140. // SIMD_JS
  2141. // Simd128 syms should be live in at most one form
  2142. tempBv->And(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2143. Assert(tempBv->IsEmpty());
  2144. // Verify that all syms to restore are live in some fashion
  2145. tempBv->Minus(byteCodeUpwardExposedUsed, bailOutInfo->liveVarSyms);
  2146. tempBv->Minus(bailOutInfo->liveLosslessInt32Syms);
  2147. tempBv->Minus(bailOutInfo->liveFloat64Syms);
  2148. tempBv->Minus(bailOutInfo->liveSimd128F4Syms);
  2149. tempBv->Minus(bailOutInfo->liveSimd128I4Syms);
  2150. Assert(tempBv->IsEmpty());
  2151. #endif
  2152. if (this->func->IsJitInDebugMode())
  2153. {
  2154. // Add to byteCodeUpwardExposedUsed the non-temp local vars used so far to restore during bail out.
  2155. // The ones that are not used so far will get their values from bytecode when we continue after bail out in interpreter.
  2156. Assert(this->func->m_nonTempLocalVars);
  2157. tempBv->And(this->func->m_nonTempLocalVars, bailOutInfo->liveVarSyms);
  2158. // Remove syms that are restored in other ways than byteCodeUpwardExposedUsed.
  2159. FOREACH_SLIST_ENTRY(ConstantStackSymValue, value, &bailOutInfo->usedCapturedValues.constantValues)
  2160. {
  2161. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2162. if (value.Key()->HasByteCodeRegSlot())
  2163. {
  2164. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2165. }
  2166. }
  2167. NEXT_SLIST_ENTRY;
  2168. FOREACH_SLIST_ENTRY(CopyPropSyms, value, &bailOutInfo->usedCapturedValues.copyPropSyms)
  2169. {
  2170. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2171. if (value.Key()->HasByteCodeRegSlot())
  2172. {
  2173. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2174. }
  2175. }
  2176. NEXT_SLIST_ENTRY;
  2177. if (bailOutInfo->usedCapturedValues.argObjSyms)
  2178. {
  2179. tempBv->Minus(bailOutInfo->usedCapturedValues.argObjSyms);
  2180. }
  2181. byteCodeUpwardExposedUsed->Or(tempBv);
  2182. }
  2183. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2184. {
  2185. // Int32
  2186. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveLosslessInt32Syms);
  2187. byteCodeUpwardExposedUsed->Minus(tempBv);
  2188. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2189. {
  2190. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2191. Assert(stackSym->GetType() == TyVar);
  2192. StackSym * int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  2193. Assert(int32StackSym);
  2194. byteCodeUpwardExposedUsed->Set(int32StackSym->m_id);
  2195. }
  2196. NEXT_BITSET_IN_SPARSEBV;
  2197. // Float64
  2198. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveFloat64Syms);
  2199. byteCodeUpwardExposedUsed->Minus(tempBv);
  2200. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2201. {
  2202. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2203. Assert(stackSym->GetType() == TyVar);
  2204. StackSym * float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  2205. Assert(float64StackSym);
  2206. byteCodeUpwardExposedUsed->Set(float64StackSym->m_id);
  2207. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  2208. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  2209. // specialized using BailOutNumberOnly.
  2210. float64StackSym->m_requiresBailOnNotNumber = true;
  2211. }
  2212. NEXT_BITSET_IN_SPARSEBV;
  2213. // SIMD_JS
  2214. tempBv->Or(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2215. tempBv->And(byteCodeUpwardExposedUsed);
  2216. byteCodeUpwardExposedUsed->Minus(tempBv);
  2217. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2218. {
  2219. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2220. Assert(stackSym->GetType() == TyVar);
  2221. StackSym * simd128Sym = nullptr;
  2222. if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  2223. {
  2224. simd128Sym = stackSym->GetSimd128F4EquivSym(nullptr);
  2225. }
  2226. else
  2227. {
  2228. Assert(bailOutInfo->liveSimd128I4Syms->Test(symId));
  2229. simd128Sym = stackSym->GetSimd128I4EquivSym(nullptr);
  2230. }
  2231. byteCodeUpwardExposedUsed->Set(simd128Sym->m_id);
  2232. }
  2233. NEXT_BITSET_IN_SPARSEBV;
  2234. }
  2235. // Var
  2236. // Any remaining syms to restore will be restored from their var versions
  2237. }
  2238. else
  2239. {
  2240. Assert(!this->func->DoGlobOpt());
  2241. }
  2242. JitAdelete(this->tempAlloc, tempBv);
  2243. // BailOnNoProfile makes some edges dead. Upward exposed symbols info set after the BailOnProfile won't
  2244. // flow through these edges, and, in turn, not through predecessor edges of the block containing the
  2245. // BailOnNoProfile. This is specifically bad for an inlinee's argout syms as they are set as upward exposed
  2246. // when we see the InlineeEnd, but may not look so to some blocks and may get overwritten.
  2247. // Set the argout syms as upward exposed here.
  2248. if (instr->m_opcode == Js::OpCode::BailOnNoProfile && instr->m_func->IsInlinee() &&
  2249. instr->m_func->m_hasInlineArgsOpt && instr->m_func->frameInfo->isRecorded)
  2250. {
  2251. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  2252. {
  2253. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  2254. });
  2255. }
  2256. // Mark all the register that we need to restore as used (excluding constants)
  2257. block->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  2258. block->upwardExposedUses->Or(bailoutReferencedArgSymsBv);
  2259. if (!this->IsPrePass())
  2260. {
  2261. bailOutInfo->IterateArgOutSyms([=](uint index, uint, StackSym* sym) {
  2262. if (sym->IsArgSlotSym() || bailoutReferencedArgSymsBv->Test(sym->m_id))
  2263. {
  2264. bailOutInfo->argOutSyms[index]->m_isBailOutReferenced = true;
  2265. }
  2266. });
  2267. }
  2268. JitAdelete(this->tempAlloc, bailoutReferencedArgSymsBv);
  2269. if (this->IsPrePass())
  2270. {
  2271. JitAdelete(this->tempAlloc, byteCodeUpwardExposedUsed);
  2272. }
  2273. }
  2274. void
  2275. BackwardPass::ProcessBlock(BasicBlock * block)
  2276. {
  2277. this->currentBlock = block;
  2278. this->MergeSuccBlocksInfo(block);
  2279. #if DBG_DUMP
  2280. if (this->IsTraceEnabled())
  2281. {
  2282. Output::Print(_u("******************************* Before Process Block *******************************n"));
  2283. DumpBlockData(block);
  2284. }
  2285. #endif
  2286. FOREACH_INSTR_BACKWARD_IN_BLOCK_EDITING(instr, instrPrev, block)
  2287. {
  2288. #if DBG_DUMP
  2289. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2290. {
  2291. Output::Print(_u(">>>>>>>>>>>>>>>>>>>>>> %s: Instr Start\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2292. instr->Dump();
  2293. if (block->upwardExposedUses)
  2294. {
  2295. Output::SkipToColumn(10);
  2296. Output::Print(_u(" Exposed Use: "));
  2297. block->upwardExposedUses->Dump();
  2298. }
  2299. if (block->upwardExposedFields)
  2300. {
  2301. Output::SkipToColumn(10);
  2302. Output::Print(_u("Exposed Fields: "));
  2303. block->upwardExposedFields->Dump();
  2304. }
  2305. if (block->byteCodeUpwardExposedUsed)
  2306. {
  2307. Output::SkipToColumn(10);
  2308. Output::Print(_u(" Byte Code Use: "));
  2309. block->byteCodeUpwardExposedUsed->Dump();
  2310. }
  2311. Output::Print(_u("--------------------\n"));
  2312. }
  2313. #endif
  2314. AssertOrFailFastMsg(!instr->IsLowered(), "Lowered instruction detected in pre-lower context!");
  2315. this->currentInstr = instr;
  2316. this->currentRegion = this->currentBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  2317. IR::Instr * insertedInstr = TryChangeInstrForStackArgOpt();
  2318. if (insertedInstr != nullptr)
  2319. {
  2320. instrPrev = insertedInstr;
  2321. continue;
  2322. }
  2323. MarkScopeObjSymUseForStackArgOpt();
  2324. ProcessBailOnStackArgsOutOfActualsRange();
  2325. if (ProcessNoImplicitCallUses(instr) || this->ProcessBailOutInfo(instr))
  2326. {
  2327. continue;
  2328. }
  2329. IR::Instr *instrNext = instr->m_next;
  2330. if (this->TrackNoImplicitCallInlinees(instr))
  2331. {
  2332. instrPrev = instrNext->m_prev;
  2333. continue;
  2334. }
  2335. if (CanDeadStoreInstrForScopeObjRemoval() && DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev))
  2336. {
  2337. continue;
  2338. }
  2339. bool hasLiveFields = (block->upwardExposedFields && !block->upwardExposedFields->IsEmpty());
  2340. IR::Opnd * opnd = instr->GetDst();
  2341. if (opnd != nullptr)
  2342. {
  2343. bool isRemoved = ReverseCopyProp(instr);
  2344. if (isRemoved)
  2345. {
  2346. instrPrev = instrNext->m_prev;
  2347. continue;
  2348. }
  2349. if (instr->m_opcode == Js::OpCode::Conv_Bool)
  2350. {
  2351. isRemoved = this->FoldCmBool(instr);
  2352. if (isRemoved)
  2353. {
  2354. continue;
  2355. }
  2356. }
  2357. ProcessNewScObject(instr);
  2358. this->ProcessTransfers(instr);
  2359. isRemoved = this->ProcessDef(opnd);
  2360. if (isRemoved)
  2361. {
  2362. continue;
  2363. }
  2364. }
  2365. if(!IsCollectionPass())
  2366. {
  2367. this->MarkTempProcessInstr(instr);
  2368. this->ProcessFieldKills(instr);
  2369. if (this->DoDeadStoreSlots()
  2370. && (instr->HasAnyImplicitCalls() || instr->HasBailOutInfo() || instr->UsesAllFields()))
  2371. {
  2372. // Can't dead-store slots if there can be an implicit-call, an exception, or a bailout
  2373. block->slotDeadStoreCandidates->ClearAll();
  2374. }
  2375. if (this->DoFieldHoistCandidates())
  2376. {
  2377. this->ProcessFieldHoistKills(instr);
  2378. }
  2379. TrackIntUsage(instr);
  2380. TrackBitWiseOrNumberOp(instr);
  2381. TrackFloatSymEquivalence(instr);
  2382. }
  2383. opnd = instr->GetSrc1();
  2384. if (opnd != nullptr)
  2385. {
  2386. this->ProcessUse(opnd);
  2387. opnd = instr->GetSrc2();
  2388. if (opnd != nullptr)
  2389. {
  2390. this->ProcessUse(opnd);
  2391. }
  2392. }
  2393. if(IsCollectionPass())
  2394. {
  2395. continue;
  2396. }
  2397. if (this->tag == Js::DeadStorePhase)
  2398. {
  2399. switch(instr->m_opcode)
  2400. {
  2401. case Js::OpCode::LdSlot:
  2402. {
  2403. DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev);
  2404. break;
  2405. }
  2406. case Js::OpCode::InlineArrayPush:
  2407. case Js::OpCode::InlineArrayPop:
  2408. {
  2409. IR::Opnd *const thisOpnd = instr->GetSrc1();
  2410. if(thisOpnd && thisOpnd->IsRegOpnd())
  2411. {
  2412. IR::RegOpnd *const thisRegOpnd = thisOpnd->AsRegOpnd();
  2413. if(thisRegOpnd->IsArrayRegOpnd())
  2414. {
  2415. // Process the array use at the point of the array built-in call, since the array will actually
  2416. // be used at the call, not at the ArgOut_A_InlineBuiltIn
  2417. ProcessArrayRegOpndUse(instr, thisRegOpnd->AsArrayRegOpnd());
  2418. }
  2419. }
  2420. }
  2421. #if !INT32VAR // the following is not valid on 64-bit platforms
  2422. case Js::OpCode::BoundCheck:
  2423. {
  2424. if(IsPrePass())
  2425. {
  2426. break;
  2427. }
  2428. // Look for:
  2429. // BoundCheck 0 <= s1
  2430. // BoundCheck s1 <= s2 + c, where c == 0 || c == -1
  2431. //
  2432. // And change it to:
  2433. // UnsignedBoundCheck s1 <= s2 + c
  2434. //
  2435. // The BoundCheck instruction is a signed operation, so any unsigned operand used in the instruction must be
  2436. // guaranteed to be >= 0 and <= int32 max when its value is interpreted as signed. Due to the restricted
  2437. // range of s2 above, by using an unsigned comparison instead, the negative check on s1 will also be
  2438. // covered.
  2439. //
  2440. // A BoundCheck instruction takes the form (src1 <= src2 + dst).
  2441. // Check the current instruction's pattern for:
  2442. // BoundCheck s1 <= s2 + c, where c <= 0
  2443. if(!instr->GetSrc1()->IsRegOpnd() ||
  2444. !instr->GetSrc1()->IsInt32() ||
  2445. !instr->GetSrc2() ||
  2446. instr->GetSrc2()->IsIntConstOpnd())
  2447. {
  2448. break;
  2449. }
  2450. if(instr->GetDst())
  2451. {
  2452. const int c = instr->GetDst()->AsIntConstOpnd()->GetValue();
  2453. if(c != 0 && c != -1)
  2454. {
  2455. break;
  2456. }
  2457. }
  2458. // Check the previous instruction's pattern for:
  2459. // BoundCheck 0 <= s1
  2460. IR::Instr *const lowerBoundCheck = instr->m_prev;
  2461. if(lowerBoundCheck->m_opcode != Js::OpCode::BoundCheck ||
  2462. !lowerBoundCheck->GetSrc1()->IsIntConstOpnd() ||
  2463. lowerBoundCheck->GetSrc1()->AsIntConstOpnd()->GetValue() != 0 ||
  2464. !lowerBoundCheck->GetSrc2() ||
  2465. !instr->GetSrc1()->AsRegOpnd()->IsEqual(lowerBoundCheck->GetSrc2()) ||
  2466. lowerBoundCheck->GetDst() && lowerBoundCheck->GetDst()->AsIntConstOpnd()->GetValue() != 0)
  2467. {
  2468. break;
  2469. }
  2470. // Remove the previous lower bound check, and change the current upper bound check to:
  2471. // UnsignedBoundCheck s1 <= s2 + c
  2472. instr->m_opcode = Js::OpCode::UnsignedBoundCheck;
  2473. currentBlock->RemoveInstr(lowerBoundCheck);
  2474. instrPrev = instr->m_prev;
  2475. break;
  2476. }
  2477. #endif
  2478. }
  2479. DeadStoreTypeCheckBailOut(instr);
  2480. DeadStoreImplicitCallBailOut(instr, hasLiveFields);
  2481. if (block->stackSymToFinalType != nullptr)
  2482. {
  2483. this->InsertTypeTransitionsAtPotentialKills();
  2484. }
  2485. // NoImplicitCallUses transfers need to be processed after determining whether implicit calls need to be disabled
  2486. // for the current instruction, because the instruction where the def occurs also needs implicit calls disabled.
  2487. // Array value type for the destination needs to be updated before transfers have been processed by
  2488. // ProcessNoImplicitCallDef, and array value types for sources need to be updated after transfers have been
  2489. // processed by ProcessNoImplicitCallDef, as it requires the no-implicit-call tracking bit-vectors to be precise at
  2490. // the point of the update.
  2491. if(!IsPrePass())
  2492. {
  2493. UpdateArrayValueTypes(instr, instr->GetDst());
  2494. }
  2495. ProcessNoImplicitCallDef(instr);
  2496. if(!IsPrePass())
  2497. {
  2498. UpdateArrayValueTypes(instr, instr->GetSrc1());
  2499. UpdateArrayValueTypes(instr, instr->GetSrc2());
  2500. }
  2501. }
  2502. else
  2503. {
  2504. switch (instr->m_opcode)
  2505. {
  2506. case Js::OpCode::BailOnNoProfile:
  2507. {
  2508. this->ProcessBailOnNoProfile(instr, block);
  2509. // this call could change the last instr of the previous block... Adjust instrStop.
  2510. instrStop = block->GetFirstInstr()->m_prev;
  2511. Assert(this->tag != Js::DeadStorePhase);
  2512. continue;
  2513. }
  2514. case Js::OpCode::Catch:
  2515. {
  2516. if (this->func->DoOptimizeTryCatch() && !this->IsPrePass())
  2517. {
  2518. // Execute the "Catch" in the JIT'ed code, and bailout to the next instruction. This way, the bailout will restore the exception object automatically.
  2519. IR::BailOutInstr* bailOnException = IR::BailOutInstr::New(Js::OpCode::BailOnException, IR::BailOutOnException, instr->m_next, instr->m_func);
  2520. instr->InsertAfter(bailOnException);
  2521. Assert(instr->GetDst()->IsRegOpnd() && instr->GetDst()->GetStackSym()->HasByteCodeRegSlot());
  2522. StackSym * exceptionObjSym = instr->GetDst()->GetStackSym();
  2523. Assert(instr->m_prev->IsLabelInstr() && (instr->m_prev->AsLabelInstr()->GetRegion()->GetType() == RegionTypeCatch));
  2524. instr->m_prev->AsLabelInstr()->GetRegion()->SetExceptionObjectSym(exceptionObjSym);
  2525. }
  2526. break;
  2527. }
  2528. case Js::OpCode::Throw:
  2529. case Js::OpCode::EHThrow:
  2530. case Js::OpCode::InlineThrow:
  2531. this->func->SetHasThrow();
  2532. break;
  2533. }
  2534. }
  2535. if (instr->m_opcode == Js::OpCode::InlineeEnd)
  2536. {
  2537. this->ProcessInlineeEnd(instr);
  2538. }
  2539. if (instr->IsLabelInstr() && instr->m_next->m_opcode == Js::OpCode::Catch)
  2540. {
  2541. if (!this->currentRegion)
  2542. {
  2543. Assert(!this->func->DoOptimizeTryCatch() && !(this->func->IsSimpleJit() && this->func->hasBailout));
  2544. }
  2545. else
  2546. {
  2547. Assert(this->currentRegion->GetType() == RegionTypeCatch);
  2548. Region * matchingTryRegion = this->currentRegion->GetMatchingTryRegion();
  2549. Assert(matchingTryRegion);
  2550. // We need live-on-back-edge info to accurately set write-through symbols for try-catches in a loop.
  2551. // Don't set write-through symbols in pre-pass
  2552. if (!this->IsPrePass() && !matchingTryRegion->writeThroughSymbolsSet)
  2553. {
  2554. if (this->tag == Js::DeadStorePhase)
  2555. {
  2556. Assert(!this->func->DoGlobOpt());
  2557. }
  2558. // FullJit: Write-through symbols info must be populated in the backward pass as
  2559. // 1. the forward pass needs it to insert ToVars.
  2560. // 2. the deadstore pass needs it to not clear such symbols from the
  2561. // byteCodeUpwardExposedUsed BV upon a def in the try region. This is required
  2562. // because any bailout in the try region needs to restore all write-through
  2563. // symbols.
  2564. // SimpleJit: Won't run the initial backward pass, but write-through symbols info is still
  2565. // needed in the deadstore pass for <2> above.
  2566. this->SetWriteThroughSymbolsSetForRegion(this->currentBlock, matchingTryRegion);
  2567. }
  2568. }
  2569. }
  2570. #if DBG
  2571. if (instr->m_opcode == Js::OpCode::TryCatch)
  2572. {
  2573. if (!this->IsPrePass() && (this->func->DoOptimizeTryCatch() || (this->func->IsSimpleJit() && this->func->hasBailout)))
  2574. {
  2575. Assert(instr->m_next->IsLabelInstr() && (instr->m_next->AsLabelInstr()->GetRegion() != nullptr));
  2576. Region * tryRegion = instr->m_next->AsLabelInstr()->GetRegion();
  2577. Assert(tryRegion->writeThroughSymbolsSet);
  2578. }
  2579. }
  2580. #endif
  2581. ProcessPendingPreOpBailOutInfo(instr);
  2582. #if DBG_DUMP
  2583. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2584. {
  2585. Output::Print(_u("-------------------\n"));
  2586. instr->Dump();
  2587. if (block->upwardExposedUses)
  2588. {
  2589. Output::SkipToColumn(10);
  2590. Output::Print(_u(" Exposed Use: "));
  2591. block->upwardExposedUses->Dump();
  2592. }
  2593. if (block->upwardExposedFields)
  2594. {
  2595. Output::SkipToColumn(10);
  2596. Output::Print(_u("Exposed Fields: "));
  2597. block->upwardExposedFields->Dump();
  2598. }
  2599. if (block->byteCodeUpwardExposedUsed)
  2600. {
  2601. Output::SkipToColumn(10);
  2602. Output::Print(_u(" Byte Code Use: "));
  2603. block->byteCodeUpwardExposedUsed->Dump();
  2604. }
  2605. Output::Print(_u("<<<<<<<<<<<<<<<<<<<<<< %s: Instr End\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2606. }
  2607. #endif
  2608. }
  2609. NEXT_INSTR_BACKWARD_IN_BLOCK_EDITING;
  2610. EndIntOverflowDoesNotMatterRange();
  2611. if (this->DoFieldHoistCandidates() && !block->isDead && block->isLoopHeader)
  2612. {
  2613. Assert(block->loop->fieldHoistCandidates == nullptr);
  2614. block->loop->fieldHoistCandidates = block->fieldHoistCandidates->CopyNew(this->func->m_alloc);
  2615. }
  2616. if (!this->IsPrePass() && !block->isDead && block->isLoopHeader)
  2617. {
  2618. // Copy the upward exposed use as the live on back edge regs
  2619. block->loop->regAlloc.liveOnBackEdgeSyms = block->upwardExposedUses->CopyNew(this->func->m_alloc);
  2620. }
  2621. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  2622. #if DBG_DUMP
  2623. if (this->IsTraceEnabled())
  2624. {
  2625. Output::Print(_u("******************************* After Process Block *******************************n"));
  2626. DumpBlockData(block);
  2627. }
  2628. #endif
  2629. }
  2630. bool
  2631. BackwardPass::CanDeadStoreInstrForScopeObjRemoval(Sym *sym) const
  2632. {
  2633. if (tag == Js::DeadStorePhase && this->currentInstr->m_func->IsStackArgsEnabled())
  2634. {
  2635. Func * currFunc = this->currentInstr->m_func;
  2636. bool doScopeObjCreation = currFunc->GetJITFunctionBody()->GetDoScopeObjectCreation();
  2637. switch (this->currentInstr->m_opcode)
  2638. {
  2639. case Js::OpCode::InitCachedScope:
  2640. {
  2641. if(!doScopeObjCreation && this->currentInstr->GetDst()->IsScopeObjOpnd(currFunc))
  2642. {
  2643. /*
  2644. * We don't really dead store this instruction. We just want the source sym of this instruction
  2645. * to NOT be tracked as USED by this instruction.
  2646. * This instr will effectively be lowered to dest = MOV NULLObject, in the lowerer phase.
  2647. */
  2648. return true;
  2649. }
  2650. break;
  2651. }
  2652. case Js::OpCode::LdSlot:
  2653. {
  2654. if (sym && IsFormalParamSym(currFunc, sym))
  2655. {
  2656. return true;
  2657. }
  2658. break;
  2659. }
  2660. case Js::OpCode::CommitScope:
  2661. case Js::OpCode::GetCachedFunc:
  2662. {
  2663. return !doScopeObjCreation && this->currentInstr->GetSrc1()->IsScopeObjOpnd(currFunc);
  2664. }
  2665. case Js::OpCode::BrFncCachedScopeEq:
  2666. case Js::OpCode::BrFncCachedScopeNeq:
  2667. {
  2668. return !doScopeObjCreation && this->currentInstr->GetSrc2()->IsScopeObjOpnd(currFunc);
  2669. }
  2670. case Js::OpCode::CallHelper:
  2671. {
  2672. if (!doScopeObjCreation && this->currentInstr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2673. {
  2674. IR::RegOpnd * scopeObjOpnd = this->currentInstr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2675. return scopeObjOpnd->IsScopeObjOpnd(currFunc);
  2676. }
  2677. break;
  2678. }
  2679. }
  2680. }
  2681. return false;
  2682. }
  2683. /*
  2684. * This is for Eliminating Scope Object Creation during Heap arguments optimization.
  2685. */
  2686. bool
  2687. BackwardPass::DeadStoreOrChangeInstrForScopeObjRemoval(IR::Instr ** pInstrPrev)
  2688. {
  2689. IR::Instr * instr = this->currentInstr;
  2690. Func * currFunc = instr->m_func;
  2691. if (this->tag == Js::DeadStorePhase && instr->m_func->IsStackArgsEnabled() && !IsPrePass())
  2692. {
  2693. switch (instr->m_opcode)
  2694. {
  2695. /*
  2696. * This LdSlot loads the formal from the formals array. We replace this a Ld_A <ArgInSym>.
  2697. * ArgInSym is inserted at the beginning of the function during the start of the deadstore pass- for the top func.
  2698. * In case of inlinee, it will be from the source sym of the ArgOut Instruction to the inlinee.
  2699. */
  2700. case Js::OpCode::LdSlot:
  2701. {
  2702. IR::Opnd * src1 = instr->GetSrc1();
  2703. if (src1 && src1->IsSymOpnd())
  2704. {
  2705. Sym * sym = src1->AsSymOpnd()->m_sym;
  2706. Assert(sym);
  2707. if (IsFormalParamSym(currFunc, sym))
  2708. {
  2709. AssertMsg(!currFunc->GetJITFunctionBody()->HasImplicitArgIns(), "We don't have mappings between named formals and arguments object here");
  2710. instr->m_opcode = Js::OpCode::Ld_A;
  2711. PropertySym * propSym = sym->AsPropertySym();
  2712. Js::ArgSlot value = (Js::ArgSlot)propSym->m_propertyId;
  2713. Assert(currFunc->HasStackSymForFormal(value));
  2714. StackSym * paramStackSym = currFunc->GetStackSymForFormal(value);
  2715. IR::RegOpnd * srcOpnd = IR::RegOpnd::New(paramStackSym, TyVar, currFunc);
  2716. instr->ReplaceSrc1(srcOpnd);
  2717. this->ProcessSymUse(paramStackSym, true, true);
  2718. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase))
  2719. {
  2720. Output::Print(_u("StackArgFormals : %s (%d) :Replacing LdSlot with Ld_A in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2721. Output::Flush();
  2722. }
  2723. }
  2724. }
  2725. break;
  2726. }
  2727. case Js::OpCode::CommitScope:
  2728. {
  2729. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2730. {
  2731. instr->Remove();
  2732. return true;
  2733. }
  2734. break;
  2735. }
  2736. case Js::OpCode::BrFncCachedScopeEq:
  2737. case Js::OpCode::BrFncCachedScopeNeq:
  2738. {
  2739. if (instr->GetSrc2()->IsScopeObjOpnd(currFunc))
  2740. {
  2741. instr->Remove();
  2742. return true;
  2743. }
  2744. break;
  2745. }
  2746. case Js::OpCode::CallHelper:
  2747. {
  2748. //Remove the CALL and all its Argout instrs.
  2749. if (instr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2750. {
  2751. IR::RegOpnd * scopeObjOpnd = instr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2752. if (scopeObjOpnd->IsScopeObjOpnd(currFunc))
  2753. {
  2754. IR::Instr * instrDef = instr;
  2755. IR::Instr * nextInstr = instr->m_next;
  2756. while (instrDef != nullptr)
  2757. {
  2758. IR::Instr * instrToDelete = instrDef;
  2759. if (instrDef->GetSrc2() != nullptr)
  2760. {
  2761. instrDef = instrDef->GetSrc2()->GetStackSym()->GetInstrDef();
  2762. Assert(instrDef->m_opcode == Js::OpCode::ArgOut_A);
  2763. }
  2764. else
  2765. {
  2766. instrDef = nullptr;
  2767. }
  2768. instrToDelete->Remove();
  2769. }
  2770. Assert(nextInstr != nullptr);
  2771. *pInstrPrev = nextInstr->m_prev;
  2772. return true;
  2773. }
  2774. }
  2775. break;
  2776. }
  2777. case Js::OpCode::GetCachedFunc:
  2778. {
  2779. // <dst> = GetCachedFunc <scopeObject>, <functionNum>
  2780. // is converted to
  2781. // <dst> = NewScFunc <functionNum>, <env: FrameDisplay>
  2782. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2783. {
  2784. instr->m_opcode = Js::OpCode::NewScFunc;
  2785. IR::Opnd * intConstOpnd = instr->UnlinkSrc2();
  2786. instr->ReplaceSrc1(intConstOpnd);
  2787. instr->SetSrc2(IR::RegOpnd::New(currFunc->GetLocalFrameDisplaySym(), IRType::TyVar, currFunc));
  2788. }
  2789. break;
  2790. }
  2791. }
  2792. }
  2793. return false;
  2794. }
  2795. IR::Instr *
  2796. BackwardPass::TryChangeInstrForStackArgOpt()
  2797. {
  2798. IR::Instr * instr = this->currentInstr;
  2799. if (tag == Js::DeadStorePhase && instr->DoStackArgsOpt(this->func))
  2800. {
  2801. switch (instr->m_opcode)
  2802. {
  2803. case Js::OpCode::TypeofElem:
  2804. {
  2805. /*
  2806. Before:
  2807. dst = TypeOfElem arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2808. After:
  2809. tmpdst = LdElemI_A arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2810. dst = TypeOf tmpdst
  2811. */
  2812. AssertMsg(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutKind::BailOnStackArgsOutOfActualsRange), "Why is the bailout kind not set, when it is StackArgOptimized?");
  2813. instr->m_opcode = Js::OpCode::LdElemI_A;
  2814. IR::Opnd * dstOpnd = instr->UnlinkDst();
  2815. IR::RegOpnd * elementOpnd = IR::RegOpnd::New(StackSym::New(instr->m_func), IRType::TyVar, instr->m_func);
  2816. instr->SetDst(elementOpnd);
  2817. IR::Instr * typeOfInstr = IR::Instr::New(Js::OpCode::Typeof, dstOpnd, elementOpnd, instr->m_func);
  2818. instr->InsertAfter(typeOfInstr);
  2819. return typeOfInstr;
  2820. }
  2821. }
  2822. }
  2823. /*
  2824. * Scope Object Sym is kept alive in all code paths.
  2825. * -This is to facilitate Bailout to record the live Scope object Sym, whenever required.
  2826. * -Reason for doing is this because - Scope object has to be implicitly live whenever Heap Arguments object is live.
  2827. * -When we restore HeapArguments object in the bail out path, it expects the scope object also to be restored - if one was created.
  2828. * -We do not know detailed information about Heap arguments obj syms(aliasing etc.) until we complete Forward Pass.
  2829. * -And we want to avoid dead sym clean up (in this case, scope object though not explicitly live, it is live implicitly) during Block merging in the forward pass.
  2830. * -Hence this is the optimal spot to do this.
  2831. */
  2832. if (tag == Js::BackwardPhase && instr->m_func->GetScopeObjSym() != nullptr)
  2833. {
  2834. this->currentBlock->upwardExposedUses->Set(instr->m_func->GetScopeObjSym()->m_id);
  2835. }
  2836. return nullptr;
  2837. }
  2838. void
  2839. BackwardPass::TraceDeadStoreOfInstrsForScopeObjectRemoval()
  2840. {
  2841. IR::Instr * instr = this->currentInstr;
  2842. if (instr->m_func->IsStackArgsEnabled())
  2843. {
  2844. if ((instr->m_opcode == Js::OpCode::InitCachedScope || instr->m_opcode == Js::OpCode::NewScopeObject) && !IsPrePass())
  2845. {
  2846. if (PHASE_TRACE1(Js::StackArgFormalsOptPhase))
  2847. {
  2848. Output::Print(_u("StackArgFormals : %s (%d) :Removing Scope object creation in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2849. Output::Flush();
  2850. }
  2851. }
  2852. }
  2853. }
  2854. bool
  2855. BackwardPass::IsFormalParamSym(Func * func, Sym * sym) const
  2856. {
  2857. Assert(sym);
  2858. if (sym->IsPropertySym())
  2859. {
  2860. //If the sym is a propertySym, then see if the propertyId is within the range of the formals
  2861. //We can have other properties stored in the scope object other than the formals (following the formals).
  2862. PropertySym * propSym = sym->AsPropertySym();
  2863. IntConstType value = propSym->m_propertyId;
  2864. return func->IsFormalsArraySym(propSym->m_stackSym->m_id) &&
  2865. (value >= 0 && value < func->GetJITFunctionBody()->GetInParamsCount() - 1);
  2866. }
  2867. else
  2868. {
  2869. Assert(sym->IsStackSym());
  2870. return !!func->IsFormalsArraySym(sym->AsStackSym()->m_id);
  2871. }
  2872. }
  2873. #if DBG_DUMP
  2874. void
  2875. BackwardPass::DumpBlockData(BasicBlock * block)
  2876. {
  2877. block->DumpHeader();
  2878. if (block->upwardExposedUses) // may be null for dead blocks
  2879. {
  2880. Output::Print(_u(" Exposed Uses: "));
  2881. block->upwardExposedUses->Dump();
  2882. }
  2883. if (block->typesNeedingKnownObjectLayout)
  2884. {
  2885. Output::Print(_u(" Needs Known Object Layout: "));
  2886. block->typesNeedingKnownObjectLayout->Dump();
  2887. }
  2888. if (this->DoFieldHoistCandidates() && !block->isDead)
  2889. {
  2890. Output::Print(_u(" Exposed Field: "));
  2891. block->fieldHoistCandidates->Dump();
  2892. }
  2893. if (block->byteCodeUpwardExposedUsed)
  2894. {
  2895. Output::Print(_u(" Byte Code Exposed Uses: "));
  2896. block->byteCodeUpwardExposedUsed->Dump();
  2897. }
  2898. if (!this->IsCollectionPass())
  2899. {
  2900. if (!block->isDead)
  2901. {
  2902. if (this->DoDeadStoreSlots())
  2903. {
  2904. Output::Print(_u("Slot deadStore candidates: "));
  2905. block->slotDeadStoreCandidates->Dump();
  2906. }
  2907. DumpMarkTemp();
  2908. }
  2909. }
  2910. Output::Flush();
  2911. }
  2912. #endif
  2913. bool
  2914. BackwardPass::UpdateImplicitCallBailOutKind(IR::Instr *const instr, bool needsBailOutOnImplicitCall)
  2915. {
  2916. Assert(instr);
  2917. Assert(instr->HasBailOutInfo());
  2918. IR::BailOutKind implicitCallBailOutKind = needsBailOutOnImplicitCall ? IR::BailOutOnImplicitCalls : IR::BailOutInvalid;
  2919. const IR::BailOutKind instrBailOutKind = instr->GetBailOutKind();
  2920. if (instrBailOutKind & IR::BailOutMarkTempObject)
  2921. {
  2922. // Don't remove the implicit call pre op bailout for mark temp object
  2923. // Remove the mark temp object bit, as we don't need it after the dead store pass
  2924. instr->SetBailOutKind(instrBailOutKind & ~IR::BailOutMarkTempObject);
  2925. return true;
  2926. }
  2927. const IR::BailOutKind instrImplicitCallBailOutKind = instrBailOutKind & ~IR::BailOutKindBits;
  2928. if(instrImplicitCallBailOutKind == IR::BailOutOnImplicitCallsPreOp)
  2929. {
  2930. if(needsBailOutOnImplicitCall)
  2931. {
  2932. implicitCallBailOutKind = IR::BailOutOnImplicitCallsPreOp;
  2933. }
  2934. }
  2935. else if(instrImplicitCallBailOutKind != IR::BailOutOnImplicitCalls && instrImplicitCallBailOutKind != IR::BailOutInvalid)
  2936. {
  2937. // This bailout kind (the value of 'instrImplicitCallBailOutKind') must guarantee that implicit calls will not happen.
  2938. // If it doesn't make such a guarantee, it must be possible to merge this bailout kind with an implicit call bailout
  2939. // kind, and therefore should be part of BailOutKindBits.
  2940. Assert(!needsBailOutOnImplicitCall);
  2941. return true;
  2942. }
  2943. if(instrImplicitCallBailOutKind == implicitCallBailOutKind)
  2944. {
  2945. return true;
  2946. }
  2947. const IR::BailOutKind newBailOutKind = instrBailOutKind - instrImplicitCallBailOutKind + implicitCallBailOutKind;
  2948. if(newBailOutKind == IR::BailOutInvalid)
  2949. {
  2950. return false;
  2951. }
  2952. instr->SetBailOutKind(newBailOutKind);
  2953. return true;
  2954. }
  2955. bool
  2956. BackwardPass::ProcessNoImplicitCallUses(IR::Instr *const instr)
  2957. {
  2958. Assert(instr);
  2959. if(instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  2960. {
  2961. return false;
  2962. }
  2963. Assert(tag == Js::DeadStorePhase);
  2964. Assert(!instr->GetDst());
  2965. Assert(instr->GetSrc1());
  2966. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsSymOpnd());
  2967. Assert(!instr->GetSrc2() || instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsSymOpnd());
  2968. if(IsCollectionPass())
  2969. {
  2970. return true;
  2971. }
  2972. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  2973. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  2974. {
  2975. IR::Opnd *const src = srcs[i];
  2976. IR::ArrayRegOpnd *arraySrc = nullptr;
  2977. Sym *sym;
  2978. switch(src->GetKind())
  2979. {
  2980. case IR::OpndKindReg:
  2981. {
  2982. IR::RegOpnd *const regSrc = src->AsRegOpnd();
  2983. sym = regSrc->m_sym;
  2984. if(considerSymAsRealUseInNoImplicitCallUses && considerSymAsRealUseInNoImplicitCallUses == sym)
  2985. {
  2986. considerSymAsRealUseInNoImplicitCallUses = nullptr;
  2987. ProcessStackSymUse(sym->AsStackSym(), true);
  2988. }
  2989. if(regSrc->IsArrayRegOpnd())
  2990. {
  2991. arraySrc = regSrc->AsArrayRegOpnd();
  2992. }
  2993. break;
  2994. }
  2995. case IR::OpndKindSym:
  2996. sym = src->AsSymOpnd()->m_sym;
  2997. Assert(sym->IsPropertySym());
  2998. break;
  2999. default:
  3000. Assert(false);
  3001. __assume(false);
  3002. }
  3003. currentBlock->noImplicitCallUses->Set(sym->m_id);
  3004. const ValueType valueType(src->GetValueType());
  3005. if(valueType.IsArrayOrObjectWithArray())
  3006. {
  3007. if(valueType.HasNoMissingValues())
  3008. {
  3009. currentBlock->noImplicitCallNoMissingValuesUses->Set(sym->m_id);
  3010. }
  3011. if(!valueType.HasVarElements())
  3012. {
  3013. currentBlock->noImplicitCallNativeArrayUses->Set(sym->m_id);
  3014. }
  3015. if(arraySrc)
  3016. {
  3017. ProcessArrayRegOpndUse(instr, arraySrc);
  3018. }
  3019. }
  3020. }
  3021. if(!IsPrePass())
  3022. {
  3023. currentBlock->RemoveInstr(instr);
  3024. }
  3025. return true;
  3026. }
  3027. void
  3028. BackwardPass::ProcessNoImplicitCallDef(IR::Instr *const instr)
  3029. {
  3030. Assert(tag == Js::DeadStorePhase);
  3031. Assert(instr);
  3032. IR::Opnd *const dst = instr->GetDst();
  3033. if(!dst)
  3034. {
  3035. return;
  3036. }
  3037. Sym *dstSym;
  3038. switch(dst->GetKind())
  3039. {
  3040. case IR::OpndKindReg:
  3041. dstSym = dst->AsRegOpnd()->m_sym;
  3042. break;
  3043. case IR::OpndKindSym:
  3044. dstSym = dst->AsSymOpnd()->m_sym;
  3045. if(!dstSym->IsPropertySym())
  3046. {
  3047. return;
  3048. }
  3049. break;
  3050. default:
  3051. return;
  3052. }
  3053. if(!currentBlock->noImplicitCallUses->TestAndClear(dstSym->m_id))
  3054. {
  3055. Assert(!currentBlock->noImplicitCallNoMissingValuesUses->Test(dstSym->m_id));
  3056. Assert(!currentBlock->noImplicitCallNativeArrayUses->Test(dstSym->m_id));
  3057. Assert(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Test(dstSym->m_id));
  3058. Assert(!currentBlock->noImplicitCallArrayLengthSymUses->Test(dstSym->m_id));
  3059. return;
  3060. }
  3061. const bool transferNoMissingValuesUse = !!currentBlock->noImplicitCallNoMissingValuesUses->TestAndClear(dstSym->m_id);
  3062. const bool transferNativeArrayUse = !!currentBlock->noImplicitCallNativeArrayUses->TestAndClear(dstSym->m_id);
  3063. const bool transferJsArrayHeadSegmentSymUse =
  3064. !!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->TestAndClear(dstSym->m_id);
  3065. const bool transferArrayLengthSymUse = !!currentBlock->noImplicitCallArrayLengthSymUses->TestAndClear(dstSym->m_id);
  3066. IR::Opnd *const src = instr->GetSrc1();
  3067. if(!src || instr->GetSrc2())
  3068. {
  3069. return;
  3070. }
  3071. if(dst->IsRegOpnd() && src->IsRegOpnd())
  3072. {
  3073. if(!OpCodeAttr::NonIntTransfer(instr->m_opcode))
  3074. {
  3075. return;
  3076. }
  3077. }
  3078. else if(
  3079. !(
  3080. // LdFld or similar
  3081. (dst->IsRegOpnd() && src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym()) ||
  3082. // StFld or similar. Don't transfer a field opnd from StFld into the reg opnd src unless the field's value type is
  3083. // definitely array or object with array, because only those value types require implicit calls to be disabled as
  3084. // long as they are live. Other definite value types only require implicit calls to be disabled as long as a live
  3085. // field holds the value, which is up to the StFld when going backwards.
  3086. (src->IsRegOpnd() && dst->GetValueType().IsArrayOrObjectWithArray())
  3087. ) ||
  3088. !GlobOpt::TransferSrcValue(instr))
  3089. {
  3090. return;
  3091. }
  3092. Sym *srcSym;
  3093. switch(src->GetKind())
  3094. {
  3095. case IR::OpndKindReg:
  3096. srcSym = src->AsRegOpnd()->m_sym;
  3097. break;
  3098. case IR::OpndKindSym:
  3099. srcSym = src->AsSymOpnd()->m_sym;
  3100. Assert(srcSym->IsPropertySym());
  3101. break;
  3102. default:
  3103. Assert(false);
  3104. __assume(false);
  3105. }
  3106. currentBlock->noImplicitCallUses->Set(srcSym->m_id);
  3107. if(transferNoMissingValuesUse)
  3108. {
  3109. currentBlock->noImplicitCallNoMissingValuesUses->Set(srcSym->m_id);
  3110. }
  3111. if(transferNativeArrayUse)
  3112. {
  3113. currentBlock->noImplicitCallNativeArrayUses->Set(srcSym->m_id);
  3114. }
  3115. if(transferJsArrayHeadSegmentSymUse)
  3116. {
  3117. currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Set(srcSym->m_id);
  3118. }
  3119. if(transferArrayLengthSymUse)
  3120. {
  3121. currentBlock->noImplicitCallArrayLengthSymUses->Set(srcSym->m_id);
  3122. }
  3123. }
  3124. template<class F>
  3125. IR::Opnd *
  3126. BackwardPass::FindNoImplicitCallUse(
  3127. IR::Instr *const instr,
  3128. StackSym *const sym,
  3129. const F IsCheckedUse,
  3130. IR::Instr * *const noImplicitCallUsesInstrRef)
  3131. {
  3132. IR::RegOpnd *const opnd = IR::RegOpnd::New(sym, sym->GetType(), instr->m_func);
  3133. IR::Opnd *const use = FindNoImplicitCallUse(instr, opnd, IsCheckedUse, noImplicitCallUsesInstrRef);
  3134. opnd->FreeInternal(instr->m_func);
  3135. return use;
  3136. }
  3137. template<class F>
  3138. IR::Opnd *
  3139. BackwardPass::FindNoImplicitCallUse(
  3140. IR::Instr *const instr,
  3141. IR::Opnd *const opnd,
  3142. const F IsCheckedUse,
  3143. IR::Instr * *const noImplicitCallUsesInstrRef)
  3144. {
  3145. Assert(instr);
  3146. Assert(instr->m_opcode != Js::OpCode::NoImplicitCallUses);
  3147. // Skip byte-code uses
  3148. IR::Instr *prevInstr = instr->m_prev;
  3149. while(
  3150. prevInstr &&
  3151. !prevInstr->IsLabelInstr() &&
  3152. (!prevInstr->IsRealInstr() || prevInstr->IsByteCodeUsesInstr()) &&
  3153. prevInstr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3154. {
  3155. prevInstr = prevInstr->m_prev;
  3156. }
  3157. // Find the corresponding use in a NoImplicitCallUses instruction
  3158. for(; prevInstr && prevInstr->m_opcode == Js::OpCode::NoImplicitCallUses; prevInstr = prevInstr->m_prev)
  3159. {
  3160. IR::Opnd *const checkedSrcs[] = { prevInstr->GetSrc1(), prevInstr->GetSrc2() };
  3161. for(int i = 0; i < sizeof(checkedSrcs) / sizeof(checkedSrcs[0]) && checkedSrcs[i]; ++i)
  3162. {
  3163. IR::Opnd *const checkedSrc = checkedSrcs[i];
  3164. if(checkedSrc->IsEqual(opnd) && IsCheckedUse(checkedSrc))
  3165. {
  3166. if(noImplicitCallUsesInstrRef)
  3167. {
  3168. *noImplicitCallUsesInstrRef = prevInstr;
  3169. }
  3170. return checkedSrc;
  3171. }
  3172. }
  3173. }
  3174. if(noImplicitCallUsesInstrRef)
  3175. {
  3176. *noImplicitCallUsesInstrRef = nullptr;
  3177. }
  3178. return nullptr;
  3179. }
  3180. void
  3181. BackwardPass::ProcessArrayRegOpndUse(IR::Instr *const instr, IR::ArrayRegOpnd *const arrayRegOpnd)
  3182. {
  3183. Assert(tag == Js::DeadStorePhase);
  3184. Assert(!IsCollectionPass());
  3185. Assert(instr);
  3186. Assert(arrayRegOpnd);
  3187. if(!(arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym() || arrayRegOpnd->LengthSym()))
  3188. {
  3189. return;
  3190. }
  3191. const ValueType arrayValueType(arrayRegOpnd->GetValueType());
  3192. const bool isJsArray = !arrayValueType.IsLikelyTypedArray();
  3193. Assert(isJsArray == arrayValueType.IsArrayOrObjectWithArray());
  3194. Assert(!isJsArray == arrayValueType.IsOptimizedTypedArray());
  3195. BasicBlock *const block = currentBlock;
  3196. if(!IsPrePass() &&
  3197. (arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym()) &&
  3198. (!isJsArray || instr->m_opcode != Js::OpCode::NoImplicitCallUses))
  3199. {
  3200. bool headSegmentIsLoadedButUnused =
  3201. instr->loadedArrayHeadSegment &&
  3202. arrayRegOpnd->HeadSegmentSym() &&
  3203. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentSym()->m_id);
  3204. const bool headSegmentLengthIsLoadedButUnused =
  3205. instr->loadedArrayHeadSegmentLength &&
  3206. arrayRegOpnd->HeadSegmentLengthSym() &&
  3207. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3208. if(headSegmentLengthIsLoadedButUnused && instr->extractedUpperBoundCheckWithoutHoisting)
  3209. {
  3210. // Find the upper bound check (index[src1] <= headSegmentLength[src2] + offset[dst])
  3211. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3212. Assert(upperBoundCheck && upperBoundCheck != instr);
  3213. Assert(upperBoundCheck->GetSrc2()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3214. // Find the head segment length load
  3215. IR::Instr *headSegmentLengthLoad = this->globOpt->FindArraySegmentLoadInstr(upperBoundCheck);
  3216. Assert(headSegmentLengthLoad->GetDst()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3217. Assert(
  3218. headSegmentLengthLoad->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym ==
  3219. (isJsArray ? arrayRegOpnd->HeadSegmentSym() : arrayRegOpnd->m_sym));
  3220. // Fold the head segment length load into the upper bound check. Keep the load instruction there with a Nop so that
  3221. // the head segment length sym can be marked as unused before the Nop. The lowerer will remove it.
  3222. upperBoundCheck->ReplaceSrc2(headSegmentLengthLoad->UnlinkSrc1());
  3223. headSegmentLengthLoad->m_opcode = Js::OpCode::Nop;
  3224. if(isJsArray)
  3225. {
  3226. // The head segment length is on the head segment, so the bound check now uses the head segment sym
  3227. headSegmentIsLoadedButUnused = false;
  3228. }
  3229. }
  3230. if(headSegmentIsLoadedButUnused || headSegmentLengthIsLoadedButUnused)
  3231. {
  3232. // Check if the head segment / head segment length are being loaded here. If so, remove them and let the fast
  3233. // path load them since it does a better job.
  3234. IR::ArrayRegOpnd *noImplicitCallArrayUse = nullptr;
  3235. if(isJsArray)
  3236. {
  3237. IR::Opnd *const use =
  3238. FindNoImplicitCallUse(
  3239. instr,
  3240. arrayRegOpnd,
  3241. [&](IR::Opnd *const checkedSrc) -> bool
  3242. {
  3243. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3244. if(!checkedSrcValueType.IsLikelyObject() ||
  3245. checkedSrcValueType.GetObjectType() != arrayValueType.GetObjectType())
  3246. {
  3247. return false;
  3248. }
  3249. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3250. if(!checkedRegSrc->IsArrayRegOpnd())
  3251. {
  3252. return false;
  3253. }
  3254. IR::ArrayRegOpnd *const checkedArraySrc = checkedRegSrc->AsArrayRegOpnd();
  3255. if(headSegmentIsLoadedButUnused &&
  3256. checkedArraySrc->HeadSegmentSym() != arrayRegOpnd->HeadSegmentSym())
  3257. {
  3258. return false;
  3259. }
  3260. if(headSegmentLengthIsLoadedButUnused &&
  3261. checkedArraySrc->HeadSegmentLengthSym() != arrayRegOpnd->HeadSegmentLengthSym())
  3262. {
  3263. return false;
  3264. }
  3265. return true;
  3266. });
  3267. if(use)
  3268. {
  3269. noImplicitCallArrayUse = use->AsRegOpnd()->AsArrayRegOpnd();
  3270. }
  3271. }
  3272. else if(headSegmentLengthIsLoadedButUnused)
  3273. {
  3274. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web
  3275. // worker, so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there
  3276. // are no forward uses of the head segment length sym, to allow removing the extracted head segment length
  3277. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3278. // removed.
  3279. IR::Instr *noImplicitCallUsesInstr;
  3280. IR::Opnd *const use =
  3281. FindNoImplicitCallUse(
  3282. instr,
  3283. arrayRegOpnd->HeadSegmentLengthSym(),
  3284. [&](IR::Opnd *const checkedSrc) -> bool
  3285. {
  3286. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3287. },
  3288. &noImplicitCallUsesInstr);
  3289. if(use)
  3290. {
  3291. Assert(noImplicitCallUsesInstr);
  3292. Assert(!noImplicitCallUsesInstr->GetDst());
  3293. Assert(noImplicitCallUsesInstr->GetSrc1());
  3294. if(use == noImplicitCallUsesInstr->GetSrc1())
  3295. {
  3296. if(noImplicitCallUsesInstr->GetSrc2())
  3297. {
  3298. noImplicitCallUsesInstr->ReplaceSrc1(noImplicitCallUsesInstr->UnlinkSrc2());
  3299. }
  3300. else
  3301. {
  3302. noImplicitCallUsesInstr->FreeSrc1();
  3303. noImplicitCallUsesInstr->m_opcode = Js::OpCode::Nop;
  3304. }
  3305. }
  3306. else
  3307. {
  3308. Assert(use == noImplicitCallUsesInstr->GetSrc2());
  3309. noImplicitCallUsesInstr->FreeSrc2();
  3310. }
  3311. }
  3312. }
  3313. if(headSegmentIsLoadedButUnused &&
  3314. (!isJsArray || !arrayRegOpnd->HeadSegmentLengthSym() || headSegmentLengthIsLoadedButUnused))
  3315. {
  3316. // For JS arrays, the head segment length load is dependent on the head segment. So, only remove the head
  3317. // segment load if the head segment length load can also be removed.
  3318. arrayRegOpnd->RemoveHeadSegmentSym();
  3319. instr->loadedArrayHeadSegment = false;
  3320. if(noImplicitCallArrayUse)
  3321. {
  3322. noImplicitCallArrayUse->RemoveHeadSegmentSym();
  3323. }
  3324. }
  3325. if(headSegmentLengthIsLoadedButUnused)
  3326. {
  3327. arrayRegOpnd->RemoveHeadSegmentLengthSym();
  3328. instr->loadedArrayHeadSegmentLength = false;
  3329. if(noImplicitCallArrayUse)
  3330. {
  3331. noImplicitCallArrayUse->RemoveHeadSegmentLengthSym();
  3332. }
  3333. }
  3334. }
  3335. }
  3336. if(isJsArray && instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3337. {
  3338. // Only uses in NoImplicitCallUses instructions are counted toward liveness
  3339. return;
  3340. }
  3341. // Treat dependent syms as uses. For JS arrays, only uses in NoImplicitCallUses count because only then the assumptions made
  3342. // on the dependent syms are guaranteed to be valid. Similarly for typed arrays, a head segment length sym use counts toward
  3343. // liveness only in a NoImplicitCallUses instruction.
  3344. if(arrayRegOpnd->HeadSegmentSym())
  3345. {
  3346. ProcessStackSymUse(arrayRegOpnd->HeadSegmentSym(), true);
  3347. if(isJsArray)
  3348. {
  3349. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3350. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3351. }
  3352. }
  3353. if(arrayRegOpnd->HeadSegmentLengthSym())
  3354. {
  3355. if(isJsArray)
  3356. {
  3357. ProcessStackSymUse(arrayRegOpnd->HeadSegmentLengthSym(), true);
  3358. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3359. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3360. }
  3361. else
  3362. {
  3363. // ProcessNoImplicitCallUses automatically marks JS array reg opnds and their corresponding syms as live. A typed
  3364. // array's head segment length sym also needs to be marked as live at its use in the NoImplicitCallUses instruction,
  3365. // but it is just in a reg opnd. Flag the opnd to have the sym be marked as live when that instruction is processed.
  3366. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  3367. IR::Opnd *const use =
  3368. FindNoImplicitCallUse(
  3369. instr,
  3370. arrayRegOpnd->HeadSegmentLengthSym(),
  3371. [&](IR::Opnd *const checkedSrc) -> bool
  3372. {
  3373. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3374. });
  3375. if(use)
  3376. {
  3377. considerSymAsRealUseInNoImplicitCallUses = arrayRegOpnd->HeadSegmentLengthSym();
  3378. }
  3379. }
  3380. }
  3381. StackSym *const lengthSym = arrayRegOpnd->LengthSym();
  3382. if(lengthSym && lengthSym != arrayRegOpnd->HeadSegmentLengthSym())
  3383. {
  3384. ProcessStackSymUse(lengthSym, true);
  3385. Assert(arrayValueType.IsArray());
  3386. block->noImplicitCallUses->Set(lengthSym->m_id);
  3387. block->noImplicitCallArrayLengthSymUses->Set(lengthSym->m_id);
  3388. }
  3389. }
  3390. void
  3391. BackwardPass::ProcessNewScObject(IR::Instr* instr)
  3392. {
  3393. if (this->tag != Js::DeadStorePhase || IsCollectionPass())
  3394. {
  3395. return;
  3396. }
  3397. if (!instr->IsNewScObjectInstr())
  3398. {
  3399. return;
  3400. }
  3401. if (instr->HasBailOutInfo())
  3402. {
  3403. Assert(instr->IsProfiledInstr());
  3404. Assert(instr->GetBailOutKind() == IR::BailOutFailedCtorGuardCheck);
  3405. Assert(instr->GetDst()->IsRegOpnd());
  3406. BasicBlock * block = this->currentBlock;
  3407. StackSym* objSym = instr->GetDst()->AsRegOpnd()->GetStackSym();
  3408. if (block->upwardExposedUses->Test(objSym->m_id))
  3409. {
  3410. // If the object created here is used downstream, let's capture any property operations we must protect.
  3411. Assert(instr->GetDst()->AsRegOpnd()->GetStackSym()->HasObjectTypeSym());
  3412. JITTimeConstructorCache* ctorCache = instr->m_func->GetConstructorCache(static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId));
  3413. if (block->stackSymToFinalType != nullptr)
  3414. {
  3415. // NewScObject is the origin of the object pointer. If we have a final type in hand, do the
  3416. // transition here.
  3417. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(objSym->m_id);
  3418. if (pBucket &&
  3419. pBucket->GetInitialType() != nullptr &&
  3420. pBucket->GetFinalType() != pBucket->GetInitialType())
  3421. {
  3422. Assert(pBucket->GetInitialType() == ctorCache->GetType());
  3423. if (!this->IsPrePass())
  3424. {
  3425. this->InsertTypeTransition(instr->m_next, objSym, pBucket);
  3426. }
  3427. #if DBG
  3428. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  3429. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  3430. {
  3431. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  3432. }
  3433. pBucket->SetInitialType(nullptr);
  3434. pBucket->SetFinalType(nullptr);
  3435. #else
  3436. block->stackSymToFinalType->Clear(objSym->m_id);
  3437. #endif
  3438. }
  3439. }
  3440. if (block->stackSymToGuardedProperties != nullptr)
  3441. {
  3442. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties->Get(objSym->m_id);
  3443. if (bucket != nullptr)
  3444. {
  3445. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  3446. if (guardedPropertyOps != nullptr)
  3447. {
  3448. ctorCache->EnsureGuardedPropOps(this->func->m_alloc);
  3449. ctorCache->AddGuardedPropOps(guardedPropertyOps);
  3450. bucket->SetGuardedPropertyOps(nullptr);
  3451. JitAdelete(this->tempAlloc, guardedPropertyOps);
  3452. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  3453. }
  3454. }
  3455. }
  3456. }
  3457. else
  3458. {
  3459. // If the object is not used downstream, let's remove the bailout and let the lowerer emit a fast path along with
  3460. // the fallback on helper, if the ctor cache ever became invalid.
  3461. instr->ClearBailOutInfo();
  3462. if (preOpBailOutInstrToProcess == instr)
  3463. {
  3464. preOpBailOutInstrToProcess = nullptr;
  3465. }
  3466. #if DBG
  3467. // We're creating a brand new object here, so no type check upstream could protect any properties of this
  3468. // object. Let's make sure we don't have any left to protect.
  3469. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties != nullptr ?
  3470. block->stackSymToGuardedProperties->Get(objSym->m_id) : nullptr;
  3471. Assert(bucket == nullptr || bucket->GetGuardedPropertyOps()->IsEmpty());
  3472. #endif
  3473. }
  3474. }
  3475. }
  3476. void
  3477. BackwardPass::UpdateArrayValueTypes(IR::Instr *const instr, IR::Opnd *origOpnd)
  3478. {
  3479. Assert(tag == Js::DeadStorePhase);
  3480. Assert(!IsPrePass());
  3481. Assert(instr);
  3482. if(!origOpnd)
  3483. {
  3484. return;
  3485. }
  3486. IR::Instr *opndOwnerInstr = instr;
  3487. switch(instr->m_opcode)
  3488. {
  3489. case Js::OpCode::StElemC:
  3490. case Js::OpCode::StArrSegElemC:
  3491. // These may not be fixed if we are unsure about the type of the array they're storing to
  3492. // (because it relies on profile data) and we weren't able to hoist the array check.
  3493. return;
  3494. }
  3495. Sym *sym;
  3496. IR::Opnd* opnd = origOpnd;
  3497. IR::ArrayRegOpnd *arrayOpnd;
  3498. switch(opnd->GetKind())
  3499. {
  3500. case IR::OpndKindIndir:
  3501. opnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  3502. // fall-through
  3503. case IR::OpndKindReg:
  3504. {
  3505. IR::RegOpnd *const regOpnd = opnd->AsRegOpnd();
  3506. sym = regOpnd->m_sym;
  3507. arrayOpnd = regOpnd->IsArrayRegOpnd() ? regOpnd->AsArrayRegOpnd() : nullptr;
  3508. break;
  3509. }
  3510. case IR::OpndKindSym:
  3511. sym = opnd->AsSymOpnd()->m_sym;
  3512. if(!sym->IsPropertySym())
  3513. {
  3514. return;
  3515. }
  3516. arrayOpnd = nullptr;
  3517. break;
  3518. default:
  3519. return;
  3520. }
  3521. const ValueType valueType(opnd->GetValueType());
  3522. if(!valueType.IsAnyOptimizedArray())
  3523. {
  3524. return;
  3525. }
  3526. const bool isJsArray = valueType.IsArrayOrObjectWithArray();
  3527. Assert(!isJsArray == valueType.IsOptimizedTypedArray());
  3528. const bool noForwardImplicitCallUses = currentBlock->noImplicitCallUses->IsEmpty();
  3529. bool changeArray = isJsArray && !opnd->IsValueTypeFixed() && noForwardImplicitCallUses;
  3530. bool changeNativeArray =
  3531. isJsArray &&
  3532. !opnd->IsValueTypeFixed() &&
  3533. !valueType.HasVarElements() &&
  3534. currentBlock->noImplicitCallNativeArrayUses->IsEmpty();
  3535. bool changeNoMissingValues =
  3536. isJsArray &&
  3537. !opnd->IsValueTypeFixed() &&
  3538. valueType.HasNoMissingValues() &&
  3539. currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty();
  3540. const bool noForwardJsArrayHeadSegmentSymUses = currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty();
  3541. bool removeHeadSegmentSym = isJsArray && arrayOpnd && arrayOpnd->HeadSegmentSym() && noForwardJsArrayHeadSegmentSymUses;
  3542. bool removeHeadSegmentLengthSym =
  3543. arrayOpnd &&
  3544. arrayOpnd->HeadSegmentLengthSym() &&
  3545. (isJsArray ? noForwardJsArrayHeadSegmentSymUses : noForwardImplicitCallUses);
  3546. Assert(!isJsArray || !arrayOpnd || !arrayOpnd->LengthSym() || valueType.IsArray());
  3547. bool removeLengthSym =
  3548. isJsArray &&
  3549. arrayOpnd &&
  3550. arrayOpnd->LengthSym() &&
  3551. currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty();
  3552. if(!(changeArray || changeNoMissingValues || changeNativeArray || removeHeadSegmentSym || removeHeadSegmentLengthSym))
  3553. {
  3554. return;
  3555. }
  3556. // We have a definitely-array value type for the base, but either implicit calls are not currently being disabled for
  3557. // legally using the value type as a definite array, or we are not currently bailing out upon creating a missing value
  3558. // for legally using the value type as a definite array with no missing values.
  3559. // For source opnds, ensure that a NoImplicitCallUses immediately precedes this instruction. Otherwise, convert the value
  3560. // type to an appropriate version so that the lowerer doesn't incorrectly treat it as it says.
  3561. if(opnd != opndOwnerInstr->GetDst())
  3562. {
  3563. if(isJsArray)
  3564. {
  3565. IR::Opnd *const checkedSrc =
  3566. FindNoImplicitCallUse(
  3567. instr,
  3568. opnd,
  3569. [&](IR::Opnd *const checkedSrc) -> bool
  3570. {
  3571. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3572. return
  3573. checkedSrcValueType.IsLikelyObject() &&
  3574. checkedSrcValueType.GetObjectType() == valueType.GetObjectType();
  3575. });
  3576. if(checkedSrc)
  3577. {
  3578. // Implicit calls will be disabled to the point immediately before this instruction
  3579. changeArray = false;
  3580. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3581. if(changeNativeArray &&
  3582. !checkedSrcValueType.HasVarElements() &&
  3583. checkedSrcValueType.HasIntElements() == valueType.HasIntElements())
  3584. {
  3585. // If necessary, instructions before this will bail out on converting a native array
  3586. changeNativeArray = false;
  3587. }
  3588. if(changeNoMissingValues && checkedSrcValueType.HasNoMissingValues())
  3589. {
  3590. // If necessary, instructions before this will bail out on creating a missing value
  3591. changeNoMissingValues = false;
  3592. }
  3593. if((removeHeadSegmentSym || removeHeadSegmentLengthSym || removeLengthSym) && checkedSrc->IsRegOpnd())
  3594. {
  3595. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3596. if(checkedRegSrc->IsArrayRegOpnd())
  3597. {
  3598. IR::ArrayRegOpnd *const checkedArraySrc = checkedSrc->AsRegOpnd()->AsArrayRegOpnd();
  3599. if(removeHeadSegmentSym && checkedArraySrc->HeadSegmentSym() == arrayOpnd->HeadSegmentSym())
  3600. {
  3601. // If necessary, instructions before this will bail out upon invalidating head segment sym
  3602. removeHeadSegmentSym = false;
  3603. }
  3604. if(removeHeadSegmentLengthSym &&
  3605. checkedArraySrc->HeadSegmentLengthSym() == arrayOpnd->HeadSegmentLengthSym())
  3606. {
  3607. // If necessary, instructions before this will bail out upon invalidating head segment length sym
  3608. removeHeadSegmentLengthSym = false;
  3609. }
  3610. if(removeLengthSym && checkedArraySrc->LengthSym() == arrayOpnd->LengthSym())
  3611. {
  3612. // If necessary, instructions before this will bail out upon invalidating a length sym
  3613. removeLengthSym = false;
  3614. }
  3615. }
  3616. }
  3617. }
  3618. }
  3619. else
  3620. {
  3621. Assert(removeHeadSegmentLengthSym);
  3622. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web worker,
  3623. // so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there are no forward
  3624. // uses of any head segment length syms, to allow removing the extracted head segment length
  3625. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3626. // removed.
  3627. IR::Opnd *const use =
  3628. FindNoImplicitCallUse(
  3629. instr,
  3630. arrayOpnd->HeadSegmentLengthSym(),
  3631. [&](IR::Opnd *const checkedSrc) -> bool
  3632. {
  3633. return checkedSrc->AsRegOpnd()->m_sym == arrayOpnd->HeadSegmentLengthSym();
  3634. });
  3635. if(use)
  3636. {
  3637. // Implicit calls will be disabled to the point immediately before this instruction
  3638. removeHeadSegmentLengthSym = false;
  3639. }
  3640. }
  3641. }
  3642. if(changeArray || changeNativeArray)
  3643. {
  3644. if(arrayOpnd)
  3645. {
  3646. opnd = arrayOpnd->CopyAsRegOpnd(opndOwnerInstr->m_func);
  3647. if (origOpnd->IsIndirOpnd())
  3648. {
  3649. origOpnd->AsIndirOpnd()->ReplaceBaseOpnd(opnd->AsRegOpnd());
  3650. }
  3651. else
  3652. {
  3653. opndOwnerInstr->Replace(arrayOpnd, opnd);
  3654. }
  3655. arrayOpnd = nullptr;
  3656. }
  3657. opnd->SetValueType(valueType.ToLikely());
  3658. }
  3659. else
  3660. {
  3661. if(changeNoMissingValues)
  3662. {
  3663. opnd->SetValueType(valueType.SetHasNoMissingValues(false));
  3664. }
  3665. if(removeHeadSegmentSym)
  3666. {
  3667. Assert(arrayOpnd);
  3668. arrayOpnd->RemoveHeadSegmentSym();
  3669. }
  3670. if(removeHeadSegmentLengthSym)
  3671. {
  3672. Assert(arrayOpnd);
  3673. arrayOpnd->RemoveHeadSegmentLengthSym();
  3674. }
  3675. if(removeLengthSym)
  3676. {
  3677. Assert(arrayOpnd);
  3678. arrayOpnd->RemoveLengthSym();
  3679. }
  3680. }
  3681. }
  3682. void
  3683. BackwardPass::UpdateArrayBailOutKind(IR::Instr *const instr)
  3684. {
  3685. Assert(!IsPrePass());
  3686. Assert(instr);
  3687. Assert(instr->HasBailOutInfo());
  3688. if ((instr->m_opcode != Js::OpCode::StElemI_A && instr->m_opcode != Js::OpCode::StElemI_A_Strict &&
  3689. instr->m_opcode != Js::OpCode::Memcopy && instr->m_opcode != Js::OpCode::Memset) ||
  3690. !instr->GetDst()->IsIndirOpnd())
  3691. {
  3692. return;
  3693. }
  3694. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  3695. const ValueType baseValueType(baseOpnd->GetValueType());
  3696. if(baseValueType.IsNotArrayOrObjectWithArray())
  3697. {
  3698. return;
  3699. }
  3700. IR::BailOutKind includeBailOutKinds = IR::BailOutInvalid;
  3701. if(!baseValueType.IsNotNativeArray() &&
  3702. (!baseValueType.IsLikelyNativeArray() || instr->GetSrc1()->IsVar()) &&
  3703. !currentBlock->noImplicitCallNativeArrayUses->IsEmpty())
  3704. {
  3705. // There is an upwards-exposed use of a native array. Since the array referenced by this instruction can be aliased,
  3706. // this instruction needs to bail out if it converts the native array even if this array specifically is not
  3707. // upwards-exposed.
  3708. includeBailOutKinds |= IR::BailOutConvertedNativeArray;
  3709. }
  3710. if(baseOpnd->IsArrayRegOpnd() && baseOpnd->AsArrayRegOpnd()->EliminatedUpperBoundCheck())
  3711. {
  3712. if(instr->extractedUpperBoundCheckWithoutHoisting && !currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3713. {
  3714. // See comment below regarding head segment invalidation. A failed upper bound check usually means that it will
  3715. // invalidate the head segment length, so change the bailout kind on the upper bound check to have it bail out for
  3716. // the right reason. Even though the store may actually occur in a non-head segment, which would not invalidate the
  3717. // head segment or length, any store outside the head segment bounds causes head segment load elimination to be
  3718. // turned off for the store, because the segment structure of the array is not guaranteed to be the same every time.
  3719. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3720. Assert(upperBoundCheck && upperBoundCheck != instr);
  3721. if(upperBoundCheck->GetBailOutKind() == IR::BailOutOnArrayAccessHelperCall)
  3722. {
  3723. upperBoundCheck->SetBailOutKind(IR::BailOutOnInvalidatedArrayHeadSegment);
  3724. }
  3725. else
  3726. {
  3727. Assert(upperBoundCheck->GetBailOutKind() == IR::BailOutOnFailedHoistedBoundCheck);
  3728. }
  3729. }
  3730. }
  3731. else
  3732. {
  3733. if(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3734. {
  3735. // There is an upwards-exposed use of a segment sym. Since the head segment syms referenced by this instruction can
  3736. // be aliased, this instruction needs to bail out if it changes the segment syms it references even if the ones it
  3737. // references specifically are not upwards-exposed. This bailout kind also guarantees that this element store will
  3738. // not create missing values.
  3739. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayHeadSegment;
  3740. }
  3741. else if(
  3742. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  3743. !(instr->GetBailOutKind() & IR::BailOutOnArrayAccessHelperCall))
  3744. {
  3745. // There is an upwards-exposed use of an array with no missing values. Since the array referenced by this
  3746. // instruction can be aliased, this instruction needs to bail out if it creates a missing value in the array even if
  3747. // this array specifically is not upwards-exposed.
  3748. includeBailOutKinds |= IR::BailOutOnMissingValue;
  3749. }
  3750. if(!baseValueType.IsNotArray() && !currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty())
  3751. {
  3752. // There is an upwards-exposed use of a length sym. Since the length sym referenced by this instruction can be
  3753. // aliased, this instruction needs to bail out if it changes the length sym it references even if the ones it
  3754. // references specifically are not upwards-exposed.
  3755. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayLength;
  3756. }
  3757. }
  3758. if(!includeBailOutKinds)
  3759. {
  3760. return;
  3761. }
  3762. Assert(!(includeBailOutKinds & ~IR::BailOutKindBits));
  3763. instr->SetBailOutKind(instr->GetBailOutKind() | includeBailOutKinds);
  3764. }
  3765. bool
  3766. BackwardPass::ProcessStackSymUse(StackSym * stackSym, BOOLEAN isNonByteCodeUse)
  3767. {
  3768. BasicBlock * block = this->currentBlock;
  3769. if (this->DoByteCodeUpwardExposedUsed())
  3770. {
  3771. if (!isNonByteCodeUse && stackSym->HasByteCodeRegSlot())
  3772. {
  3773. // Always track the sym use on the var sym.
  3774. StackSym * byteCodeUseSym = stackSym;
  3775. if (byteCodeUseSym->IsTypeSpec())
  3776. {
  3777. // It has to have a var version for byte code regs
  3778. byteCodeUseSym = byteCodeUseSym->GetVarEquivSym(nullptr);
  3779. }
  3780. block->byteCodeUpwardExposedUsed->Set(byteCodeUseSym->m_id);
  3781. #if DBG
  3782. // We can only track first level function stack syms right now
  3783. if (byteCodeUseSym->GetByteCodeFunc() == this->func)
  3784. {
  3785. Js::RegSlot byteCodeRegSlot = byteCodeUseSym->GetByteCodeRegSlot();
  3786. if (block->byteCodeRestoreSyms[byteCodeRegSlot] != byteCodeUseSym)
  3787. {
  3788. AssertMsg(block->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  3789. "Can't have two active lifetime for the same byte code register");
  3790. block->byteCodeRestoreSyms[byteCodeRegSlot] = byteCodeUseSym;
  3791. }
  3792. }
  3793. #endif
  3794. }
  3795. }
  3796. if(IsCollectionPass())
  3797. {
  3798. return true;
  3799. }
  3800. if (this->DoMarkTempObjects())
  3801. {
  3802. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  3803. block->tempObjectTracker->ProcessUse(stackSym, this);
  3804. }
  3805. #if DBG
  3806. if (this->DoMarkTempObjectVerify())
  3807. {
  3808. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  3809. block->tempObjectVerifyTracker->ProcessUse(stackSym, this);
  3810. }
  3811. #endif
  3812. return !!block->upwardExposedUses->TestAndSet(stackSym->m_id);
  3813. }
  3814. bool
  3815. BackwardPass::ProcessSymUse(Sym * sym, bool isRegOpndUse, BOOLEAN isNonByteCodeUse)
  3816. {
  3817. BasicBlock * block = this->currentBlock;
  3818. if (CanDeadStoreInstrForScopeObjRemoval(sym))
  3819. {
  3820. return false;
  3821. }
  3822. if (sym->IsPropertySym())
  3823. {
  3824. PropertySym * propertySym = sym->AsPropertySym();
  3825. ProcessStackSymUse(propertySym->m_stackSym, isNonByteCodeUse);
  3826. if(IsCollectionPass())
  3827. {
  3828. return true;
  3829. }
  3830. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  3831. if (block->fieldHoistCandidates && GlobOpt::TransferSrcValue(this->currentInstr))
  3832. {
  3833. // If the instruction doesn't transfer the src value to dst, it will not be copyprop'd
  3834. // So we can't hoist those.
  3835. block->fieldHoistCandidates->Set(propertySym->m_id);
  3836. }
  3837. if (this->DoDeadStoreSlots())
  3838. {
  3839. block->slotDeadStoreCandidates->Clear(propertySym->m_id);
  3840. }
  3841. if (tag == Js::BackwardPhase)
  3842. {
  3843. // Backward phase tracks liveness of fields to tell GlobOpt where we may need bailout.
  3844. return this->ProcessPropertySymUse(propertySym);
  3845. }
  3846. else
  3847. {
  3848. // Dead-store phase tracks copy propped syms, so it only cares about ByteCodeUses we inserted,
  3849. // not live fields.
  3850. return false;
  3851. }
  3852. }
  3853. StackSym * stackSym = sym->AsStackSym();
  3854. bool isUsed = ProcessStackSymUse(stackSym, isNonByteCodeUse);
  3855. if (!IsCollectionPass() && isRegOpndUse && this->DoMarkTempNumbers())
  3856. {
  3857. // Collect mark temp number information
  3858. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  3859. block->tempNumberTracker->ProcessUse(stackSym, this);
  3860. }
  3861. return isUsed;
  3862. }
  3863. bool
  3864. BackwardPass::MayPropertyBeWrittenTo(Js::PropertyId propertyId)
  3865. {
  3866. return this->func->anyPropertyMayBeWrittenTo ||
  3867. (this->func->propertiesWrittenTo != nullptr && this->func->propertiesWrittenTo->ContainsKey(propertyId));
  3868. }
  3869. void
  3870. BackwardPass::ProcessPropertySymOpndUse(IR::PropertySymOpnd * opnd)
  3871. {
  3872. // If this operand doesn't participate in the type check sequence it's a pass-through.
  3873. // We will not set any bits on the operand and we will ignore them when lowering.
  3874. if (!opnd->IsTypeCheckSeqCandidate())
  3875. {
  3876. return;
  3877. }
  3878. AssertMsg(opnd->HasObjectTypeSym(), "Optimized property sym operand without a type sym?");
  3879. SymID typeSymId = opnd->GetObjectTypeSym()->m_id;
  3880. BasicBlock * block = this->currentBlock;
  3881. if (this->tag == Js::BackwardPhase)
  3882. {
  3883. // In the backward phase, we have no availability info, and we're trying to see
  3884. // where there are live fields so we can decide where to put bailouts.
  3885. Assert(opnd->MayNeedTypeCheckProtection());
  3886. block->upwardExposedFields->Set(typeSymId);
  3887. TrackObjTypeSpecWriteGuards(opnd, block);
  3888. }
  3889. else
  3890. {
  3891. // In the dead-store phase, we're trying to see where the lowered code needs to make sure to check
  3892. // types for downstream load/stores. We're also setting up the upward-exposed uses at loop headers
  3893. // so register allocation will be correct.
  3894. Assert(opnd->MayNeedTypeCheckProtection());
  3895. const bool isStore = opnd == this->currentInstr->GetDst();
  3896. // Note that we don't touch upwardExposedUses here.
  3897. if (opnd->IsTypeAvailable())
  3898. {
  3899. opnd->SetTypeDead(!block->upwardExposedFields->TestAndSet(typeSymId));
  3900. if (opnd->IsTypeChecked() && opnd->IsObjectHeaderInlined())
  3901. {
  3902. // The object's type must not change in a way that changes the layout.
  3903. // If we see a StFld with a type check bailout between here and the type check that guards this
  3904. // property, we must not dead-store the StFld's type check bailout, even if that operand's type appears
  3905. // dead, because that object may alias this one.
  3906. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3907. if (bv == nullptr)
  3908. {
  3909. bv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  3910. block->typesNeedingKnownObjectLayout = bv;
  3911. }
  3912. bv->Set(typeSymId);
  3913. }
  3914. }
  3915. else
  3916. {
  3917. opnd->SetTypeDead(
  3918. !block->upwardExposedFields->TestAndClear(typeSymId) &&
  3919. (
  3920. // Don't set the type dead if this is a store that may change the layout in a way that invalidates
  3921. // optimized load/stores downstream. Leave it non-dead in that case so the type check bailout
  3922. // is preserved and so that Lower will generate the bailout properly.
  3923. !isStore ||
  3924. !block->typesNeedingKnownObjectLayout ||
  3925. block->typesNeedingKnownObjectLayout->IsEmpty()
  3926. )
  3927. );
  3928. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3929. if (bv != nullptr)
  3930. {
  3931. bv->Clear(typeSymId);
  3932. }
  3933. }
  3934. bool mayNeedTypeTransition = true;
  3935. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  3936. {
  3937. mayNeedTypeTransition = !isStore;
  3938. }
  3939. if (mayNeedTypeTransition &&
  3940. !this->IsPrePass() &&
  3941. !this->currentInstr->HasBailOutInfo() &&
  3942. (opnd->NeedsPrimaryTypeCheck() ||
  3943. opnd->NeedsLocalTypeCheck() ||
  3944. opnd->NeedsLoadFromProtoTypeCheck()))
  3945. {
  3946. // This is a "checked" opnd that nevertheless will have some kind of type check generated for it.
  3947. // (Typical case is a load from prototype with no upstream guard.)
  3948. // If the type check fails, we will call a helper, which will require that the type be correct here.
  3949. // Final type can't be pushed up past this point. Do whatever type transition is required.
  3950. if (block->stackSymToFinalType != nullptr)
  3951. {
  3952. StackSym *baseSym = opnd->GetObjectSym();
  3953. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(baseSym->m_id);
  3954. if (pBucket &&
  3955. pBucket->GetFinalType() != nullptr &&
  3956. pBucket->GetFinalType() != pBucket->GetInitialType())
  3957. {
  3958. this->InsertTypeTransition(this->currentInstr->m_next, baseSym, pBucket);
  3959. pBucket->SetFinalType(pBucket->GetInitialType());
  3960. }
  3961. }
  3962. }
  3963. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  3964. {
  3965. // Do this after the above code, as the value of the final type may change there.
  3966. TrackAddPropertyTypes(opnd, block);
  3967. }
  3968. TrackObjTypeSpecProperties(opnd, block);
  3969. TrackObjTypeSpecWriteGuards(opnd, block);
  3970. }
  3971. }
  3972. void
  3973. BackwardPass::TrackObjTypeSpecProperties(IR::PropertySymOpnd *opnd, BasicBlock *block)
  3974. {
  3975. Assert(tag == Js::DeadStorePhase);
  3976. Assert(opnd->IsTypeCheckSeqCandidate());
  3977. // Now that we're in the dead store pass and we know definitively which operations will have a type
  3978. // check and which are protected by an upstream type check, we can push the lists of guarded properties
  3979. // up the flow graph and drop them on the type checks for the corresponding object symbol.
  3980. if (opnd->IsTypeCheckSeqParticipant())
  3981. {
  3982. // Add this operation to the list of guarded operations for this object symbol.
  3983. HashTable<ObjTypeGuardBucket>* stackSymToGuardedProperties = block->stackSymToGuardedProperties;
  3984. if (stackSymToGuardedProperties == nullptr)
  3985. {
  3986. stackSymToGuardedProperties = HashTable<ObjTypeGuardBucket>::New(this->tempAlloc, 8);
  3987. block->stackSymToGuardedProperties = stackSymToGuardedProperties;
  3988. }
  3989. StackSym* objSym = opnd->GetObjectSym();
  3990. ObjTypeGuardBucket* bucket = stackSymToGuardedProperties->FindOrInsertNew(objSym->m_id);
  3991. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  3992. if (guardedPropertyOps == nullptr)
  3993. {
  3994. // The bit vectors we push around the flow graph only need to live as long as this phase.
  3995. guardedPropertyOps = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  3996. bucket->SetGuardedPropertyOps(guardedPropertyOps);
  3997. }
  3998. #if DBG
  3999. FOREACH_BITSET_IN_SPARSEBV(propOpId, guardedPropertyOps)
  4000. {
  4001. JITObjTypeSpecFldInfo* existingFldInfo = this->func->GetGlobalObjTypeSpecFldInfo(propOpId);
  4002. Assert(existingFldInfo != nullptr);
  4003. if (existingFldInfo->GetPropertyId() != opnd->GetPropertyId())
  4004. {
  4005. continue;
  4006. }
  4007. // It would be very nice to assert that the info we have for this property matches all properties guarded thus far.
  4008. // Unfortunately, in some cases of object pointer copy propagation into a loop, we may end up with conflicting
  4009. // information for the same property. We simply ignore the conflict and emit an equivalent type check, which
  4010. // will attempt to check for one property on two different slots, and obviously fail. Thus we may have a
  4011. // guaranteed bailout, but we'll simply re-JIT with equivalent object type spec disabled. To avoid this
  4012. // issue altogether, we would need to track the set of guarded properties along with the type value in the
  4013. // forward pass, and when a conflict is detected either not optimize the offending instruction, or correct
  4014. // its information based on the info from the property in the type value info.
  4015. //Assert(!existingFldInfo->IsPoly() || !opnd->IsPoly() || GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()));
  4016. //Assert(existingFldInfo->GetSlotIndex() == opnd->GetSlotIndex());
  4017. if (PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func) && !JITManager::GetJITManager()->IsJITServer())
  4018. {
  4019. if (existingFldInfo->IsPoly() && opnd->IsPoly() &&
  4020. (!GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()) ||
  4021. (existingFldInfo->GetSlotIndex() != opnd->GetSlotIndex())))
  4022. {
  4023. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4024. Output::Print(_u("EquivObjTypeSpec: top function %s (%s): duplicate property clash on %s(#%d) on operation %u \n"),
  4025. this->func->GetJITFunctionBody()->GetDisplayName(), this->func->GetDebugNumberSet(debugStringBuffer),
  4026. this->func->GetInProcThreadContext()->GetPropertyRecord(opnd->GetPropertyId())->GetBuffer(), opnd->GetPropertyId(), opnd->GetObjTypeSpecFldId());
  4027. Output::Flush();
  4028. }
  4029. }
  4030. }
  4031. NEXT_BITSET_IN_SPARSEBV
  4032. #endif
  4033. bucket->AddToGuardedPropertyOps(opnd->GetObjTypeSpecFldId());
  4034. if (opnd->NeedsMonoCheck())
  4035. {
  4036. Assert(opnd->IsMono());
  4037. JITTypeHolder monoGuardType = opnd->IsInitialTypeChecked() ? opnd->GetInitialType() : opnd->GetType();
  4038. bucket->SetMonoGuardType(monoGuardType);
  4039. }
  4040. if (opnd->NeedsPrimaryTypeCheck())
  4041. {
  4042. // Grab the guarded properties which match this type check with respect to polymorphism and drop them
  4043. // on the operand. Only equivalent type checks can protect polymorphic properties to avoid a case where
  4044. // we have 1) a cache with type set {t1, t2} and property a, followed by 2) a cache with type t3 and
  4045. // property b, and 3) a cache with type set {t1, t2} and property c, where the slot index of property c
  4046. // on t1 and t2 is different than on t3. If cache 2 were to protect property c it would not verify that
  4047. // it resides on the correct slot for cache 3. Yes, an equivalent type check could protect monomorphic
  4048. // properties, but it would then unnecessarily verify their equivalence on the slow path.
  4049. // Also, make sure the guarded properties on the operand are allocated from the func's allocator to
  4050. // persists until lowering.
  4051. Assert(guardedPropertyOps != nullptr);
  4052. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4053. opnd->AddGuardedPropOps(guardedPropertyOps);
  4054. if (this->currentInstr->HasTypeCheckBailOut())
  4055. {
  4056. // Stop pushing the mono guard type up if it is being checked here.
  4057. if (bucket->NeedsMonoCheck())
  4058. {
  4059. if (this->currentInstr->HasEquivalentTypeCheckBailOut())
  4060. {
  4061. // Some instr protected by this one requires a monomorphic type check. (E.g., final type opt,
  4062. // fixed field not loaded from prototype.) Note the IsTypeAvailable test above: only do this at
  4063. // the initial type check that protects this path.
  4064. opnd->SetMonoGuardType(bucket->GetMonoGuardType());
  4065. this->currentInstr->ChangeEquivalentToMonoTypeCheckBailOut();
  4066. }
  4067. bucket->SetMonoGuardType(nullptr);
  4068. }
  4069. if (!opnd->IsTypeAvailable())
  4070. {
  4071. // Stop tracking the guarded properties if there's not another type check upstream.
  4072. bucket->SetGuardedPropertyOps(nullptr);
  4073. JitAdelete(this->tempAlloc, guardedPropertyOps);
  4074. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  4075. }
  4076. }
  4077. #if DBG
  4078. {
  4079. // If there is no upstream type check that is live and could protect guarded properties, we better
  4080. // not have any properties remaining.
  4081. ObjTypeGuardBucket* objTypeGuardBucket = block->stackSymToGuardedProperties->Get(opnd->GetObjectSym()->m_id);
  4082. Assert(opnd->IsTypeAvailable() || objTypeGuardBucket == nullptr || objTypeGuardBucket->GetGuardedPropertyOps()->IsEmpty());
  4083. }
  4084. #endif
  4085. }
  4086. }
  4087. else if (opnd->NeedsLocalTypeCheck())
  4088. {
  4089. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4090. opnd->SetGuardedPropOp(opnd->GetObjTypeSpecFldId());
  4091. }
  4092. }
  4093. void
  4094. BackwardPass::TrackObjTypeSpecWriteGuards(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4095. {
  4096. // TODO (ObjTypeSpec): Move write guard tracking to the forward pass, by recording on the type value
  4097. // which property IDs have been written since the last type check. This will result in more accurate
  4098. // tracking in cases when object pointer copy prop kicks in.
  4099. if (this->tag == Js::BackwardPhase)
  4100. {
  4101. // If this operation may need a write guard (load from proto or fixed field check) then add its
  4102. // write guard symbol to the map for this object. If it remains live (hasn't been written to)
  4103. // until the type check upstream, it will get recorded there so that the type check can be registered
  4104. // for invalidation on this property used in this operation.
  4105. // (ObjTypeSpec): Consider supporting polymorphic write guards as well. We can't currently distinguish between mono and
  4106. // poly write guards, and a type check can only protect operations matching with respect to polymorphism (see
  4107. // BackwardPass::TrackObjTypeSpecProperties for details), so for now we only target monomorphic operations.
  4108. if (opnd->IsMono() && opnd->MayNeedWriteGuardProtection())
  4109. {
  4110. if (block->stackSymToWriteGuardsMap == nullptr)
  4111. {
  4112. block->stackSymToWriteGuardsMap = HashTable<ObjWriteGuardBucket>::New(this->tempAlloc, 8);
  4113. }
  4114. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->FindOrInsertNew(opnd->GetObjectSym()->m_id);
  4115. BVSparse<JitArenaAllocator>* writeGuards = bucket->GetWriteGuards();
  4116. if (writeGuards == nullptr)
  4117. {
  4118. // The bit vectors we push around the flow graph only need to live as long as this phase.
  4119. writeGuards = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  4120. bucket->SetWriteGuards(writeGuards);
  4121. }
  4122. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4123. Assert(propertySym->m_writeGuardSym != nullptr);
  4124. SymID writeGuardSymId = propertySym->m_writeGuardSym->m_id;
  4125. writeGuards->Set(writeGuardSymId);
  4126. }
  4127. // Record any live (upward exposed) write guards on this operation, if this operation may end up with
  4128. // a type check. If we ultimately don't need a type check here, we will simply ignore the guards, because
  4129. // an earlier type check will protect them.
  4130. if (!IsPrePass() && opnd->IsMono() && !opnd->IsTypeDead())
  4131. {
  4132. Assert(opnd->GetWriteGuards() == nullptr);
  4133. if (block->stackSymToWriteGuardsMap != nullptr)
  4134. {
  4135. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->Get(opnd->GetObjectSym()->m_id);
  4136. if (bucket != nullptr)
  4137. {
  4138. // Get all the write guards associated with this object sym and filter them down to those that
  4139. // are upward exposed. If we end up emitting a type check for this instruction, we will create
  4140. // a type property guard registered for all guarded proto properties and we will set the write
  4141. // guard syms live during forward pass, such that we can avoid unnecessary write guard type
  4142. // checks and bailouts on every proto property (as long as it hasn't been written to since the
  4143. // primary type check).
  4144. auto writeGuards = bucket->GetWriteGuards()->CopyNew(this->func->m_alloc);
  4145. writeGuards->And(block->upwardExposedFields);
  4146. opnd->SetWriteGuards(writeGuards);
  4147. }
  4148. }
  4149. }
  4150. }
  4151. else
  4152. {
  4153. // If we know this property has never been written to in this function (either on this object or any
  4154. // of its aliases) we don't need the local type check.
  4155. if (opnd->MayNeedWriteGuardProtection() && !opnd->IsWriteGuardChecked() && !MayPropertyBeWrittenTo(opnd->GetPropertyId()))
  4156. {
  4157. opnd->SetWriteGuardChecked(true);
  4158. }
  4159. // If we don't need a primary type check here let's clear the write guards. The primary type check upstream will
  4160. // register the type check for the corresponding properties.
  4161. if (!IsPrePass() && !opnd->NeedsPrimaryTypeCheck())
  4162. {
  4163. opnd->ClearWriteGuards();
  4164. }
  4165. }
  4166. }
  4167. void
  4168. BackwardPass::TrackAddPropertyTypes(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4169. {
  4170. // Do the work of objtypespec add-property opt even if it's disabled by PHASE option, so that we have
  4171. // the dataflow info that can be inspected.
  4172. Assert(this->tag == Js::DeadStorePhase);
  4173. Assert(opnd->IsMono() || opnd->HasEquivalentTypeSet());
  4174. JITTypeHolder typeWithProperty = opnd->IsMono() ? opnd->GetType() : opnd->GetFirstEquivalentType();
  4175. JITTypeHolder typeWithoutProperty = opnd->HasInitialType() ? opnd->GetInitialType() : JITTypeHolder(nullptr);
  4176. if (typeWithoutProperty == nullptr ||
  4177. typeWithProperty == typeWithoutProperty ||
  4178. (opnd->IsTypeChecked() && !opnd->IsInitialTypeChecked()))
  4179. {
  4180. if (!this->IsPrePass() && block->stackSymToFinalType != nullptr && !this->currentInstr->HasBailOutInfo())
  4181. {
  4182. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4183. AddPropertyCacheBucket *pBucket =
  4184. block->stackSymToFinalType->Get(propertySym->m_stackSym->m_id);
  4185. if (pBucket && pBucket->GetFinalType() != nullptr && pBucket->GetInitialType() != pBucket->GetFinalType())
  4186. {
  4187. opnd->SetFinalType(pBucket->GetFinalType());
  4188. }
  4189. }
  4190. return;
  4191. }
  4192. #if DBG
  4193. Assert(typeWithProperty != nullptr);
  4194. const JITTypeHandler * typeWithoutPropertyTypeHandler = typeWithoutProperty->GetTypeHandler();
  4195. const JITTypeHandler * typeWithPropertyTypeHandler = typeWithProperty->GetTypeHandler();
  4196. // TODO: OOP JIT, reenable assert
  4197. //Assert(typeWithoutPropertyTypeHandler->GetPropertyCount() + 1 == typeWithPropertyTypeHandler->GetPropertyCount());
  4198. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(typeWithoutPropertyTypeHandler, typeWithPropertyTypeHandler),
  4199. "TypeHandlers are not compatible for transition?");
  4200. Assert(typeWithoutPropertyTypeHandler->GetSlotCapacity() <= typeWithPropertyTypeHandler->GetSlotCapacity());
  4201. #endif
  4202. // If there's already a final type for this instance, record it on the operand.
  4203. // If not, start tracking it.
  4204. if (block->stackSymToFinalType == nullptr)
  4205. {
  4206. block->stackSymToFinalType = HashTable<AddPropertyCacheBucket>::New(this->tempAlloc, 8);
  4207. }
  4208. // Find or create the type-tracking record for this instance in this block.
  4209. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4210. AddPropertyCacheBucket *pBucket =
  4211. block->stackSymToFinalType->FindOrInsertNew(propertySym->m_stackSym->m_id);
  4212. JITTypeHolder finalType(nullptr);
  4213. #if DBG
  4214. JITTypeHolder deadStoreUnavailableFinalType(nullptr);
  4215. #endif
  4216. if (pBucket->GetInitialType() == nullptr || opnd->GetType() != pBucket->GetInitialType())
  4217. {
  4218. #if DBG
  4219. if (opnd->GetType() == pBucket->deadStoreUnavailableInitialType)
  4220. {
  4221. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4222. }
  4223. #endif
  4224. // No info found, or the info was bad, so initialize it from this cache.
  4225. finalType = opnd->GetType();
  4226. pBucket->SetFinalType(finalType);
  4227. }
  4228. else
  4229. {
  4230. // Match: The type we push upward is now the typeWithoutProperty at this point,
  4231. // and the final type is the one we've been tracking.
  4232. finalType = pBucket->GetFinalType();
  4233. #if DBG
  4234. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4235. #endif
  4236. }
  4237. pBucket->SetInitialType(typeWithoutProperty);
  4238. if (!PHASE_OFF(Js::ObjTypeSpecStorePhase, this->func))
  4239. {
  4240. #if DBG
  4241. // We may regress in this case:
  4242. // if (b)
  4243. // t1 = {};
  4244. // o = t1;
  4245. // o.x =
  4246. // else
  4247. // t2 = {};
  4248. // o = t2;
  4249. // o.x =
  4250. // o.y =
  4251. //
  4252. // Where the backward pass will propagate the final type in o.y to o.x, then globopt will copy prop t1 and t2 to o.x.
  4253. // But not o.y (because of the merge). Then, in the dead store pass, o.y's final type will not propagate to t1.x and t2.x
  4254. // respectively, thus regression the final type. However, in both cases, the types of t1 and t2 are dead anyways.
  4255. //
  4256. // if the type is dead, we don't care if we have regressed the type, as no one is depending on it to skip type check anyways
  4257. if (!opnd->IsTypeDead())
  4258. {
  4259. // This is the type that would have been propagated if we didn't kill it because the type isn't available
  4260. JITTypeHolder checkFinalType = deadStoreUnavailableFinalType != nullptr ? deadStoreUnavailableFinalType : finalType;
  4261. if (opnd->HasFinalType() && opnd->GetFinalType() != checkFinalType)
  4262. {
  4263. // Final type discovery must be progressively better (unless we kill it in the deadstore pass
  4264. // when the type is not available during the forward pass)
  4265. const JITTypeHandler * oldFinalTypeHandler = opnd->GetFinalType()->GetTypeHandler();
  4266. const JITTypeHandler * checkFinalTypeHandler = checkFinalType->GetTypeHandler();
  4267. // TODO: OOP JIT, enable assert
  4268. //Assert(oldFinalTypeHandler->GetPropertyCount() < checkFinalTypeHandler->GetPropertyCount());
  4269. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(oldFinalTypeHandler, checkFinalTypeHandler),
  4270. "TypeHandlers should be compatible for transition.");
  4271. Assert(oldFinalTypeHandler->GetSlotCapacity() <= checkFinalTypeHandler->GetSlotCapacity());
  4272. }
  4273. }
  4274. #endif
  4275. Assert(opnd->IsBeingAdded());
  4276. if (!this->IsPrePass())
  4277. {
  4278. opnd->SetFinalType(finalType);
  4279. }
  4280. if (!opnd->IsTypeChecked())
  4281. {
  4282. // Transition from initial to final type will only happen at type check points.
  4283. if (opnd->IsTypeAvailable())
  4284. {
  4285. pBucket->SetFinalType(pBucket->GetInitialType());
  4286. }
  4287. }
  4288. }
  4289. #if DBG_DUMP
  4290. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  4291. {
  4292. Output::Print(_u("ObjTypeSpecStore: "));
  4293. this->currentInstr->Dump();
  4294. pBucket->Dump();
  4295. }
  4296. #endif
  4297. // In the dead-store pass, we have forward information that tells us whether a "final type"
  4298. // reached this point from an earlier store. If it didn't (i.e., it's not available here),
  4299. // remove it from the backward map so that upstream stores will use the final type that is
  4300. // live there. (This avoids unnecessary bailouts in cases where the final type is only live
  4301. // on one branch of an "if", a case that the initial backward pass can't detect.)
  4302. // An example:
  4303. // if (cond)
  4304. // o.x =
  4305. // o.y =
  4306. if (!opnd->IsTypeAvailable())
  4307. {
  4308. #if DBG
  4309. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  4310. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  4311. {
  4312. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  4313. }
  4314. pBucket->SetInitialType(nullptr);
  4315. pBucket->SetFinalType(nullptr);
  4316. #else
  4317. block->stackSymToFinalType->Clear(propertySym->m_stackSym->m_id);
  4318. #endif
  4319. }
  4320. }
  4321. void
  4322. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, int symId, AddPropertyCacheBucket *data)
  4323. {
  4324. StackSym *objSym = this->func->m_symTable->FindStackSym(symId);
  4325. Assert(objSym);
  4326. this->InsertTypeTransition(instrInsertBefore, objSym, data);
  4327. }
  4328. void
  4329. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, StackSym *objSym, AddPropertyCacheBucket *data)
  4330. {
  4331. IR::RegOpnd *baseOpnd = IR::RegOpnd::New(objSym, TyMachReg, this->func);
  4332. baseOpnd->SetIsJITOptimizedReg(true);
  4333. IR::AddrOpnd *initialTypeOpnd =
  4334. IR::AddrOpnd::New(data->GetInitialType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4335. initialTypeOpnd->m_metadata = data->GetInitialType().t;
  4336. IR::AddrOpnd *finalTypeOpnd =
  4337. IR::AddrOpnd::New(data->GetFinalType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4338. finalTypeOpnd->m_metadata = data->GetFinalType().t;
  4339. IR::Instr *adjustTypeInstr =
  4340. IR::Instr::New(Js::OpCode::AdjustObjType, finalTypeOpnd, baseOpnd, initialTypeOpnd, this->func);
  4341. instrInsertBefore->InsertBefore(adjustTypeInstr);
  4342. }
  4343. void
  4344. BackwardPass::InsertTypeTransitionAfterInstr(IR::Instr *instr, int symId, AddPropertyCacheBucket *data)
  4345. {
  4346. if (!this->IsPrePass())
  4347. {
  4348. // Transition to the final type if we don't bail out.
  4349. if (instr->EndsBasicBlock())
  4350. {
  4351. // The instr with the bailout is something like a branch that may not fall through.
  4352. // Insert the transitions instead at the beginning of each successor block.
  4353. this->InsertTypeTransitionsAtPriorSuccessors(this->currentBlock, nullptr, symId, data);
  4354. }
  4355. else
  4356. {
  4357. this->InsertTypeTransition(instr->m_next, symId, data);
  4358. }
  4359. }
  4360. // Note: we could probably clear this entry out of the table, but I don't know
  4361. // whether it's worth it, because it's likely coming right back.
  4362. data->SetFinalType(data->GetInitialType());
  4363. }
  4364. void
  4365. BackwardPass::InsertTypeTransitionAtBlock(BasicBlock *block, int symId, AddPropertyCacheBucket *data)
  4366. {
  4367. bool inserted = false;
  4368. FOREACH_INSTR_IN_BLOCK(instr, block)
  4369. {
  4370. if (instr->IsRealInstr())
  4371. {
  4372. // Check for pre-existing type transition. There may be more than one AdjustObjType here,
  4373. // so look at them all.
  4374. if (instr->m_opcode == Js::OpCode::AdjustObjType)
  4375. {
  4376. if (instr->GetSrc1()->AsRegOpnd()->m_sym->m_id == (SymID)symId)
  4377. {
  4378. // This symbol already has a type transition at this point.
  4379. // It *must* be doing the same transition we're already trying to do.
  4380. Assert((intptr_t)instr->GetDst()->AsAddrOpnd()->m_address == data->GetFinalType()->GetAddr() &&
  4381. (intptr_t)instr->GetSrc2()->AsAddrOpnd()->m_address == data->GetInitialType()->GetAddr());
  4382. // Nothing to do.
  4383. return;
  4384. }
  4385. }
  4386. else
  4387. {
  4388. this->InsertTypeTransition(instr, symId, data);
  4389. inserted = true;
  4390. break;
  4391. }
  4392. }
  4393. }
  4394. NEXT_INSTR_IN_BLOCK;
  4395. if (!inserted)
  4396. {
  4397. Assert(block->GetLastInstr()->m_next);
  4398. this->InsertTypeTransition(block->GetLastInstr()->m_next, symId, data);
  4399. }
  4400. }
  4401. void
  4402. BackwardPass::InsertTypeTransitionsAtPriorSuccessors(
  4403. BasicBlock *block,
  4404. BasicBlock *blockSucc,
  4405. int symId,
  4406. AddPropertyCacheBucket *data)
  4407. {
  4408. // For each successor of block prior to blockSucc, adjust the type.
  4409. FOREACH_SUCCESSOR_BLOCK(blockFix, block)
  4410. {
  4411. if (blockFix == blockSucc)
  4412. {
  4413. return;
  4414. }
  4415. this->InsertTypeTransitionAtBlock(blockFix, symId, data);
  4416. }
  4417. NEXT_SUCCESSOR_BLOCK;
  4418. }
  4419. void
  4420. BackwardPass::InsertTypeTransitionsAtPotentialKills()
  4421. {
  4422. // Final types can't be pushed up past certain instructions.
  4423. IR::Instr *instr = this->currentInstr;
  4424. if (instr->HasBailOutInfo() || instr->m_opcode == Js::OpCode::UpdateNewScObjectCache)
  4425. {
  4426. // Final types can't be pushed up past a bailout point.
  4427. // Insert any transitions called for by the current state of add-property buckets.
  4428. // Also do this for ctor cache updates, to avoid putting a type in the ctor cache that extends past
  4429. // the end of the ctor that the cache covers.
  4430. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4431. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4432. return false;
  4433. });
  4434. }
  4435. else
  4436. {
  4437. // If this is a load/store that expects an object-header-inlined type, don't push another sym's transition from
  4438. // object-header-inlined to non-object-header-inlined type past it, because the two syms may be aliases.
  4439. IR::PropertySymOpnd *propertySymOpnd = instr->GetPropertySymOpnd();
  4440. if (propertySymOpnd && propertySymOpnd->IsObjectHeaderInlined())
  4441. {
  4442. SymID opndId = propertySymOpnd->m_sym->AsPropertySym()->m_stackSym->m_id;
  4443. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4444. if ((SymID)symId == opndId)
  4445. {
  4446. // This is the sym we're tracking. No aliasing to worry about.
  4447. return false;
  4448. }
  4449. if (propertySymOpnd->IsMono() && data->GetInitialType() != propertySymOpnd->GetType())
  4450. {
  4451. // Type mismatch in a monomorphic case -- no aliasing.
  4452. return false;
  4453. }
  4454. if (this->TransitionUndoesObjectHeaderInlining(data))
  4455. {
  4456. // We're transitioning from inlined to non-inlined, so we can't push it up any farther.
  4457. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4458. }
  4459. return false;
  4460. });
  4461. }
  4462. }
  4463. }
  4464. template<class Fn>
  4465. void
  4466. BackwardPass::ForEachAddPropertyCacheBucket(Fn fn)
  4467. {
  4468. BasicBlock *block = this->currentBlock;
  4469. if (block->stackSymToFinalType == nullptr)
  4470. {
  4471. return;
  4472. }
  4473. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, block->stackSymToFinalType)
  4474. {
  4475. AddPropertyCacheBucket *data = &bucket.element;
  4476. if (data->GetInitialType() != nullptr &&
  4477. data->GetInitialType() != data->GetFinalType())
  4478. {
  4479. bool done = fn(bucket.value, data);
  4480. if (done)
  4481. {
  4482. break;
  4483. }
  4484. }
  4485. }
  4486. NEXT_HASHTABLE_ENTRY;
  4487. }
  4488. bool
  4489. BackwardPass::TransitionUndoesObjectHeaderInlining(AddPropertyCacheBucket *data) const
  4490. {
  4491. JITTypeHolder type = data->GetInitialType();
  4492. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4493. {
  4494. return false;
  4495. }
  4496. if (!type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler())
  4497. {
  4498. return false;
  4499. }
  4500. type = data->GetFinalType();
  4501. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4502. {
  4503. return false;
  4504. }
  4505. return !type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler();
  4506. }
  4507. void
  4508. BackwardPass::CollectCloneStrCandidate(IR::Opnd * opnd)
  4509. {
  4510. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4511. Assert(regOpnd != nullptr);
  4512. StackSym *sym = regOpnd->m_sym;
  4513. if (tag == Js::BackwardPhase
  4514. && currentInstr->m_opcode == Js::OpCode::Add_A
  4515. && currentInstr->GetSrc1() == opnd
  4516. && !this->IsPrePass()
  4517. && !this->IsCollectionPass()
  4518. && this->currentBlock->loop)
  4519. {
  4520. Assert(currentBlock->cloneStrCandidates != nullptr);
  4521. currentBlock->cloneStrCandidates->Set(sym->m_id);
  4522. }
  4523. }
  4524. void
  4525. BackwardPass::InvalidateCloneStrCandidate(IR::Opnd * opnd)
  4526. {
  4527. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4528. Assert(regOpnd != nullptr);
  4529. StackSym *sym = regOpnd->m_sym;
  4530. if (tag == Js::BackwardPhase &&
  4531. (currentInstr->m_opcode != Js::OpCode::Add_A || currentInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id != sym->m_id) &&
  4532. !this->IsPrePass() &&
  4533. !this->IsCollectionPass() &&
  4534. this->currentBlock->loop)
  4535. {
  4536. currentBlock->cloneStrCandidates->Clear(sym->m_id);
  4537. }
  4538. }
  4539. void
  4540. BackwardPass::ProcessUse(IR::Opnd * opnd)
  4541. {
  4542. switch (opnd->GetKind())
  4543. {
  4544. case IR::OpndKindReg:
  4545. {
  4546. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4547. StackSym *sym = regOpnd->m_sym;
  4548. if (!IsCollectionPass())
  4549. {
  4550. // isTempLastUse is only used for string concat right now, so lets not mark it if it's not a string.
  4551. // If it's upward exposed, it is not it's last use.
  4552. if (regOpnd->m_isTempLastUse && (regOpnd->GetValueType().IsNotString() || this->currentBlock->upwardExposedUses->Test(sym->m_id) || sym->m_mayNotBeTempLastUse))
  4553. {
  4554. regOpnd->m_isTempLastUse = false;
  4555. }
  4556. this->CollectCloneStrCandidate(opnd);
  4557. }
  4558. this->DoSetDead(regOpnd, !this->ProcessSymUse(sym, true, regOpnd->GetIsJITOptimizedReg()));
  4559. if (IsCollectionPass())
  4560. {
  4561. break;
  4562. }
  4563. if (tag == Js::DeadStorePhase && regOpnd->IsArrayRegOpnd())
  4564. {
  4565. ProcessArrayRegOpndUse(currentInstr, regOpnd->AsArrayRegOpnd());
  4566. }
  4567. if (currentInstr->m_opcode == Js::OpCode::BailOnNotArray)
  4568. {
  4569. Assert(tag == Js::DeadStorePhase);
  4570. const ValueType valueType(regOpnd->GetValueType());
  4571. if(valueType.IsLikelyArrayOrObjectWithArray())
  4572. {
  4573. currentBlock->noImplicitCallUses->Clear(sym->m_id);
  4574. // We are being conservative here to always check for missing value
  4575. // if any of them expect no missing value. That is because we don't know
  4576. // what set of sym is equivalent (copied) from the one we are testing for right now.
  4577. if(valueType.HasNoMissingValues() &&
  4578. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  4579. !IsPrePass())
  4580. {
  4581. // There is a use of this sym that requires this array to have no missing values, so this instruction
  4582. // needs to bail out if the array has missing values.
  4583. Assert(currentInstr->GetBailOutKind() == IR::BailOutOnNotArray ||
  4584. currentInstr->GetBailOutKind() == IR::BailOutOnNotNativeArray);
  4585. currentInstr->SetBailOutKind(currentInstr->GetBailOutKind() | IR::BailOutOnMissingValue);
  4586. }
  4587. currentBlock->noImplicitCallNoMissingValuesUses->Clear(sym->m_id);
  4588. currentBlock->noImplicitCallNativeArrayUses->Clear(sym->m_id);
  4589. }
  4590. }
  4591. }
  4592. break;
  4593. case IR::OpndKindSym:
  4594. {
  4595. IR::SymOpnd *symOpnd = opnd->AsSymOpnd();
  4596. Sym * sym = symOpnd->m_sym;
  4597. this->DoSetDead(symOpnd, !this->ProcessSymUse(sym, false, opnd->GetIsJITOptimizedReg()));
  4598. if (IsCollectionPass())
  4599. {
  4600. break;
  4601. }
  4602. if (sym->IsPropertySym())
  4603. {
  4604. // TODO: We don't have last use info for property sym
  4605. // and we don't set the last use of the stacksym inside the property sym
  4606. if (tag == Js::BackwardPhase)
  4607. {
  4608. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  4609. {
  4610. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(symOpnd->AsPropertySymOpnd(), this->currentInstr, this->currentBlock->loop);
  4611. }
  4612. }
  4613. if (this->DoMarkTempNumbersOnTempObjects())
  4614. {
  4615. this->currentBlock->tempNumberTracker->ProcessPropertySymUse(symOpnd, this->currentInstr, this);
  4616. }
  4617. if (symOpnd->IsPropertySymOpnd())
  4618. {
  4619. this->ProcessPropertySymOpndUse(symOpnd->AsPropertySymOpnd());
  4620. }
  4621. }
  4622. }
  4623. break;
  4624. case IR::OpndKindIndir:
  4625. {
  4626. IR::IndirOpnd * indirOpnd = opnd->AsIndirOpnd();
  4627. IR::RegOpnd * baseOpnd = indirOpnd->GetBaseOpnd();
  4628. this->DoSetDead(baseOpnd, !this->ProcessSymUse(baseOpnd->m_sym, false, baseOpnd->GetIsJITOptimizedReg()));
  4629. IR::RegOpnd * indexOpnd = indirOpnd->GetIndexOpnd();
  4630. if (indexOpnd)
  4631. {
  4632. this->DoSetDead(indexOpnd, !this->ProcessSymUse(indexOpnd->m_sym, false, indexOpnd->GetIsJITOptimizedReg()));
  4633. }
  4634. if(IsCollectionPass())
  4635. {
  4636. break;
  4637. }
  4638. if (this->DoMarkTempNumbersOnTempObjects())
  4639. {
  4640. this->currentBlock->tempNumberTracker->ProcessIndirUse(indirOpnd, currentInstr, this);
  4641. }
  4642. if(tag == Js::DeadStorePhase && baseOpnd->IsArrayRegOpnd())
  4643. {
  4644. ProcessArrayRegOpndUse(currentInstr, baseOpnd->AsArrayRegOpnd());
  4645. }
  4646. }
  4647. break;
  4648. }
  4649. }
  4650. bool
  4651. BackwardPass::ProcessPropertySymUse(PropertySym *propertySym)
  4652. {
  4653. Assert(this->tag == Js::BackwardPhase);
  4654. BasicBlock *block = this->currentBlock;
  4655. bool isLive = !!block->upwardExposedFields->TestAndSet(propertySym->m_id);
  4656. if (propertySym->m_propertyEquivSet)
  4657. {
  4658. block->upwardExposedFields->Or(propertySym->m_propertyEquivSet);
  4659. }
  4660. return isLive;
  4661. }
  4662. void
  4663. BackwardPass::MarkTemp(StackSym * sym)
  4664. {
  4665. Assert(!IsCollectionPass());
  4666. // Don't care about type specialized syms
  4667. if (!sym->IsVar())
  4668. {
  4669. return;
  4670. }
  4671. BasicBlock * block = this->currentBlock;
  4672. if (this->DoMarkTempNumbers())
  4673. {
  4674. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  4675. block->tempNumberTracker->MarkTemp(sym, this);
  4676. }
  4677. if (this->DoMarkTempObjects())
  4678. {
  4679. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  4680. block->tempObjectTracker->MarkTemp(sym, this);
  4681. }
  4682. #if DBG
  4683. if (this->DoMarkTempObjectVerify())
  4684. {
  4685. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  4686. block->tempObjectVerifyTracker->MarkTemp(sym, this);
  4687. }
  4688. #endif
  4689. }
  4690. void
  4691. BackwardPass::MarkTempProcessInstr(IR::Instr * instr)
  4692. {
  4693. Assert(!IsCollectionPass());
  4694. if (this->currentBlock->isDead)
  4695. {
  4696. return;
  4697. }
  4698. BasicBlock * block;
  4699. block = this->currentBlock;
  4700. if (this->DoMarkTempNumbers())
  4701. {
  4702. block->tempNumberTracker->ProcessInstr(instr, this);
  4703. }
  4704. if (this->DoMarkTempObjects())
  4705. {
  4706. block->tempObjectTracker->ProcessInstr(instr);
  4707. }
  4708. #if DBG
  4709. if (this->DoMarkTempObjectVerify())
  4710. {
  4711. block->tempObjectVerifyTracker->ProcessInstr(instr, this);
  4712. }
  4713. #endif
  4714. }
  4715. #if DBG_DUMP
  4716. void
  4717. BackwardPass::DumpMarkTemp()
  4718. {
  4719. Assert(!IsCollectionPass());
  4720. BasicBlock * block = this->currentBlock;
  4721. if (this->DoMarkTempNumbers())
  4722. {
  4723. block->tempNumberTracker->Dump();
  4724. }
  4725. if (this->DoMarkTempObjects())
  4726. {
  4727. block->tempObjectTracker->Dump();
  4728. }
  4729. #if DBG
  4730. if (this->DoMarkTempObjectVerify())
  4731. {
  4732. block->tempObjectVerifyTracker->Dump();
  4733. }
  4734. #endif
  4735. }
  4736. #endif
  4737. void
  4738. BackwardPass::SetSymIsUsedOnlyInNumberIfLastUse(IR::Opnd *const opnd)
  4739. {
  4740. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4741. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4742. {
  4743. symUsedOnlyForNumberBySymId->Set(stackSym->m_id);
  4744. }
  4745. }
  4746. void
  4747. BackwardPass::SetSymIsNotUsedOnlyInNumber(IR::Opnd *const opnd)
  4748. {
  4749. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4750. if (stackSym)
  4751. {
  4752. symUsedOnlyForNumberBySymId->Clear(stackSym->m_id);
  4753. }
  4754. }
  4755. void
  4756. BackwardPass::SetSymIsUsedOnlyInBitOpsIfLastUse(IR::Opnd *const opnd)
  4757. {
  4758. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4759. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4760. {
  4761. symUsedOnlyForBitOpsBySymId->Set(stackSym->m_id);
  4762. }
  4763. }
  4764. void
  4765. BackwardPass::SetSymIsNotUsedOnlyInBitOps(IR::Opnd *const opnd)
  4766. {
  4767. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4768. if (stackSym)
  4769. {
  4770. symUsedOnlyForBitOpsBySymId->Clear(stackSym->m_id);
  4771. }
  4772. }
  4773. void
  4774. BackwardPass::TrackBitWiseOrNumberOp(IR::Instr *const instr)
  4775. {
  4776. Assert(instr);
  4777. const bool trackBitWiseop = DoTrackBitOpsOrNumber();
  4778. const bool trackNumberop = trackBitWiseop;
  4779. const Js::OpCode opcode = instr->m_opcode;
  4780. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4781. if (!trackBitWiseop && !trackNumberop)
  4782. {
  4783. return;
  4784. }
  4785. if (!instr->IsRealInstr())
  4786. {
  4787. return;
  4788. }
  4789. if (dstSym)
  4790. {
  4791. // For a dst where the def is in this block, transfer the current info into the instruction
  4792. if (trackBitWiseop && symUsedOnlyForBitOpsBySymId->TestAndClear(dstSym->m_id))
  4793. {
  4794. instr->dstIsAlwaysConvertedToInt32 = true;
  4795. }
  4796. if (trackNumberop && symUsedOnlyForNumberBySymId->TestAndClear(dstSym->m_id))
  4797. {
  4798. instr->dstIsAlwaysConvertedToNumber = true;
  4799. }
  4800. }
  4801. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  4802. if (OpCodeAttr::NonTempNumberSources(opcode))
  4803. {
  4804. if (trackBitWiseop)
  4805. {
  4806. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4807. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4808. }
  4809. if (trackNumberop)
  4810. {
  4811. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4812. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4813. }
  4814. return;
  4815. }
  4816. if (trackBitWiseop)
  4817. {
  4818. switch (opcode)
  4819. {
  4820. // Instructions that can cause src values to escape the local scope have already been excluded
  4821. case Js::OpCode::Not_A:
  4822. case Js::OpCode::And_A:
  4823. case Js::OpCode::Or_A:
  4824. case Js::OpCode::Xor_A:
  4825. case Js::OpCode::Shl_A:
  4826. case Js::OpCode::Shr_A:
  4827. case Js::OpCode::Not_I4:
  4828. case Js::OpCode::And_I4:
  4829. case Js::OpCode::Or_I4:
  4830. case Js::OpCode::Xor_I4:
  4831. case Js::OpCode::Shl_I4:
  4832. case Js::OpCode::Shr_I4:
  4833. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4834. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc1());
  4835. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc2());
  4836. break;
  4837. default:
  4838. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4839. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4840. break;
  4841. }
  4842. }
  4843. if (trackNumberop)
  4844. {
  4845. switch (opcode)
  4846. {
  4847. // Instructions that can cause src values to escape the local scope have already been excluded
  4848. case Js::OpCode::Conv_Num:
  4849. case Js::OpCode::Div_A:
  4850. case Js::OpCode::Mul_A:
  4851. case Js::OpCode::Sub_A:
  4852. case Js::OpCode::Rem_A:
  4853. case Js::OpCode::Incr_A:
  4854. case Js::OpCode::Decr_A:
  4855. case Js::OpCode::Neg_A:
  4856. case Js::OpCode::Not_A:
  4857. case Js::OpCode::ShrU_A:
  4858. case Js::OpCode::ShrU_I4:
  4859. case Js::OpCode::And_A:
  4860. case Js::OpCode::Or_A:
  4861. case Js::OpCode::Xor_A:
  4862. case Js::OpCode::Shl_A:
  4863. case Js::OpCode::Shr_A:
  4864. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4865. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc1());
  4866. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc2());
  4867. break;
  4868. default:
  4869. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4870. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. void
  4876. BackwardPass::RemoveNegativeZeroBailout(IR::Instr* instr)
  4877. {
  4878. Assert(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutOnNegativeZero));
  4879. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4880. bailOutKind = bailOutKind & ~IR::BailOutOnNegativeZero;
  4881. if (bailOutKind)
  4882. {
  4883. instr->SetBailOutKind(bailOutKind);
  4884. }
  4885. else
  4886. {
  4887. instr->ClearBailOutInfo();
  4888. if (preOpBailOutInstrToProcess == instr)
  4889. {
  4890. preOpBailOutInstrToProcess = nullptr;
  4891. }
  4892. }
  4893. }
  4894. void
  4895. BackwardPass::TrackIntUsage(IR::Instr *const instr)
  4896. {
  4897. Assert(instr);
  4898. const bool trackNegativeZero = DoTrackNegativeZero();
  4899. const bool trackIntOverflow = DoTrackIntOverflow();
  4900. const bool trackCompoundedIntOverflow = DoTrackCompoundedIntOverflow();
  4901. const bool trackNon32BitOverflow = DoTrackNon32BitOverflow();
  4902. if(!(trackNegativeZero || trackIntOverflow || trackCompoundedIntOverflow))
  4903. {
  4904. return;
  4905. }
  4906. const Js::OpCode opcode = instr->m_opcode;
  4907. if(trackCompoundedIntOverflow && opcode == Js::OpCode::StatementBoundary && instr->AsPragmaInstr()->m_statementIndex == 0)
  4908. {
  4909. // Cannot bail out before the first statement boundary, so the range cannot extend beyond this instruction
  4910. Assert(!instr->ignoreIntOverflowInRange);
  4911. EndIntOverflowDoesNotMatterRange();
  4912. return;
  4913. }
  4914. if(!instr->IsRealInstr())
  4915. {
  4916. return;
  4917. }
  4918. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4919. bool ignoreIntOverflowCandidate = false;
  4920. if(dstSym)
  4921. {
  4922. // For a dst where the def is in this block, transfer the current info into the instruction
  4923. if(trackNegativeZero)
  4924. {
  4925. if (negativeZeroDoesNotMatterBySymId->Test(dstSym->m_id))
  4926. {
  4927. instr->ignoreNegativeZero = true;
  4928. }
  4929. if (tag == Js::DeadStorePhase)
  4930. {
  4931. if (negativeZeroDoesNotMatterBySymId->TestAndClear(dstSym->m_id))
  4932. {
  4933. if (instr->HasBailOutInfo())
  4934. {
  4935. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4936. if (bailOutKind & IR::BailOutOnNegativeZero)
  4937. {
  4938. RemoveNegativeZeroBailout(instr);
  4939. }
  4940. }
  4941. }
  4942. else
  4943. {
  4944. if (instr->HasBailOutInfo())
  4945. {
  4946. if (instr->GetBailOutKind() & IR::BailOutOnNegativeZero)
  4947. {
  4948. if (this->currentBlock->couldRemoveNegZeroBailoutForDef->TestAndClear(dstSym->m_id))
  4949. {
  4950. RemoveNegativeZeroBailout(instr);
  4951. }
  4952. }
  4953. // This instruction could potentially bail out. Hence, we cannot reliably remove negative zero
  4954. // bailouts upstream. If we did, and the operation actually produced a -0, and this instruction
  4955. // bailed out, we'd use +0 instead of -0 in the interpreter.
  4956. this->currentBlock->couldRemoveNegZeroBailoutForDef->ClearAll();
  4957. }
  4958. }
  4959. }
  4960. else
  4961. {
  4962. this->negativeZeroDoesNotMatterBySymId->Clear(dstSym->m_id);
  4963. }
  4964. }
  4965. if(trackIntOverflow)
  4966. {
  4967. ignoreIntOverflowCandidate = !!intOverflowDoesNotMatterBySymId->TestAndClear(dstSym->m_id);
  4968. if(trackCompoundedIntOverflow)
  4969. {
  4970. instr->ignoreIntOverflowInRange = !!intOverflowDoesNotMatterInRangeBySymId->TestAndClear(dstSym->m_id);
  4971. }
  4972. }
  4973. }
  4974. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  4975. if(OpCodeAttr::NonTempNumberSources(opcode))
  4976. {
  4977. if(trackNegativeZero)
  4978. {
  4979. SetNegativeZeroMatters(instr->GetSrc1());
  4980. SetNegativeZeroMatters(instr->GetSrc2());
  4981. }
  4982. if(trackIntOverflow)
  4983. {
  4984. SetIntOverflowMatters(instr->GetSrc1());
  4985. SetIntOverflowMatters(instr->GetSrc2());
  4986. if(trackCompoundedIntOverflow)
  4987. {
  4988. instr->ignoreIntOverflowInRange = false;
  4989. SetIntOverflowMattersInRange(instr->GetSrc1());
  4990. SetIntOverflowMattersInRange(instr->GetSrc2());
  4991. EndIntOverflowDoesNotMatterRange();
  4992. }
  4993. }
  4994. return;
  4995. }
  4996. // -0 tracking
  4997. if(trackNegativeZero)
  4998. {
  4999. switch(opcode)
  5000. {
  5001. // Instructions that can cause src values to escape the local scope have already been excluded
  5002. case Js::OpCode::FromVar:
  5003. case Js::OpCode::Conv_Prim:
  5004. Assert(dstSym);
  5005. Assert(instr->GetSrc1());
  5006. Assert(!instr->GetSrc2());
  5007. if(instr->GetDst()->IsInt32())
  5008. {
  5009. // Conversion to int32 that is either explicit, or has a bailout check ensuring that it's an int value
  5010. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5011. break;
  5012. }
  5013. // fall-through
  5014. default:
  5015. if(dstSym && !instr->ignoreNegativeZero)
  5016. {
  5017. // -0 matters for dst, so -0 also matters for srcs
  5018. SetNegativeZeroMatters(instr->GetSrc1());
  5019. SetNegativeZeroMatters(instr->GetSrc2());
  5020. break;
  5021. }
  5022. if(opcode == Js::OpCode::Div_A || opcode == Js::OpCode::Div_I4)
  5023. {
  5024. // src1 is being divided by src2, so -0 matters for src2
  5025. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5026. SetNegativeZeroMatters(instr->GetSrc2());
  5027. break;
  5028. }
  5029. // fall-through
  5030. case Js::OpCode::Incr_A:
  5031. case Js::OpCode::Decr_A:
  5032. // Adding 1 to something or subtracting 1 from something does not generate -0
  5033. case Js::OpCode::Not_A:
  5034. case Js::OpCode::And_A:
  5035. case Js::OpCode::Or_A:
  5036. case Js::OpCode::Xor_A:
  5037. case Js::OpCode::Shl_A:
  5038. case Js::OpCode::Shr_A:
  5039. case Js::OpCode::ShrU_A:
  5040. case Js::OpCode::Not_I4:
  5041. case Js::OpCode::And_I4:
  5042. case Js::OpCode::Or_I4:
  5043. case Js::OpCode::Xor_I4:
  5044. case Js::OpCode::Shl_I4:
  5045. case Js::OpCode::Shr_I4:
  5046. case Js::OpCode::ShrU_I4:
  5047. case Js::OpCode::Conv_Str:
  5048. case Js::OpCode::Coerce_Str:
  5049. case Js::OpCode::Coerce_Regex:
  5050. case Js::OpCode::Coerce_StrOrRegex:
  5051. case Js::OpCode::Conv_PrimStr:
  5052. case Js::OpCode::Add_Ptr:
  5053. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  5054. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5055. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5056. break;
  5057. case Js::OpCode::Add_I4:
  5058. {
  5059. Assert(dstSym);
  5060. Assert(instr->GetSrc1());
  5061. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsIntConstOpnd());
  5062. Assert(instr->GetSrc2());
  5063. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsIntConstOpnd());
  5064. if (instr->ignoreNegativeZero ||
  5065. (instr->GetSrc1()->IsIntConstOpnd() && instr->GetSrc1()->AsIntConstOpnd()->GetValue() != 0) ||
  5066. (instr->GetSrc2()->IsIntConstOpnd() && instr->GetSrc2()->AsIntConstOpnd()->GetValue() != 0))
  5067. {
  5068. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5069. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5070. break;
  5071. }
  5072. // -0 + -0 == -0. As long as one src is guaranteed to not be -0, -0 does not matter for the other src. Pick a
  5073. // src for which to ignore negative zero, based on which sym is last-use. If both syms are last-use, src2 is
  5074. // picked arbitrarily.
  5075. SetNegativeZeroMatters(instr->GetSrc1());
  5076. SetNegativeZeroMatters(instr->GetSrc2());
  5077. if (tag == Js::DeadStorePhase)
  5078. {
  5079. if (instr->GetSrc2()->IsRegOpnd() &&
  5080. !currentBlock->upwardExposedUses->Test(instr->GetSrc2()->AsRegOpnd()->m_sym->m_id))
  5081. {
  5082. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5083. }
  5084. else
  5085. {
  5086. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc1());
  5087. }
  5088. }
  5089. break;
  5090. }
  5091. case Js::OpCode::Add_A:
  5092. Assert(dstSym);
  5093. Assert(instr->GetSrc1());
  5094. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5095. Assert(instr->GetSrc2());
  5096. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd());
  5097. if(instr->ignoreNegativeZero || instr->GetSrc1()->IsAddrOpnd() || instr->GetSrc2()->IsAddrOpnd())
  5098. {
  5099. // -0 does not matter for dst, or this instruction does not generate -0 since one of the srcs is not -0
  5100. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5101. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5102. break;
  5103. }
  5104. SetNegativeZeroMatters(instr->GetSrc1());
  5105. SetNegativeZeroMatters(instr->GetSrc2());
  5106. break;
  5107. case Js::OpCode::Sub_I4:
  5108. {
  5109. Assert(dstSym);
  5110. Assert(instr->GetSrc1());
  5111. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsIntConstOpnd());
  5112. Assert(instr->GetSrc2());
  5113. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsIntConstOpnd());
  5114. if (instr->ignoreNegativeZero ||
  5115. (instr->GetSrc1()->IsIntConstOpnd() && instr->GetSrc1()->AsIntConstOpnd()->GetValue() != 0) ||
  5116. (instr->GetSrc2()->IsIntConstOpnd() && instr->GetSrc2()->AsIntConstOpnd()->GetValue() != 0))
  5117. {
  5118. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5119. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5120. }
  5121. else
  5122. {
  5123. goto NegativeZero_Sub_Default;
  5124. }
  5125. break;
  5126. }
  5127. case Js::OpCode::Sub_A:
  5128. Assert(dstSym);
  5129. Assert(instr->GetSrc1());
  5130. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5131. Assert(instr->GetSrc2());
  5132. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd() || instr->GetSrc2()->IsIntConstOpnd());
  5133. if(instr->ignoreNegativeZero ||
  5134. instr->GetSrc1()->IsAddrOpnd() ||
  5135. (
  5136. instr->GetSrc2()->IsAddrOpnd() &&
  5137. instr->GetSrc2()->AsAddrOpnd()->IsVar() &&
  5138. Js::TaggedInt::ToInt32(instr->GetSrc2()->AsAddrOpnd()->m_address) != 0
  5139. ))
  5140. {
  5141. // At least one of the following is true:
  5142. // - -0 does not matter for dst
  5143. // - Src1 is not -0, and so this instruction cannot generate -0
  5144. // - Src2 is a nonzero tagged int constant, and so this instruction cannot generate -0
  5145. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5146. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5147. break;
  5148. }
  5149. // fall-through
  5150. NegativeZero_Sub_Default:
  5151. // -0 - 0 == -0. As long as src1 is guaranteed to not be -0, -0 does not matter for src2.
  5152. SetNegativeZeroMatters(instr->GetSrc1());
  5153. SetNegativeZeroMatters(instr->GetSrc2());
  5154. if (this->tag == Js::DeadStorePhase)
  5155. {
  5156. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5157. }
  5158. break;
  5159. case Js::OpCode::BrEq_I4:
  5160. case Js::OpCode::BrTrue_I4:
  5161. case Js::OpCode::BrFalse_I4:
  5162. case Js::OpCode::BrGe_I4:
  5163. case Js::OpCode::BrUnGe_I4:
  5164. case Js::OpCode::BrGt_I4:
  5165. case Js::OpCode::BrUnGt_I4:
  5166. case Js::OpCode::BrLt_I4:
  5167. case Js::OpCode::BrUnLt_I4:
  5168. case Js::OpCode::BrLe_I4:
  5169. case Js::OpCode::BrUnLe_I4:
  5170. case Js::OpCode::BrNeq_I4:
  5171. // Int-specialized branches may prove that one of the src must be zero purely based on the int range, in which
  5172. // case they rely on prior -0 bailouts to guarantee that the src cannot be -0. So, consider that -0 matters for
  5173. // the srcs.
  5174. // fall-through
  5175. case Js::OpCode::InlineMathAtan2:
  5176. // Atan(y,x) - signs of y, x is used to determine the quadrant of the result
  5177. SetNegativeZeroMatters(instr->GetSrc1());
  5178. SetNegativeZeroMatters(instr->GetSrc2());
  5179. break;
  5180. case Js::OpCode::Expo_A:
  5181. case Js::OpCode::InlineMathPow:
  5182. // Negative zero matters for src1
  5183. // Pow( 0, <neg>) is Infinity
  5184. // Pow(-0, <neg>) is -Infinity
  5185. SetNegativeZeroMatters(instr->GetSrc1());
  5186. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5187. break;
  5188. case Js::OpCode::LdElemI_A:
  5189. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5190. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd());
  5191. break;
  5192. case Js::OpCode::StElemI_A:
  5193. case Js::OpCode::StElemI_A_Strict:
  5194. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5195. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd());
  5196. break;
  5197. }
  5198. }
  5199. // Int overflow tracking
  5200. if(!trackIntOverflow)
  5201. {
  5202. return;
  5203. }
  5204. switch(opcode)
  5205. {
  5206. // Instructions that can cause src values to escape the local scope have already been excluded
  5207. default:
  5208. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5209. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5210. // insufficient.
  5211. ignoreIntOverflowCandidate = false;
  5212. // fall-through
  5213. case Js::OpCode::Incr_A:
  5214. case Js::OpCode::Decr_A:
  5215. case Js::OpCode::Add_A:
  5216. case Js::OpCode::Sub_A:
  5217. // The sources are not guaranteed to be converted to int32. Let the compounded int overflow tracking handle this.
  5218. SetIntOverflowMatters(instr->GetSrc1());
  5219. SetIntOverflowMatters(instr->GetSrc2());
  5220. break;
  5221. case Js::OpCode::Mul_A:
  5222. if (trackNon32BitOverflow)
  5223. {
  5224. if (ignoreIntOverflowCandidate)
  5225. instr->ignoreOverflowBitCount = 53;
  5226. }
  5227. else
  5228. {
  5229. ignoreIntOverflowCandidate = false;
  5230. }
  5231. SetIntOverflowMatters(instr->GetSrc1());
  5232. SetIntOverflowMatters(instr->GetSrc2());
  5233. break;
  5234. case Js::OpCode::Neg_A:
  5235. case Js::OpCode::Ld_A:
  5236. case Js::OpCode::Conv_Num:
  5237. case Js::OpCode::ShrU_A:
  5238. if(!ignoreIntOverflowCandidate)
  5239. {
  5240. // Int overflow matters for dst, so int overflow also matters for srcs
  5241. SetIntOverflowMatters(instr->GetSrc1());
  5242. SetIntOverflowMatters(instr->GetSrc2());
  5243. break;
  5244. }
  5245. // fall-through
  5246. case Js::OpCode::Not_A:
  5247. case Js::OpCode::And_A:
  5248. case Js::OpCode::Or_A:
  5249. case Js::OpCode::Xor_A:
  5250. case Js::OpCode::Shl_A:
  5251. case Js::OpCode::Shr_A:
  5252. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5253. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5254. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5255. // difference if the srcs have int32-overflowed values.
  5256. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc1());
  5257. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc2());
  5258. break;
  5259. }
  5260. if(ignoreIntOverflowCandidate)
  5261. {
  5262. instr->ignoreIntOverflow = true;
  5263. }
  5264. // Compounded int overflow tracking
  5265. if(!trackCompoundedIntOverflow)
  5266. {
  5267. return;
  5268. }
  5269. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset)
  5270. {
  5271. // The forward pass may need to insert conversions with bailouts before the first instruction in the range. Since this
  5272. // instruction does not have a valid byte code offset for bailout purposes, end the current range now.
  5273. instr->ignoreIntOverflowInRange = false;
  5274. SetIntOverflowMattersInRange(instr->GetSrc1());
  5275. SetIntOverflowMattersInRange(instr->GetSrc2());
  5276. EndIntOverflowDoesNotMatterRange();
  5277. return;
  5278. }
  5279. if(ignoreIntOverflowCandidate)
  5280. {
  5281. instr->ignoreIntOverflowInRange = true;
  5282. if(dstSym)
  5283. {
  5284. dstSym->scratch.globOpt.numCompoundedAddSubUses = 0;
  5285. }
  5286. }
  5287. bool lossy = false;
  5288. switch(opcode)
  5289. {
  5290. // Instructions that can cause src values to escape the local scope have already been excluded
  5291. case Js::OpCode::Incr_A:
  5292. case Js::OpCode::Decr_A:
  5293. case Js::OpCode::Add_A:
  5294. case Js::OpCode::Sub_A:
  5295. {
  5296. if(!instr->ignoreIntOverflowInRange)
  5297. {
  5298. // Int overflow matters for dst, so int overflow also matters for srcs
  5299. SetIntOverflowMattersInRange(instr->GetSrc1());
  5300. SetIntOverflowMattersInRange(instr->GetSrc2());
  5301. break;
  5302. }
  5303. AnalysisAssert(dstSym);
  5304. // The number of compounded add/sub uses of each src is at least the number of compounded add/sub uses of the dst,
  5305. // + 1 for the current instruction
  5306. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5307. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5308. const int addSubUses = dstSym->scratch.globOpt.numCompoundedAddSubUses + 1;
  5309. if(addSubUses > MaxCompoundedUsesInAddSubForIgnoringIntOverflow)
  5310. {
  5311. // There are too many compounded add/sub uses of the srcs. There is a possibility that combined, the number
  5312. // eventually overflows the 53 bits that 'double' values have to precisely represent ints
  5313. instr->ignoreIntOverflowInRange = false;
  5314. SetIntOverflowMattersInRange(instr->GetSrc1());
  5315. SetIntOverflowMattersInRange(instr->GetSrc2());
  5316. break;
  5317. }
  5318. TransferCompoundedAddSubUsesToSrcs(instr, addSubUses);
  5319. break;
  5320. }
  5321. case Js::OpCode::Neg_A:
  5322. case Js::OpCode::Ld_A:
  5323. case Js::OpCode::Conv_Num:
  5324. case Js::OpCode::ShrU_A:
  5325. {
  5326. if(!instr->ignoreIntOverflowInRange)
  5327. {
  5328. // Int overflow matters for dst, so int overflow also matters for srcs
  5329. SetIntOverflowMattersInRange(instr->GetSrc1());
  5330. SetIntOverflowMattersInRange(instr->GetSrc2());
  5331. break;
  5332. }
  5333. AnalysisAssert(dstSym);
  5334. TransferCompoundedAddSubUsesToSrcs(instr, dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5335. lossy = opcode == Js::OpCode::ShrU_A;
  5336. break;
  5337. }
  5338. case Js::OpCode::Not_A:
  5339. case Js::OpCode::And_A:
  5340. case Js::OpCode::Or_A:
  5341. case Js::OpCode::Xor_A:
  5342. case Js::OpCode::Shl_A:
  5343. case Js::OpCode::Shr_A:
  5344. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5345. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5346. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5347. // difference if the srcs have int32-overflowed values.
  5348. instr->ignoreIntOverflowInRange = true;
  5349. lossy = true;
  5350. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc1(), 0);
  5351. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc2(), 0);
  5352. break;
  5353. case Js::OpCode::LdSlotArr:
  5354. case Js::OpCode::LdSlot:
  5355. {
  5356. Assert(dstSym);
  5357. Assert(!instr->GetSrc2()); // at the moment, this list contains only unary operations
  5358. if(intOverflowCurrentlyMattersInRange)
  5359. {
  5360. // These instructions will not begin a range, so just return. They don't begin a range because their initial
  5361. // value may not be available until after the instruction is processed in the forward pass.
  5362. Assert(!instr->ignoreIntOverflowInRange);
  5363. return;
  5364. }
  5365. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5366. // Int overflow does not matter for dst, so the srcs need to be tracked as inputs into the region of
  5367. // instructions where int overflow does not matter. Since these instructions will not begin or end a range, they
  5368. // are tracked in separate candidates bit-vectors and once we have confirmed that they don't begin the range,
  5369. // they will be transferred to 'SymsRequiredToBe[Lossy]Int'. Furthermore, once this instruction is included in
  5370. // the range, its dst sym has to be removed. Since this instructions may not be included in the range, add the
  5371. // dst sym to the candidates bit-vectors. If they are included, the process of transferring will remove the dst
  5372. // syms and add the src syms.
  5373. // Remove the dst using the candidate bit-vectors
  5374. Assert(
  5375. !instr->ignoreIntOverflowInRange ||
  5376. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id));
  5377. if(instr->ignoreIntOverflowInRange ||
  5378. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id))
  5379. {
  5380. candidateSymsRequiredToBeInt->Set(dstSym->m_id);
  5381. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id))
  5382. {
  5383. candidateSymsRequiredToBeLossyInt->Set(dstSym->m_id);
  5384. }
  5385. }
  5386. if(!instr->ignoreIntOverflowInRange)
  5387. {
  5388. // These instructions will not end a range, so just return. They may be included in the middle of a range, but
  5389. // since int overflow matters for the dst, the src does not need to be counted as an input into the range.
  5390. return;
  5391. }
  5392. instr->ignoreIntOverflowInRange = false;
  5393. // Add the src using the candidate bit-vectors. The src property sym may already be included in the range or as
  5394. // a candidate. The xor of the final bit-vector with the candidate is the set of syms required to be int,
  5395. // assuming all instructions up to and not including this one are included in the range.
  5396. const SymID srcSymId = instr->GetSrc1()->AsSymOpnd()->m_sym->m_id;
  5397. const bool srcIncluded =
  5398. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(srcSymId) ^
  5399. !!candidateSymsRequiredToBeInt->Test(srcSymId);
  5400. const bool srcIncludedAsLossy =
  5401. srcIncluded &&
  5402. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(srcSymId) ^
  5403. !!candidateSymsRequiredToBeLossyInt->Test(srcSymId);
  5404. const bool srcNeedsToBeLossless =
  5405. !currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id) ||
  5406. (srcIncluded && !srcIncludedAsLossy);
  5407. if(srcIncluded)
  5408. {
  5409. if(srcIncludedAsLossy && srcNeedsToBeLossless)
  5410. {
  5411. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5412. }
  5413. }
  5414. else
  5415. {
  5416. candidateSymsRequiredToBeInt->Compliment(srcSymId);
  5417. if(!srcNeedsToBeLossless)
  5418. {
  5419. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5420. }
  5421. }
  5422. // These instructions will not end a range, so just return. They may be included in the middle of a range, and the
  5423. // src has been included as a candidate input into the range.
  5424. return;
  5425. }
  5426. case Js::OpCode::Mul_A:
  5427. if (trackNon32BitOverflow)
  5428. {
  5429. // MULs will always be at the start of a range. Either included in the range if int32 overflow is ignored, or excluded if int32 overflow matters. Even if int32 can be ignored, MULs can still bailout on 53-bit.
  5430. // That's why it cannot be in the middle of a range.
  5431. if (instr->ignoreIntOverflowInRange)
  5432. {
  5433. AnalysisAssert(dstSym);
  5434. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5435. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5436. instr->ignoreOverflowBitCount = (uint8) (53 - dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5437. // We have the max number of compounded adds/subs. 32-bit overflow cannot be ignored.
  5438. if (instr->ignoreOverflowBitCount == 32)
  5439. {
  5440. instr->ignoreIntOverflowInRange = false;
  5441. }
  5442. }
  5443. SetIntOverflowMattersInRange(instr->GetSrc1());
  5444. SetIntOverflowMattersInRange(instr->GetSrc2());
  5445. break;
  5446. }
  5447. // fall-through
  5448. default:
  5449. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5450. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5451. // insufficient.
  5452. instr->ignoreIntOverflowInRange = false;
  5453. SetIntOverflowMattersInRange(instr->GetSrc1());
  5454. SetIntOverflowMattersInRange(instr->GetSrc2());
  5455. break;
  5456. }
  5457. if(!instr->ignoreIntOverflowInRange)
  5458. {
  5459. EndIntOverflowDoesNotMatterRange();
  5460. return;
  5461. }
  5462. if(intOverflowCurrentlyMattersInRange)
  5463. {
  5464. // This is the last instruction in a new range of instructions where int overflow does not matter
  5465. intOverflowCurrentlyMattersInRange = false;
  5466. IR::Instr *const boundaryInstr = IR::PragmaInstr::New(Js::OpCode::NoIntOverflowBoundary, 0, instr->m_func);
  5467. boundaryInstr->SetByteCodeOffset(instr);
  5468. currentBlock->InsertInstrAfter(boundaryInstr, instr);
  5469. currentBlock->intOverflowDoesNotMatterRange =
  5470. IntOverflowDoesNotMatterRange::New(
  5471. globOpt->alloc,
  5472. instr,
  5473. boundaryInstr,
  5474. currentBlock->intOverflowDoesNotMatterRange);
  5475. }
  5476. else
  5477. {
  5478. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5479. // Extend the current range of instructions where int overflow does not matter, to include this instruction. We also need to
  5480. // include the tracked syms for instructions that have not yet been included in the range, which are tracked in the range's
  5481. // bit-vector. 'SymsRequiredToBeInt' will contain both the dst and src syms of instructions not yet included in the range;
  5482. // the xor will remove the dst syms and add the src syms.
  5483. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Xor(candidateSymsRequiredToBeInt);
  5484. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Xor(candidateSymsRequiredToBeLossyInt);
  5485. candidateSymsRequiredToBeInt->ClearAll();
  5486. candidateSymsRequiredToBeLossyInt->ClearAll();
  5487. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(instr);
  5488. }
  5489. // Track syms that are inputs into the range based on the current instruction, which was just added to the range. The dst
  5490. // sym is obtaining a new value so it isn't required to be an int at the start of the range, but the srcs are.
  5491. if(dstSym)
  5492. {
  5493. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Clear(dstSym->m_id);
  5494. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(dstSym->m_id);
  5495. }
  5496. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5497. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  5498. {
  5499. StackSym *srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5500. if(!srcSym)
  5501. {
  5502. continue;
  5503. }
  5504. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->TestAndSet(srcSym->m_id))
  5505. {
  5506. if(!lossy)
  5507. {
  5508. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(srcSym->m_id);
  5509. }
  5510. }
  5511. else if(lossy)
  5512. {
  5513. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Set(srcSym->m_id);
  5514. }
  5515. }
  5516. // If the last instruction included in the range is a MUL, we have to end the range.
  5517. // MULs with ignoreIntOverflow can still bailout on 53-bit overflow, so they cannot be in the middle of a range
  5518. if (trackNon32BitOverflow && instr->m_opcode == Js::OpCode::Mul_A)
  5519. {
  5520. // range would have ended already if int32 overflow matters
  5521. Assert(instr->ignoreIntOverflowInRange && instr->ignoreOverflowBitCount != 32);
  5522. EndIntOverflowDoesNotMatterRange();
  5523. }
  5524. }
  5525. void
  5526. BackwardPass::SetNegativeZeroDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5527. {
  5528. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5529. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5530. {
  5531. negativeZeroDoesNotMatterBySymId->Set(stackSym->m_id);
  5532. }
  5533. }
  5534. void
  5535. BackwardPass::SetNegativeZeroMatters(IR::Opnd *const opnd)
  5536. {
  5537. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5538. if(stackSym)
  5539. {
  5540. negativeZeroDoesNotMatterBySymId->Clear(stackSym->m_id);
  5541. }
  5542. }
  5543. void
  5544. BackwardPass::SetCouldRemoveNegZeroBailoutForDefIfLastUse(IR::Opnd *const opnd)
  5545. {
  5546. StackSym * stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5547. if (stackSym && !this->currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5548. {
  5549. this->currentBlock->couldRemoveNegZeroBailoutForDef->Set(stackSym->m_id);
  5550. }
  5551. }
  5552. void
  5553. BackwardPass::SetIntOverflowDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5554. {
  5555. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5556. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5557. {
  5558. intOverflowDoesNotMatterBySymId->Set(stackSym->m_id);
  5559. }
  5560. }
  5561. void
  5562. BackwardPass::SetIntOverflowMatters(IR::Opnd *const opnd)
  5563. {
  5564. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5565. if(stackSym)
  5566. {
  5567. intOverflowDoesNotMatterBySymId->Clear(stackSym->m_id);
  5568. }
  5569. }
  5570. bool
  5571. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(IR::Opnd *const opnd, const int addSubUses)
  5572. {
  5573. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5574. return stackSym && SetIntOverflowDoesNotMatterInRangeIfLastUse(stackSym, addSubUses);
  5575. }
  5576. bool
  5577. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(StackSym *const stackSym, const int addSubUses)
  5578. {
  5579. Assert(stackSym);
  5580. Assert(addSubUses >= 0);
  5581. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5582. if(currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5583. {
  5584. return false;
  5585. }
  5586. intOverflowDoesNotMatterInRangeBySymId->Set(stackSym->m_id);
  5587. stackSym->scratch.globOpt.numCompoundedAddSubUses = addSubUses;
  5588. return true;
  5589. }
  5590. void
  5591. BackwardPass::SetIntOverflowMattersInRange(IR::Opnd *const opnd)
  5592. {
  5593. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5594. if(stackSym)
  5595. {
  5596. intOverflowDoesNotMatterInRangeBySymId->Clear(stackSym->m_id);
  5597. }
  5598. }
  5599. void
  5600. BackwardPass::TransferCompoundedAddSubUsesToSrcs(IR::Instr *const instr, const int addSubUses)
  5601. {
  5602. Assert(instr);
  5603. Assert(addSubUses >= 0);
  5604. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5605. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5606. for(int i = 0; i < _countof(srcs) && srcs[i]; ++i)
  5607. {
  5608. StackSym *const srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5609. if(!srcSym)
  5610. {
  5611. // Int overflow tracking is only done for StackSyms in RegOpnds. Int overflow matters for the src, so it is
  5612. // guaranteed to be in the int range at this point if the instruction is int-specialized.
  5613. continue;
  5614. }
  5615. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5616. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5617. if(SetIntOverflowDoesNotMatterInRangeIfLastUse(srcSym, addSubUses))
  5618. {
  5619. // This is the last use of the src
  5620. continue;
  5621. }
  5622. if(intOverflowDoesNotMatterInRangeBySymId->Test(srcSym->m_id))
  5623. {
  5624. // Since a src may be compounded through different chains of add/sub instructions, the greater number must be
  5625. // preserved
  5626. srcSym->scratch.globOpt.numCompoundedAddSubUses =
  5627. max(srcSym->scratch.globOpt.numCompoundedAddSubUses, addSubUses);
  5628. }
  5629. else
  5630. {
  5631. // Int overflow matters for the src, so it is guaranteed to be in the int range at this point if the instruction is
  5632. // int-specialized
  5633. }
  5634. }
  5635. }
  5636. void
  5637. BackwardPass::EndIntOverflowDoesNotMatterRange()
  5638. {
  5639. if(intOverflowCurrentlyMattersInRange)
  5640. {
  5641. return;
  5642. }
  5643. intOverflowCurrentlyMattersInRange = true;
  5644. if(currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next ==
  5645. currentBlock->intOverflowDoesNotMatterRange->LastInstr())
  5646. {
  5647. // Don't need a range for a single-instruction range
  5648. IntOverflowDoesNotMatterRange *const rangeToDelete = currentBlock->intOverflowDoesNotMatterRange;
  5649. currentBlock->intOverflowDoesNotMatterRange = currentBlock->intOverflowDoesNotMatterRange->Next();
  5650. currentBlock->RemoveInstr(rangeToDelete->LastInstr());
  5651. rangeToDelete->Delete(globOpt->alloc);
  5652. }
  5653. else
  5654. {
  5655. // End the current range of instructions where int overflow does not matter
  5656. IR::Instr *const boundaryInstr =
  5657. IR::PragmaInstr::New(
  5658. Js::OpCode::NoIntOverflowBoundary,
  5659. 0,
  5660. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_func);
  5661. boundaryInstr->SetByteCodeOffset(currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5662. currentBlock->InsertInstrBefore(boundaryInstr, currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5663. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(boundaryInstr);
  5664. #if DBG_DUMP
  5665. if(PHASE_TRACE(Js::TrackCompoundedIntOverflowPhase, func))
  5666. {
  5667. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5668. Output::Print(
  5669. _u("TrackCompoundedIntOverflow - Top function: %s (%s), Phase: %s, Block: %u\n"),
  5670. func->GetJITFunctionBody()->GetDisplayName(),
  5671. func->GetDebugNumberSet(debugStringBuffer),
  5672. Js::PhaseNames[Js::BackwardPhase],
  5673. currentBlock->GetBlockNum());
  5674. Output::Print(_u(" Input syms to be int-specialized (lossless): "));
  5675. candidateSymsRequiredToBeInt->Minus(
  5676. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt(),
  5677. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()); // candidate bit-vectors are cleared below anyway
  5678. candidateSymsRequiredToBeInt->Dump();
  5679. Output::Print(_u(" Input syms to be converted to int (lossy): "));
  5680. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Dump();
  5681. Output::Print(_u(" First instr: "));
  5682. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next->Dump();
  5683. Output::Flush();
  5684. }
  5685. #endif
  5686. }
  5687. // Reset candidates for the next range
  5688. candidateSymsRequiredToBeInt->ClearAll();
  5689. candidateSymsRequiredToBeLossyInt->ClearAll();
  5690. // Syms are not tracked across different ranges of instructions where int overflow does not matter, since instructions
  5691. // between the ranges may bail out. The value of the dst of an int operation where overflow is ignored is incorrect until
  5692. // the last use of that sym is converted to int. If the int operation and the last use of the sym are in different ranges
  5693. // and an instruction between the ranges bails out, other inputs into the second range are no longer guaranteed to be ints,
  5694. // so the incorrect value of the sym may be used in non-int operations.
  5695. intOverflowDoesNotMatterInRangeBySymId->ClearAll();
  5696. }
  5697. void
  5698. BackwardPass::TrackFloatSymEquivalence(IR::Instr *const instr)
  5699. {
  5700. /*
  5701. This function determines sets of float-specialized syms where any two syms in a set may have the same value number at some
  5702. point in the function. Conversely, if two float-specialized syms are not in the same set, it guarantees that those two syms
  5703. will never have the same value number. These sets are referred to as equivalence classes here.
  5704. The equivalence class for a sym is used to determine whether a bailout FromVar generating a float value for the sym needs to
  5705. bail out on any non-number value. For instance, for syms s1 and s5 in an equivalence class (say we have s5 = s1 at some
  5706. point), if there's a FromVar that generates a float value for s1 but only bails out on strings or non-primitives, and s5 is
  5707. returned from the function, it has to be ensured that s5 is not converted to Var. If the source of the FromVar was null, the
  5708. FromVar would not have bailed out, and s1 and s5 would have the value +0. When s5 is returned, we need to return null and
  5709. not +0, so the equivalence class is used to determine that since s5 requires a bailout on any non-number value, so does s1.
  5710. The tracking is very conservative because the bit that says "I require bailout on any non-number value" is on the sym itself
  5711. (referred to as non-number bailout bit below).
  5712. Data:
  5713. - BackwardPass::floatSymEquivalenceMap
  5714. - hash table mapping a float sym ID to its equivalence class
  5715. - FloatSymEquivalenceClass
  5716. - bit vector of float sym IDs that are in the equivalence class
  5717. - one non-number bailout bit for all syms in the equivalence class
  5718. Algorithm:
  5719. - In a loop prepass or when not in loop:
  5720. - For a float sym transfer (s0.f = s1.f), add both syms to an equivalence class (set the syms in a bit vector)
  5721. - If either sym requires bailout on any non-number value, set the equivalence class' non-number bailout bit
  5722. - If one of the syms is already in an equivalence class, merge the two equivalence classes by OR'ing the two bit vectors
  5723. and the non-number bailout bit.
  5724. - Note that for functions with a loop, dependency tracking is done using equivalence classes and that information is not
  5725. transferred back into each sym's non-number bailout bit
  5726. - In a loop non-prepass or when not in loop, for a FromVar instruction that requires bailout only on strings and
  5727. non-primitives:
  5728. - If the destination float sym's non-number bailout bit is set, or the sym is in an equivalence class whose non-number
  5729. bailout bit is set, change the bailout to bail out on any non-number value
  5730. The result is that if a float-specialized sym's value is used in a way in which it would be invalid to use the float value
  5731. through any other float-specialized sym that acquires the value, the FromVar generating the float value will be modified to
  5732. bail out on any non-number value.
  5733. */
  5734. Assert(instr);
  5735. if(tag != Js::DeadStorePhase || instr->GetSrc2() || !instr->m_func->hasBailout)
  5736. {
  5737. return;
  5738. }
  5739. if(!instr->GetDst() || !instr->GetDst()->IsRegOpnd())
  5740. {
  5741. return;
  5742. }
  5743. const auto dst = instr->GetDst()->AsRegOpnd()->m_sym;
  5744. if(!dst->IsFloat64())
  5745. {
  5746. return;
  5747. }
  5748. if(!instr->GetSrc1() || !instr->GetSrc1()->IsRegOpnd())
  5749. {
  5750. return;
  5751. }
  5752. const auto src = instr->GetSrc1()->AsRegOpnd()->m_sym;
  5753. if(OpCodeAttr::NonIntTransfer(instr->m_opcode) && (!currentBlock->loop || IsPrePass()))
  5754. {
  5755. Assert(src->IsFloat64()); // dst is specialized, and since this is a float transfer, src must be specialized too
  5756. if(dst == src)
  5757. {
  5758. return;
  5759. }
  5760. if(!func->m_fg->hasLoop)
  5761. {
  5762. // Special case for functions with no loops, since there can only be in-order dependencies. Just merge the two
  5763. // non-number bailout bits and put the result in the source.
  5764. if(dst->m_requiresBailOnNotNumber)
  5765. {
  5766. src->m_requiresBailOnNotNumber = true;
  5767. }
  5768. return;
  5769. }
  5770. FloatSymEquivalenceClass *dstEquivalenceClass, *srcEquivalenceClass;
  5771. const bool dstHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass);
  5772. const bool srcHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(src->m_id, &srcEquivalenceClass);
  5773. if(!dstHasEquivalenceClass)
  5774. {
  5775. if(srcHasEquivalenceClass)
  5776. {
  5777. // Just add the destination into the source's equivalence class
  5778. srcEquivalenceClass->Set(dst);
  5779. floatSymEquivalenceMap->Add(dst->m_id, srcEquivalenceClass);
  5780. return;
  5781. }
  5782. dstEquivalenceClass = JitAnew(tempAlloc, FloatSymEquivalenceClass, tempAlloc);
  5783. dstEquivalenceClass->Set(dst);
  5784. floatSymEquivalenceMap->Add(dst->m_id, dstEquivalenceClass);
  5785. }
  5786. if(!srcHasEquivalenceClass)
  5787. {
  5788. // Just add the source into the destination's equivalence class
  5789. dstEquivalenceClass->Set(src);
  5790. floatSymEquivalenceMap->Add(src->m_id, dstEquivalenceClass);
  5791. return;
  5792. }
  5793. if(dstEquivalenceClass == srcEquivalenceClass)
  5794. {
  5795. return;
  5796. }
  5797. Assert(!dstEquivalenceClass->Bv()->Test(src->m_id));
  5798. Assert(!srcEquivalenceClass->Bv()->Test(dst->m_id));
  5799. // Merge the two equivalence classes. The source's equivalence class is typically smaller, so it's merged into the
  5800. // destination's equivalence class. To save space and prevent a potential explosion of bit vector size,
  5801. // 'floatSymEquivalenceMap' is updated for syms in the source's equivalence class to map to the destination's now merged
  5802. // equivalence class, and the source's equivalence class is discarded.
  5803. dstEquivalenceClass->Or(srcEquivalenceClass);
  5804. FOREACH_BITSET_IN_SPARSEBV(id, srcEquivalenceClass->Bv())
  5805. {
  5806. floatSymEquivalenceMap->Item(id, dstEquivalenceClass);
  5807. } NEXT_BITSET_IN_SPARSEBV;
  5808. JitAdelete(tempAlloc, srcEquivalenceClass);
  5809. return;
  5810. }
  5811. // Not a float transfer, and non-prepass (not necessarily in a loop)
  5812. if(!instr->HasBailOutInfo() || instr->GetBailOutKind() != IR::BailOutPrimitiveButString)
  5813. {
  5814. return;
  5815. }
  5816. Assert(instr->m_opcode == Js::OpCode::FromVar);
  5817. // If either the destination or its equivalence class says it requires bailout on any non-number value, adjust the bailout
  5818. // kind on the instruction. Both are checked because in functions without loops, equivalence tracking is not done and only
  5819. // the sym's non-number bailout bit will have the information, and in functions with loops, equivalence tracking is done
  5820. // throughout the function and checking just the sym's non-number bailout bit is insufficient.
  5821. FloatSymEquivalenceClass *dstEquivalenceClass;
  5822. if(dst->m_requiresBailOnNotNumber ||
  5823. (floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass) && dstEquivalenceClass->RequiresBailOnNotNumber()))
  5824. {
  5825. instr->SetBailOutKind(IR::BailOutNumberOnly);
  5826. }
  5827. }
  5828. bool
  5829. BackwardPass::ProcessDef(IR::Opnd * opnd)
  5830. {
  5831. BOOLEAN isJITOptimizedReg = false;
  5832. Sym * sym;
  5833. if (opnd->IsRegOpnd())
  5834. {
  5835. sym = opnd->AsRegOpnd()->m_sym;
  5836. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5837. if (!IsCollectionPass())
  5838. {
  5839. this->InvalidateCloneStrCandidate(opnd);
  5840. }
  5841. }
  5842. else if (opnd->IsSymOpnd())
  5843. {
  5844. sym = opnd->AsSymOpnd()->m_sym;
  5845. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5846. }
  5847. else
  5848. {
  5849. if (opnd->IsIndirOpnd())
  5850. {
  5851. this->ProcessUse(opnd);
  5852. }
  5853. return false;
  5854. }
  5855. BasicBlock * block = this->currentBlock;
  5856. BOOLEAN isUsed = true;
  5857. BOOLEAN keepSymLiveForException = false;
  5858. BOOLEAN keepVarSymLiveForException = false;
  5859. IR::Instr * instr = this->currentInstr;
  5860. Assert(!instr->IsByteCodeUsesInstr());
  5861. if (sym->IsPropertySym())
  5862. {
  5863. if(IsCollectionPass())
  5864. {
  5865. return false;
  5866. }
  5867. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  5868. if (block->fieldHoistCandidates)
  5869. {
  5870. block->fieldHoistCandidates->Clear(sym->m_id);
  5871. }
  5872. PropertySym *propertySym = sym->AsPropertySym();
  5873. if (this->DoDeadStoreSlots())
  5874. {
  5875. if (propertySym->m_fieldKind == PropertyKindLocalSlots || propertySym->m_fieldKind == PropertyKindSlots)
  5876. {
  5877. BOOLEAN isPropertySymUsed = !block->slotDeadStoreCandidates->TestAndSet(propertySym->m_id);
  5878. // we should not do any dead slots in asmjs loop body
  5879. Assert(!(this->func->GetJITFunctionBody()->IsAsmJsMode() && this->func->IsLoopBody() && !isPropertySymUsed));
  5880. Assert(isPropertySymUsed || !block->upwardExposedUses->Test(propertySym->m_id));
  5881. isUsed = isPropertySymUsed || block->upwardExposedUses->Test(propertySym->m_stackSym->m_id);
  5882. }
  5883. }
  5884. this->DoSetDead(opnd, !block->upwardExposedFields->TestAndClear(propertySym->m_id));
  5885. ProcessStackSymUse(propertySym->m_stackSym, isJITOptimizedReg);
  5886. if (tag == Js::BackwardPhase)
  5887. {
  5888. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5889. {
  5890. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(opnd->AsPropertySymOpnd(), instr, this->currentBlock->loop);
  5891. }
  5892. }
  5893. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5894. {
  5895. this->ProcessPropertySymOpndUse(opnd->AsPropertySymOpnd());
  5896. }
  5897. }
  5898. else
  5899. {
  5900. Assert(!instr->IsByteCodeUsesInstr());
  5901. if (this->DoByteCodeUpwardExposedUsed())
  5902. {
  5903. if (sym->AsStackSym()->HasByteCodeRegSlot())
  5904. {
  5905. StackSym * varSym = sym->AsStackSym();
  5906. if (varSym->IsTypeSpec())
  5907. {
  5908. // It has to have a var version for byte code regs
  5909. varSym = varSym->GetVarEquivSym(nullptr);
  5910. }
  5911. if (this->currentRegion)
  5912. {
  5913. keepSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, sym->AsStackSym());
  5914. keepVarSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, varSym);
  5915. }
  5916. if (!isJITOptimizedReg)
  5917. {
  5918. if (!DoDeadStore(this->func, sym->AsStackSym()))
  5919. {
  5920. // Don't deadstore the bytecodereg sym, so that we could do write to get the locals inspection
  5921. if (opnd->IsRegOpnd())
  5922. {
  5923. opnd->AsRegOpnd()->m_dontDeadStore = true;
  5924. }
  5925. }
  5926. // write through symbols should not be cleared from the byteCodeUpwardExposedUsed BV upon defs in the Try region:
  5927. // try
  5928. // x =
  5929. // <bailout> <-- this bailout should restore x from its first def. This would not happen if x is cleared
  5930. // from byteCodeUpwardExposedUsed when we process its second def
  5931. // <exception>
  5932. // x =
  5933. // catch
  5934. // = x
  5935. if (!keepVarSymLiveForException)
  5936. {
  5937. // Always track the sym use on the var sym.
  5938. block->byteCodeUpwardExposedUsed->Clear(varSym->m_id);
  5939. #if DBG
  5940. // TODO: We can only track first level function stack syms right now
  5941. if (varSym->GetByteCodeFunc() == this->func)
  5942. {
  5943. block->byteCodeRestoreSyms[varSym->GetByteCodeRegSlot()] = nullptr;
  5944. }
  5945. #endif
  5946. }
  5947. }
  5948. }
  5949. }
  5950. if(IsCollectionPass())
  5951. {
  5952. return false;
  5953. }
  5954. // Don't care about property sym for mark temps
  5955. if (opnd->IsRegOpnd())
  5956. {
  5957. this->MarkTemp(sym->AsStackSym());
  5958. }
  5959. if (this->tag == Js::BackwardPhase &&
  5960. instr->m_opcode == Js::OpCode::Ld_A &&
  5961. instr->GetSrc1()->IsRegOpnd() &&
  5962. block->upwardExposedFields->Test(sym->m_id))
  5963. {
  5964. block->upwardExposedFields->Set(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  5965. }
  5966. if (!keepSymLiveForException)
  5967. {
  5968. isUsed = block->upwardExposedUses->TestAndClear(sym->m_id);
  5969. }
  5970. }
  5971. if (isUsed || !this->DoDeadStore())
  5972. {
  5973. return false;
  5974. }
  5975. // FromVar on a primitive value has no side-effects
  5976. // TODO: There may be more cases where FromVars can be dead-stored, such as cases where they have a bailout that would bail
  5977. // out on non-primitive vars, thereby causing no side effects anyway. However, it needs to be ensured that no assumptions
  5978. // that depend on the bailout are made later in the function.
  5979. // Special case StFld for trackable fields
  5980. bool hasSideEffects = instr->HasAnySideEffects()
  5981. && instr->m_opcode != Js::OpCode::StFld
  5982. && instr->m_opcode != Js::OpCode::StRootFld
  5983. && instr->m_opcode != Js::OpCode::StFldStrict
  5984. && instr->m_opcode != Js::OpCode::StRootFldStrict;
  5985. if (this->IsPrePass() || hasSideEffects)
  5986. {
  5987. return false;
  5988. }
  5989. if (opnd->IsRegOpnd() && opnd->AsRegOpnd()->m_dontDeadStore)
  5990. {
  5991. return false;
  5992. }
  5993. if (instr->HasBailOutInfo())
  5994. {
  5995. // A bailout inserted for aggressive or lossy int type specialization causes assumptions to be made on the value of
  5996. // the instruction's destination later on, as though the bailout did not happen. If the value is an int constant and
  5997. // that value is propagated forward, it can cause the bailout instruction to become a dead store and be removed,
  5998. // thereby invalidating the assumptions made. Or for lossy int type specialization, the lossy conversion to int32
  5999. // may have side effects and so cannot be dead-store-removed. As one way of solving that problem, bailout
  6000. // instructions resulting from aggressive or lossy int type spec are not dead-stored.
  6001. const auto bailOutKind = instr->GetBailOutKind();
  6002. if(bailOutKind & IR::BailOutOnResultConditions)
  6003. {
  6004. return false;
  6005. }
  6006. switch(bailOutKind & ~IR::BailOutKindBits)
  6007. {
  6008. case IR::BailOutIntOnly:
  6009. case IR::BailOutNumberOnly:
  6010. case IR::BailOutExpectingInteger:
  6011. case IR::BailOutPrimitiveButString:
  6012. case IR::BailOutExpectingString:
  6013. case IR::BailOutOnNotPrimitive:
  6014. case IR::BailOutFailedInlineTypeCheck:
  6015. case IR::BailOutOnFloor:
  6016. case IR::BailOnModByPowerOf2:
  6017. case IR::BailOnDivResultNotInt:
  6018. case IR::BailOnIntMin:
  6019. return false;
  6020. }
  6021. }
  6022. // Dead store
  6023. DeadStoreInstr(instr);
  6024. return true;
  6025. }
  6026. bool
  6027. BackwardPass::DeadStoreInstr(IR::Instr *instr)
  6028. {
  6029. BasicBlock * block = this->currentBlock;
  6030. #if DBG_DUMP
  6031. if (this->IsTraceEnabled())
  6032. {
  6033. Output::Print(_u("Deadstore instr: "));
  6034. instr->Dump();
  6035. }
  6036. this->numDeadStore++;
  6037. #endif
  6038. // Before we remove the dead store, we need to track the byte code uses
  6039. if (this->DoByteCodeUpwardExposedUsed())
  6040. {
  6041. #if DBG
  6042. BVSparse<JitArenaAllocator> tempBv(this->tempAlloc);
  6043. tempBv.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6044. #endif
  6045. PropertySym *unusedPropertySym = nullptr;
  6046. GlobOpt::TrackByteCodeSymUsed(instr, this->currentBlock->byteCodeUpwardExposedUsed, &unusedPropertySym);
  6047. #if DBG
  6048. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  6049. tempBv2.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6050. tempBv2.Minus(&tempBv);
  6051. FOREACH_BITSET_IN_SPARSEBV(symId, &tempBv2)
  6052. {
  6053. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  6054. Assert(stackSym->GetType() == TyVar);
  6055. // TODO: We can only track first level function stack syms right now
  6056. if (stackSym->GetByteCodeFunc() == this->func)
  6057. {
  6058. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  6059. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  6060. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  6061. {
  6062. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  6063. "Can't have two active lifetime for the same byte code register");
  6064. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  6065. }
  6066. }
  6067. }
  6068. NEXT_BITSET_IN_SPARSEBV;
  6069. #endif
  6070. }
  6071. // If this is a pre-op bailout instruction, we may have saved it for bailout info processing. It's being removed now, so no
  6072. // need to process the bailout info anymore.
  6073. Assert(!preOpBailOutInstrToProcess || preOpBailOutInstrToProcess == instr);
  6074. preOpBailOutInstrToProcess = nullptr;
  6075. #if DBG
  6076. if (this->DoMarkTempObjectVerify())
  6077. {
  6078. this->currentBlock->tempObjectVerifyTracker->NotifyDeadStore(instr, this);
  6079. }
  6080. #endif
  6081. if (instr->m_opcode == Js::OpCode::ArgIn_A)
  6082. {
  6083. //Ignore tracking ArgIn for "this", as argInsCount only tracks other params - unless it is a asmjs function(which doesn't have a "this").
  6084. if (instr->GetSrc1()->AsSymOpnd()->m_sym->AsStackSym()->GetParamSlotNum() != 1 || func->GetJITFunctionBody()->IsAsmJsMode())
  6085. {
  6086. Assert(this->func->argInsCount > 0);
  6087. this->func->argInsCount--;
  6088. }
  6089. }
  6090. TraceDeadStoreOfInstrsForScopeObjectRemoval();
  6091. block->RemoveInstr(instr);
  6092. return true;
  6093. }
  6094. void
  6095. BackwardPass::ProcessTransfers(IR::Instr * instr)
  6096. {
  6097. if (this->tag == Js::DeadStorePhase &&
  6098. this->currentBlock->upwardExposedFields &&
  6099. instr->m_opcode == Js::OpCode::Ld_A &&
  6100. instr->GetDst()->GetStackSym() &&
  6101. !instr->GetDst()->GetStackSym()->IsTypeSpec() &&
  6102. instr->GetDst()->GetStackSym()->HasObjectInfo() &&
  6103. instr->GetSrc1() &&
  6104. instr->GetSrc1()->GetStackSym() &&
  6105. !instr->GetSrc1()->GetStackSym()->IsTypeSpec() &&
  6106. instr->GetSrc1()->GetStackSym()->HasObjectInfo())
  6107. {
  6108. StackSym * dstStackSym = instr->GetDst()->GetStackSym();
  6109. PropertySym * dstPropertySym = dstStackSym->GetObjectInfo()->m_propertySymList;
  6110. BVSparse<JitArenaAllocator> transferFields(this->tempAlloc);
  6111. while (dstPropertySym != nullptr)
  6112. {
  6113. Assert(dstPropertySym->m_stackSym == dstStackSym);
  6114. transferFields.Set(dstPropertySym->m_id);
  6115. dstPropertySym = dstPropertySym->m_nextInStackSymList;
  6116. }
  6117. StackSym * srcStackSym = instr->GetSrc1()->GetStackSym();
  6118. PropertySym * srcPropertySym = srcStackSym->GetObjectInfo()->m_propertySymList;
  6119. BVSparse<JitArenaAllocator> equivFields(this->tempAlloc);
  6120. while (srcPropertySym != nullptr && !transferFields.IsEmpty())
  6121. {
  6122. Assert(srcPropertySym->m_stackSym == srcStackSym);
  6123. if (srcPropertySym->m_propertyEquivSet)
  6124. {
  6125. equivFields.And(&transferFields, srcPropertySym->m_propertyEquivSet);
  6126. if (!equivFields.IsEmpty())
  6127. {
  6128. transferFields.Minus(&equivFields);
  6129. this->currentBlock->upwardExposedFields->Set(srcPropertySym->m_id);
  6130. }
  6131. }
  6132. srcPropertySym = srcPropertySym->m_nextInStackSymList;
  6133. }
  6134. }
  6135. }
  6136. void
  6137. BackwardPass::ProcessFieldKills(IR::Instr * instr)
  6138. {
  6139. if (this->currentBlock->upwardExposedFields)
  6140. {
  6141. this->globOpt->ProcessFieldKills(instr, this->currentBlock->upwardExposedFields, false);
  6142. }
  6143. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToFinalType);
  6144. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToGuardedProperties);
  6145. }
  6146. template<typename T>
  6147. void
  6148. BackwardPass::ClearBucketsOnFieldKill(IR::Instr *instr, HashTable<T> *table)
  6149. {
  6150. if (table)
  6151. {
  6152. if (instr->UsesAllFields())
  6153. {
  6154. table->ClearAll();
  6155. }
  6156. else
  6157. {
  6158. IR::Opnd *dst = instr->GetDst();
  6159. if (dst && dst->IsRegOpnd())
  6160. {
  6161. table->Clear(dst->AsRegOpnd()->m_sym->m_id);
  6162. }
  6163. }
  6164. }
  6165. }
  6166. void
  6167. BackwardPass::ProcessFieldHoistKills(IR::Instr * instr)
  6168. {
  6169. // The backward pass, we optimistically will not kill on a[] access
  6170. // So that the field hoist candidate will be more then what can be hoisted
  6171. // The root prepass will figure out the exact set of field that is hoisted
  6172. this->globOpt->ProcessFieldKills(instr, this->currentBlock->fieldHoistCandidates, false);
  6173. switch (instr->m_opcode)
  6174. {
  6175. case Js::OpCode::BrOnHasProperty:
  6176. case Js::OpCode::BrOnNoProperty:
  6177. // Should not hoist pass these instructions
  6178. this->currentBlock->fieldHoistCandidates->Clear(instr->GetSrc1()->AsSymOpnd()->m_sym->m_id);
  6179. break;
  6180. }
  6181. }
  6182. bool
  6183. BackwardPass::TrackNoImplicitCallInlinees(IR::Instr *instr)
  6184. {
  6185. if (this->tag != Js::DeadStorePhase || this->IsPrePass())
  6186. {
  6187. return false;
  6188. }
  6189. if (instr->HasBailOutInfo()
  6190. || OpCodeAttr::CallInstr(instr->m_opcode)
  6191. || instr->CallsAccessor()
  6192. || GlobOpt::MayNeedBailOnImplicitCall(instr, nullptr, nullptr)
  6193. || instr->HasAnyLoadHeapArgsOpCode()
  6194. || instr->m_opcode == Js::OpCode::LdFuncExpr)
  6195. {
  6196. // This func has instrs with bailouts or implicit calls
  6197. Assert(instr->m_opcode != Js::OpCode::InlineeStart);
  6198. instr->m_func->SetHasImplicitCallsOnSelfAndParents();
  6199. return false;
  6200. }
  6201. if (instr->m_opcode == Js::OpCode::InlineeStart)
  6202. {
  6203. if (!instr->GetSrc1())
  6204. {
  6205. Assert(instr->m_func->m_hasInlineArgsOpt);
  6206. return false;
  6207. }
  6208. return this->ProcessInlineeStart(instr);
  6209. }
  6210. return false;
  6211. }
  6212. bool
  6213. BackwardPass::ProcessInlineeStart(IR::Instr* inlineeStart)
  6214. {
  6215. inlineeStart->m_func->SetFirstArgOffset(inlineeStart);
  6216. IR::Instr* startCallInstr = nullptr;
  6217. bool noImplicitCallsInInlinee = false;
  6218. // Inlinee has no bailouts or implicit calls. Get rid of the inline overhead.
  6219. auto removeInstr = [&](IR::Instr* argInstr)
  6220. {
  6221. Assert(argInstr->m_opcode == Js::OpCode::InlineeStart || argInstr->m_opcode == Js::OpCode::ArgOut_A || argInstr->m_opcode == Js::OpCode::ArgOut_A_Inline);
  6222. IR::Opnd *opnd = argInstr->GetSrc1();
  6223. StackSym *sym = opnd->GetStackSym();
  6224. if (!opnd->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6225. {
  6226. // Replace instrs with bytecodeUses
  6227. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(argInstr);
  6228. bytecodeUse->Set(opnd);
  6229. argInstr->InsertBefore(bytecodeUse);
  6230. }
  6231. startCallInstr = argInstr->GetSrc2()->GetStackSym()->m_instrDef;
  6232. FlowGraph::SafeRemoveInstr(argInstr);
  6233. return false;
  6234. };
  6235. // If there are no implicit calls - bailouts/throws - we can remove all inlining overhead.
  6236. if (!inlineeStart->m_func->GetHasImplicitCalls())
  6237. {
  6238. noImplicitCallsInInlinee = true;
  6239. inlineeStart->IterateArgInstrs(removeInstr);
  6240. inlineeStart->IterateMetaArgs([](IR::Instr* metArg)
  6241. {
  6242. FlowGraph::SafeRemoveInstr(metArg);
  6243. return false;
  6244. });
  6245. inlineeStart->m_func->m_hasInlineArgsOpt = false;
  6246. removeInstr(inlineeStart);
  6247. return true;
  6248. }
  6249. if (!inlineeStart->m_func->m_hasInlineArgsOpt)
  6250. {
  6251. PHASE_PRINT_TESTTRACE(Js::InlineArgsOptPhase, func, _u("%s[%d]: Skipping inline args optimization: %s[%d] HasCalls: %s 'arguments' access: %s Can do inlinee args opt: %s\n"),
  6252. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber(),
  6253. inlineeStart->m_func->GetJITFunctionBody()->GetDisplayName(), inlineeStart->m_func->GetJITFunctionBody()->GetFunctionNumber(),
  6254. IsTrueOrFalse(inlineeStart->m_func->GetHasCalls()),
  6255. IsTrueOrFalse(inlineeStart->m_func->GetHasUnoptimizedArgumentsAcccess()),
  6256. IsTrueOrFalse(inlineeStart->m_func->m_canDoInlineArgsOpt));
  6257. return false;
  6258. }
  6259. if (!inlineeStart->m_func->frameInfo->isRecorded)
  6260. {
  6261. PHASE_PRINT_TESTTRACE(Js::InlineArgsOptPhase, func, _u("%s[%d]: InlineeEnd not found - usually due to a throw or a BailOnNoProfile (stressed, most likely)\n"),
  6262. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber());
  6263. inlineeStart->m_func->DisableCanDoInlineArgOpt();
  6264. return false;
  6265. }
  6266. inlineeStart->IterateArgInstrs(removeInstr);
  6267. int i = 0;
  6268. inlineeStart->IterateMetaArgs([&](IR::Instr* metaArg)
  6269. {
  6270. if (i == Js::Constants::InlineeMetaArgIndex_ArgumentsObject &&
  6271. inlineeStart->m_func->GetJITFunctionBody()->UsesArgumentsObject())
  6272. {
  6273. Assert(!inlineeStart->m_func->GetHasUnoptimizedArgumentsAcccess());
  6274. // Do not remove arguments object meta arg if there is a reference to arguments object
  6275. }
  6276. else
  6277. {
  6278. FlowGraph::SafeRemoveInstr(metaArg);
  6279. }
  6280. i++;
  6281. return false;
  6282. });
  6283. IR::Opnd *src1 = inlineeStart->GetSrc1();
  6284. StackSym *sym = src1->GetStackSym();
  6285. if (!src1->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6286. {
  6287. // Replace instrs with bytecodeUses
  6288. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(inlineeStart);
  6289. bytecodeUse->Set(src1);
  6290. inlineeStart->InsertBefore(bytecodeUse);
  6291. }
  6292. // This indicates to the lowerer that this inlinee has been optimized
  6293. // and it should not be lowered - Now this instruction is used to mark inlineeStart
  6294. inlineeStart->FreeSrc1();
  6295. inlineeStart->FreeSrc2();
  6296. inlineeStart->FreeDst();
  6297. return true;
  6298. }
  6299. void
  6300. BackwardPass::ProcessInlineeEnd(IR::Instr* instr)
  6301. {
  6302. if (this->IsPrePass())
  6303. {
  6304. return;
  6305. }
  6306. if (this->tag == Js::BackwardPhase)
  6307. {
  6308. if (!GlobOpt::DoInlineArgsOpt(instr->m_func))
  6309. {
  6310. return;
  6311. }
  6312. // This adds a use for function sym as part of InlineeStart & all the syms referenced by the args.
  6313. // It ensure they do not get cleared from the copy prop sym map.
  6314. instr->IterateArgInstrs([=](IR::Instr* argInstr){
  6315. if (argInstr->GetSrc1()->IsRegOpnd())
  6316. {
  6317. this->currentBlock->upwardExposedUses->Set(argInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  6318. }
  6319. return false;
  6320. });
  6321. }
  6322. else if (this->tag == Js::DeadStorePhase)
  6323. {
  6324. if (instr->m_func->m_hasInlineArgsOpt)
  6325. {
  6326. Assert(instr->m_func->frameInfo);
  6327. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  6328. {
  6329. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  6330. });
  6331. }
  6332. }
  6333. }
  6334. bool
  6335. BackwardPass::ProcessBailOnNoProfile(IR::Instr *instr, BasicBlock *block)
  6336. {
  6337. Assert(this->tag == Js::BackwardPhase);
  6338. Assert(instr->m_opcode == Js::OpCode::BailOnNoProfile);
  6339. Assert(!instr->HasBailOutInfo());
  6340. AnalysisAssert(block);
  6341. if (this->IsPrePass())
  6342. {
  6343. return false;
  6344. }
  6345. IR::Instr *curInstr = instr->m_prev;
  6346. if (curInstr->IsLabelInstr() && curInstr->AsLabelInstr()->isOpHelper)
  6347. {
  6348. // Already processed
  6349. if (this->DoMarkTempObjects())
  6350. {
  6351. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6352. }
  6353. return false;
  6354. }
  6355. // Don't hoist if we see calls with profile data (recursive calls)
  6356. while(!curInstr->StartsBasicBlock())
  6357. {
  6358. // If a function was inlined, it must have had profile info.
  6359. if (curInstr->m_opcode == Js::OpCode::InlineeEnd || curInstr->m_opcode == Js::OpCode::InlineBuiltInEnd || curInstr->m_opcode == Js::OpCode::InlineNonTrackingBuiltInEnd
  6360. || curInstr->m_opcode == Js::OpCode::InlineeStart || curInstr->m_opcode == Js::OpCode::EndCallForPolymorphicInlinee)
  6361. {
  6362. break;
  6363. }
  6364. else if (OpCodeAttr::CallInstr(curInstr->m_opcode))
  6365. {
  6366. if (curInstr->m_prev->m_opcode != Js::OpCode::BailOnNoProfile)
  6367. {
  6368. break;
  6369. }
  6370. }
  6371. curInstr = curInstr->m_prev;
  6372. }
  6373. // Didn't get to the top of the block, delete this BailOnNoProfile.
  6374. if (!curInstr->IsLabelInstr())
  6375. {
  6376. block->RemoveInstr(instr);
  6377. return true;
  6378. }
  6379. // Save the head instruction for later use.
  6380. IR::LabelInstr *blockHeadInstr = curInstr->AsLabelInstr();
  6381. // We can't bail in the middle of a "tmp = CmEq s1, s2; BrTrue tmp" turned into a "BrEq s1, s2",
  6382. // because the bailout wouldn't be able to restore tmp.
  6383. IR::Instr *curNext = curInstr->GetNextRealInstrOrLabel();
  6384. IR::Instr *instrNope = nullptr;
  6385. if (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6386. {
  6387. block->RemoveInstr(instr);
  6388. return true;
  6389. /*while (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6390. {
  6391. // Instead of just giving up, we can be a little trickier. We can instead treat the tmp declaration(s) as a
  6392. // part of the block prefix, and put the bailonnoprofile immediately after them. This has the added benefit
  6393. // that we can still merge up blocks beginning with bailonnoprofile, even if they would otherwise not allow
  6394. // us to, due to the fact that these tmp declarations would be pre-empted by the higher-level bailout.
  6395. instrNope = curNext;
  6396. curNext = curNext->GetNextRealInstrOrLabel();
  6397. }*/
  6398. }
  6399. curInstr = instr->m_prev;
  6400. // Move to top of block (but just below any fgpeeptemp lds).
  6401. while(!curInstr->StartsBasicBlock() && curInstr != instrNope)
  6402. {
  6403. // Delete redundant BailOnNoProfile
  6404. if (curInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6405. {
  6406. Assert(!curInstr->HasBailOutInfo());
  6407. curInstr = curInstr->m_next;
  6408. curInstr->m_prev->Remove();
  6409. }
  6410. curInstr = curInstr->m_prev;
  6411. }
  6412. if (instr == block->GetLastInstr())
  6413. {
  6414. block->SetLastInstr(instr->m_prev);
  6415. }
  6416. instr->Unlink();
  6417. // Now try to move this up the flowgraph to the predecessor blocks
  6418. FOREACH_PREDECESSOR_BLOCK(pred, block)
  6419. {
  6420. bool hoistBailToPred = true;
  6421. if (block->isLoopHeader && pred->loop == block->loop)
  6422. {
  6423. // Skip loop back-edges
  6424. continue;
  6425. }
  6426. // If all successors of this predecessor start with a BailOnNoProfile, we should be
  6427. // okay to hoist this bail to the predecessor.
  6428. FOREACH_SUCCESSOR_BLOCK(predSucc, pred)
  6429. {
  6430. if (predSucc == block)
  6431. {
  6432. continue;
  6433. }
  6434. if (!predSucc->beginsBailOnNoProfile)
  6435. {
  6436. hoistBailToPred = false;
  6437. break;
  6438. }
  6439. } NEXT_SUCCESSOR_BLOCK;
  6440. if (hoistBailToPred)
  6441. {
  6442. IR::Instr *predInstr = pred->GetLastInstr();
  6443. IR::Instr *instrCopy = instr->Copy();
  6444. if (predInstr->EndsBasicBlock())
  6445. {
  6446. if (predInstr->m_prev->m_opcode == Js::OpCode::BailOnNoProfile)
  6447. {
  6448. // We already have one, we don't need a second.
  6449. instrCopy->Free();
  6450. }
  6451. else if (!predInstr->AsBranchInstr()->m_isSwitchBr)
  6452. {
  6453. // Don't put a bailout in the middle of a switch dispatch sequence.
  6454. // The bytecode offsets are not in order, and it would lead to incorrect
  6455. // bailout info.
  6456. instrCopy->m_func = predInstr->m_func;
  6457. predInstr->InsertBefore(instrCopy);
  6458. }
  6459. }
  6460. else
  6461. {
  6462. if (predInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6463. {
  6464. // We already have one, we don't need a second.
  6465. instrCopy->Free();
  6466. }
  6467. else
  6468. {
  6469. instrCopy->m_func = predInstr->m_func;
  6470. predInstr->InsertAfter(instrCopy);
  6471. pred->SetLastInstr(instrCopy);
  6472. }
  6473. }
  6474. }
  6475. } NEXT_PREDECESSOR_BLOCK;
  6476. // If we have a BailOnNoProfile in the first block, there must have been at least one path out of this block that always throws.
  6477. // Don't bother keeping the bailout in the first block as there are some issues in restoring the ArgIn bytecode registers on bailout
  6478. // and throw case should be rare enough that it won't matter for perf.
  6479. if (block->GetBlockNum() != 0)
  6480. {
  6481. blockHeadInstr->isOpHelper = true;
  6482. #if DBG
  6483. blockHeadInstr->m_noHelperAssert = true;
  6484. #endif
  6485. block->beginsBailOnNoProfile = true;
  6486. instr->m_func = curInstr->m_func;
  6487. curInstr->InsertAfter(instr);
  6488. bool setLastInstr = (curInstr == block->GetLastInstr());
  6489. if (setLastInstr)
  6490. {
  6491. block->SetLastInstr(instr);
  6492. }
  6493. if (this->DoMarkTempObjects())
  6494. {
  6495. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6496. }
  6497. return false;
  6498. }
  6499. else
  6500. {
  6501. instr->Free();
  6502. return true;
  6503. }
  6504. }
  6505. bool
  6506. BackwardPass::ReverseCopyProp(IR::Instr *instr)
  6507. {
  6508. // Look for :
  6509. //
  6510. // t1 = instr
  6511. // [bytecodeuse t1]
  6512. // t2 = Ld_A t1 >> t1 !upwardExposed
  6513. //
  6514. // Transform into:
  6515. //
  6516. // t2 = instr
  6517. //
  6518. if (PHASE_OFF(Js::ReverseCopyPropPhase, this->func))
  6519. {
  6520. return false;
  6521. }
  6522. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6523. {
  6524. return false;
  6525. }
  6526. if (this->func->HasTry())
  6527. {
  6528. // UpwardExposedUsed info can't be relied on
  6529. return false;
  6530. }
  6531. // Find t2 = Ld_A t1
  6532. switch (instr->m_opcode)
  6533. {
  6534. case Js::OpCode::Ld_A:
  6535. case Js::OpCode::Ld_I4:
  6536. break;
  6537. default:
  6538. return false;
  6539. }
  6540. if (!instr->GetDst()->IsRegOpnd())
  6541. {
  6542. return false;
  6543. }
  6544. if (!instr->GetSrc1()->IsRegOpnd())
  6545. {
  6546. return false;
  6547. }
  6548. if (instr->HasBailOutInfo())
  6549. {
  6550. return false;
  6551. }
  6552. IR::RegOpnd *dst = instr->GetDst()->AsRegOpnd();
  6553. IR::RegOpnd *src = instr->GetSrc1()->AsRegOpnd();
  6554. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6555. IR::ByteCodeUsesInstr *byteCodeUseInstr = nullptr;
  6556. StackSym *varSym = src->m_sym;
  6557. if (varSym->IsTypeSpec())
  6558. {
  6559. varSym = varSym->GetVarEquivSym(this->func);
  6560. }
  6561. // SKip ByteCodeUse instr if possible
  6562. // [bytecodeuse t1]
  6563. if (!instrPrev->GetDst())
  6564. {
  6565. if (instrPrev->m_opcode == Js::OpCode::ByteCodeUses)
  6566. {
  6567. byteCodeUseInstr = instrPrev->AsByteCodeUsesInstr();
  6568. const BVSparse<JitArenaAllocator>* byteCodeUpwardExposedUsed = byteCodeUseInstr->GetByteCodeUpwardExposedUsed();
  6569. if (byteCodeUpwardExposedUsed && byteCodeUpwardExposedUsed->Test(varSym->m_id) && byteCodeUpwardExposedUsed->Count() == 1)
  6570. {
  6571. instrPrev = byteCodeUseInstr->GetPrevRealInstrOrLabel();
  6572. if (!instrPrev->GetDst())
  6573. {
  6574. return false;
  6575. }
  6576. }
  6577. else
  6578. {
  6579. return false;
  6580. }
  6581. }
  6582. else
  6583. {
  6584. return false;
  6585. }
  6586. }
  6587. // The fast-path for these doesn't handle dst == src.
  6588. // REVIEW: I believe the fast-path for LdElemI_A has been fixed... Nope, still broken for "i = A[i]" for prejit
  6589. switch (instrPrev->m_opcode)
  6590. {
  6591. case Js::OpCode::LdElemI_A:
  6592. case Js::OpCode::IsInst:
  6593. case Js::OpCode::ByteCodeUses:
  6594. return false;
  6595. }
  6596. // Can't do it if post-op bailout would need result
  6597. // REVIEW: enable for pre-opt bailout?
  6598. if (instrPrev->HasBailOutInfo() && instrPrev->GetByteCodeOffset() != instrPrev->GetBailOutInfo()->bailOutOffset)
  6599. {
  6600. return false;
  6601. }
  6602. // Make sure src of Ld_A == dst of instr
  6603. // t1 = instr
  6604. if (!instrPrev->GetDst()->IsEqual(src))
  6605. {
  6606. return false;
  6607. }
  6608. // Make sure t1 isn't used later
  6609. if (this->currentBlock->upwardExposedUses->Test(src->m_sym->m_id))
  6610. {
  6611. return false;
  6612. }
  6613. if (this->currentBlock->byteCodeUpwardExposedUsed && this->currentBlock->byteCodeUpwardExposedUsed->Test(varSym->m_id))
  6614. {
  6615. return false;
  6616. }
  6617. // Make sure we can dead-store this sym (debugger mode?)
  6618. if (!this->DoDeadStore(this->func, src->m_sym))
  6619. {
  6620. return false;
  6621. }
  6622. StackSym *const dstSym = dst->m_sym;
  6623. if(instrPrev->HasBailOutInfo() && dstSym->IsInt32() && dstSym->IsTypeSpec())
  6624. {
  6625. StackSym *const prevDstSym = IR::RegOpnd::TryGetStackSym(instrPrev->GetDst());
  6626. if(instrPrev->GetBailOutKind() & IR::BailOutOnResultConditions &&
  6627. prevDstSym &&
  6628. prevDstSym->IsInt32() &&
  6629. prevDstSym->IsTypeSpec() &&
  6630. instrPrev->GetSrc1() &&
  6631. !instrPrev->GetDst()->IsEqual(instrPrev->GetSrc1()) &&
  6632. !(instrPrev->GetSrc2() && instrPrev->GetDst()->IsEqual(instrPrev->GetSrc2())))
  6633. {
  6634. // The previous instruction's dst value may be trashed by the time of the pre-op bailout. Skip reverse copy-prop if
  6635. // it would replace the previous instruction's dst with a sym that bailout had decided to use to restore a value for
  6636. // the pre-op bailout, which can't be trashed before bailout. See big comment in ProcessBailOutCopyProps for the
  6637. // reasoning behind the tests above.
  6638. FOREACH_SLISTBASE_ENTRY(
  6639. CopyPropSyms,
  6640. usedCopyPropSym,
  6641. &instrPrev->GetBailOutInfo()->usedCapturedValues.copyPropSyms)
  6642. {
  6643. if(dstSym == usedCopyPropSym.Value())
  6644. {
  6645. return false;
  6646. }
  6647. } NEXT_SLISTBASE_ENTRY;
  6648. }
  6649. }
  6650. if (byteCodeUseInstr)
  6651. {
  6652. if (this->currentBlock->byteCodeUpwardExposedUsed && instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6653. {
  6654. if(varSym->HasByteCodeRegSlot())
  6655. {
  6656. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6657. }
  6658. if (src->IsEqual(dst) && instrPrev->GetDst()->GetIsJITOptimizedReg())
  6659. {
  6660. // s2(s1).i32 = FromVar s1.var #0000 Bailout: #0000 (BailOutIntOnly)
  6661. // ByteCodeUses s1
  6662. // s2(s1).i32 = Ld_A s2(s1).i32
  6663. //
  6664. // Since the dst on the FromVar is marked JITOptimized, we need to set it on the new dst as well,
  6665. // or we'll change the bytecode liveness of s1
  6666. dst->SetIsJITOptimizedReg(true);
  6667. }
  6668. }
  6669. byteCodeUseInstr->Remove();
  6670. }
  6671. else if (instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && !src->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6672. {
  6673. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6674. }
  6675. #if DBG
  6676. if (this->DoMarkTempObjectVerify())
  6677. {
  6678. this->currentBlock->tempObjectVerifyTracker->NotifyReverseCopyProp(instrPrev);
  6679. }
  6680. #endif
  6681. dst->SetValueType(instrPrev->GetDst()->GetValueType());
  6682. instrPrev->ReplaceDst(dst);
  6683. instr->Remove();
  6684. return true;
  6685. }
  6686. bool
  6687. BackwardPass::FoldCmBool(IR::Instr *instr)
  6688. {
  6689. Assert(instr->m_opcode == Js::OpCode::Conv_Bool);
  6690. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6691. {
  6692. return false;
  6693. }
  6694. if (this->func->HasTry())
  6695. {
  6696. // UpwardExposedUsed info can't be relied on
  6697. return false;
  6698. }
  6699. IR::RegOpnd *intOpnd = instr->GetSrc1()->AsRegOpnd();
  6700. Assert(intOpnd->m_sym->IsInt32());
  6701. if (!intOpnd->m_sym->IsSingleDef())
  6702. {
  6703. return false;
  6704. }
  6705. IR::Instr *cmInstr = intOpnd->m_sym->GetInstrDef();
  6706. // Should be a Cm instr...
  6707. if (!cmInstr->GetSrc2())
  6708. {
  6709. return false;
  6710. }
  6711. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6712. if (instrPrev != cmInstr)
  6713. {
  6714. return false;
  6715. }
  6716. switch (cmInstr->m_opcode)
  6717. {
  6718. case Js::OpCode::CmEq_A:
  6719. case Js::OpCode::CmGe_A:
  6720. case Js::OpCode::CmUnGe_A:
  6721. case Js::OpCode::CmGt_A:
  6722. case Js::OpCode::CmUnGt_A:
  6723. case Js::OpCode::CmLt_A:
  6724. case Js::OpCode::CmUnLt_A:
  6725. case Js::OpCode::CmLe_A:
  6726. case Js::OpCode::CmUnLe_A:
  6727. case Js::OpCode::CmNeq_A:
  6728. case Js::OpCode::CmSrEq_A:
  6729. case Js::OpCode::CmSrNeq_A:
  6730. case Js::OpCode::CmEq_I4:
  6731. case Js::OpCode::CmNeq_I4:
  6732. case Js::OpCode::CmLt_I4:
  6733. case Js::OpCode::CmLe_I4:
  6734. case Js::OpCode::CmGt_I4:
  6735. case Js::OpCode::CmGe_I4:
  6736. case Js::OpCode::CmUnLt_I4:
  6737. case Js::OpCode::CmUnLe_I4:
  6738. case Js::OpCode::CmUnGt_I4:
  6739. case Js::OpCode::CmUnGe_I4:
  6740. break;
  6741. default:
  6742. return false;
  6743. }
  6744. IR::RegOpnd *varDst = instr->GetDst()->AsRegOpnd();
  6745. if (this->currentBlock->upwardExposedUses->Test(intOpnd->m_sym->m_id) || !this->currentBlock->upwardExposedUses->Test(varDst->m_sym->m_id))
  6746. {
  6747. return false;
  6748. }
  6749. varDst = instr->UnlinkDst()->AsRegOpnd();
  6750. cmInstr->ReplaceDst(varDst);
  6751. this->currentBlock->RemoveInstr(instr);
  6752. return true;
  6753. }
  6754. void
  6755. BackwardPass::SetWriteThroughSymbolsSetForRegion(BasicBlock * catchBlock, Region * tryRegion)
  6756. {
  6757. tryRegion->writeThroughSymbolsSet = JitAnew(this->func->m_alloc, BVSparse<JitArenaAllocator>, this->func->m_alloc);
  6758. if (this->DoByteCodeUpwardExposedUsed())
  6759. {
  6760. Assert(catchBlock->byteCodeUpwardExposedUsed);
  6761. if (!catchBlock->byteCodeUpwardExposedUsed->IsEmpty())
  6762. {
  6763. FOREACH_BITSET_IN_SPARSEBV(id, catchBlock->byteCodeUpwardExposedUsed)
  6764. {
  6765. tryRegion->writeThroughSymbolsSet->Set(id);
  6766. }
  6767. NEXT_BITSET_IN_SPARSEBV
  6768. }
  6769. #if DBG
  6770. // Symbols write-through in the parent try region should be marked as write-through in the current try region as well.
  6771. // x =
  6772. // try{
  6773. // try{
  6774. // x = <-- x needs to be write-through here. With the current mechanism of not clearing a write-through
  6775. // symbol from the bytecode upward-exposed on a def, x should be marked as write-through as
  6776. // write-through symbols for a try are basically the bytecode upward exposed symbols at the
  6777. // beginning of the corresponding catch block).
  6778. // Verify that it still holds.
  6779. // <exception>
  6780. // }
  6781. // catch(){}
  6782. // x =
  6783. // }
  6784. // catch(){}
  6785. // = x
  6786. if (tryRegion->GetParent()->GetType() == RegionTypeTry)
  6787. {
  6788. Region * parentTry = tryRegion->GetParent();
  6789. Assert(parentTry->writeThroughSymbolsSet);
  6790. FOREACH_BITSET_IN_SPARSEBV(id, parentTry->writeThroughSymbolsSet)
  6791. {
  6792. Assert(tryRegion->writeThroughSymbolsSet->Test(id));
  6793. }
  6794. NEXT_BITSET_IN_SPARSEBV
  6795. }
  6796. #endif
  6797. }
  6798. else
  6799. {
  6800. // this can happen with -off:globopt
  6801. return;
  6802. }
  6803. }
  6804. bool
  6805. BackwardPass::CheckWriteThroughSymInRegion(Region* region, StackSym* sym)
  6806. {
  6807. if (region->GetType() == RegionTypeRoot || region->GetType() == RegionTypeFinally)
  6808. {
  6809. return false;
  6810. }
  6811. // if the current region is a try region, check in its write-through set,
  6812. // otherwise (current = catch region) look in the first try ancestor's write-through set
  6813. Region * selfOrFirstTryAncestor = region->GetSelfOrFirstTryAncestor();
  6814. if (!selfOrFirstTryAncestor)
  6815. {
  6816. return false;
  6817. }
  6818. Assert(selfOrFirstTryAncestor->GetType() == RegionTypeTry);
  6819. return selfOrFirstTryAncestor->writeThroughSymbolsSet && selfOrFirstTryAncestor->writeThroughSymbolsSet->Test(sym->m_id);
  6820. }
  6821. bool
  6822. BackwardPass::DoDeadStoreLdStForMemop(IR::Instr *instr)
  6823. {
  6824. Assert(this->tag == Js::DeadStorePhase && this->currentBlock->loop != nullptr);
  6825. Loop *loop = this->currentBlock->loop;
  6826. if (globOpt->HasMemOp(loop))
  6827. {
  6828. if (instr->m_opcode == Js::OpCode::StElemI_A && instr->GetDst()->IsIndirOpnd())
  6829. {
  6830. SymID base = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6831. SymID index = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6832. FOREACH_MEMOP_CANDIDATES(candidate, loop)
  6833. {
  6834. if (base == candidate->base && index == candidate->index)
  6835. {
  6836. return true;
  6837. }
  6838. } NEXT_MEMOP_CANDIDATE
  6839. }
  6840. else if (instr->m_opcode == Js::OpCode::LdElemI_A && instr->GetSrc1()->IsIndirOpnd())
  6841. {
  6842. SymID base = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6843. SymID index = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6844. FOREACH_MEMCOPY_CANDIDATES(candidate, loop)
  6845. {
  6846. if (base == candidate->ldBase && index == candidate->index)
  6847. {
  6848. return true;
  6849. }
  6850. } NEXT_MEMCOPY_CANDIDATE
  6851. }
  6852. }
  6853. return false;
  6854. }
  6855. void
  6856. BackwardPass::RestoreInductionVariableValuesAfterMemOp(Loop *loop)
  6857. {
  6858. const auto RestoreInductionVariable = [&](SymID symId, Loop::InductionVariableChangeInfo inductionVariableChangeInfo, Loop *loop)
  6859. {
  6860. Js::OpCode opCode = Js::OpCode::Add_I4;
  6861. if (!inductionVariableChangeInfo.isIncremental)
  6862. {
  6863. opCode = Js::OpCode::Sub_I4;
  6864. }
  6865. Func *localFunc = loop->GetFunc();
  6866. StackSym *sym = localFunc->m_symTable->FindStackSym(symId)->GetInt32EquivSym(localFunc);
  6867. IR::Opnd *inductionVariableOpnd = IR::RegOpnd::New(sym, IRType::TyInt32, localFunc);
  6868. IR::Opnd *sizeOpnd = globOpt->GenerateInductionVariableChangeForMemOp(loop, inductionVariableChangeInfo.unroll);
  6869. loop->landingPad->InsertAfter(IR::Instr::New(opCode, inductionVariableOpnd, inductionVariableOpnd, sizeOpnd, loop->GetFunc()));
  6870. };
  6871. for (auto it = loop->memOpInfo->inductionVariableChangeInfoMap->GetIterator(); it.IsValid(); it.MoveNext())
  6872. {
  6873. Loop::InductionVariableChangeInfo iv = it.CurrentValue();
  6874. SymID sym = it.CurrentKey();
  6875. if (iv.unroll != Js::Constants::InvalidLoopUnrollFactor)
  6876. {
  6877. // if the variable is being used after the loop restore it
  6878. if (loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(sym))
  6879. {
  6880. RestoreInductionVariable(sym, iv, loop);
  6881. }
  6882. }
  6883. }
  6884. }
  6885. bool
  6886. BackwardPass::IsEmptyLoopAfterMemOp(Loop *loop)
  6887. {
  6888. if (globOpt->HasMemOp(loop))
  6889. {
  6890. const auto IsInductionVariableUse = [&](IR::Opnd *opnd) -> bool
  6891. {
  6892. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  6893. return (opnd &&
  6894. opnd->GetStackSym() &&
  6895. loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(this->globOpt->GetVarSymID(opnd->GetStackSym())) &&
  6896. (((Loop::InductionVariableChangeInfo)
  6897. loop->memOpInfo->inductionVariableChangeInfoMap->
  6898. LookupWithKey(this->globOpt->GetVarSymID(opnd->GetStackSym()), inductionVariableChangeInfo)).unroll != Js::Constants::InvalidLoopUnrollFactor));
  6899. };
  6900. Assert(loop->blockList.HasTwo());
  6901. FOREACH_BLOCK_IN_LOOP(bblock, loop)
  6902. {
  6903. FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrPrev, bblock)
  6904. {
  6905. if (instr->IsLabelInstr() || !instr->IsRealInstr() || instr->m_opcode == Js::OpCode::IncrLoopBodyCount || instr->m_opcode == Js::OpCode::StLoopBodyCount
  6906. || (instr->IsBranchInstr() && instr->AsBranchInstr()->IsUnconditional()))
  6907. {
  6908. continue;
  6909. }
  6910. else
  6911. {
  6912. switch (instr->m_opcode)
  6913. {
  6914. case Js::OpCode::Nop:
  6915. break;
  6916. case Js::OpCode::Ld_I4:
  6917. case Js::OpCode::Add_I4:
  6918. case Js::OpCode::Sub_I4:
  6919. if (!IsInductionVariableUse(instr->GetDst()))
  6920. {
  6921. Assert(instr->GetDst());
  6922. if (instr->GetDst()->GetStackSym()
  6923. && loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(globOpt->GetVarSymID(instr->GetDst()->GetStackSym())))
  6924. {
  6925. // We have use after the loop for a variable defined inside the loop. So the loop can't be removed.
  6926. return false;
  6927. }
  6928. }
  6929. break;
  6930. case Js::OpCode::Decr_A:
  6931. case Js::OpCode::Incr_A:
  6932. if (!IsInductionVariableUse(instr->GetSrc1()))
  6933. {
  6934. return false;
  6935. }
  6936. break;
  6937. default:
  6938. if (instr->IsBranchInstr())
  6939. {
  6940. if (IsInductionVariableUse(instr->GetSrc1()) || IsInductionVariableUse(instr->GetSrc2()))
  6941. {
  6942. break;
  6943. }
  6944. }
  6945. return false;
  6946. }
  6947. }
  6948. }
  6949. NEXT_INSTR_IN_BLOCK_EDITING;
  6950. }NEXT_BLOCK_IN_LIST;
  6951. return true;
  6952. }
  6953. return false;
  6954. }
  6955. void
  6956. BackwardPass::RemoveEmptyLoops()
  6957. {
  6958. if (PHASE_OFF(Js::MemOpPhase, this->func))
  6959. {
  6960. return;
  6961. }
  6962. const auto DeleteMemOpInfo = [&](Loop *loop)
  6963. {
  6964. JitArenaAllocator *alloc = this->func->GetTopFunc()->m_fg->alloc;
  6965. if (!loop->memOpInfo)
  6966. {
  6967. return;
  6968. }
  6969. if (loop->memOpInfo->candidates)
  6970. {
  6971. loop->memOpInfo->candidates->Clear();
  6972. JitAdelete(alloc, loop->memOpInfo->candidates);
  6973. }
  6974. if (loop->memOpInfo->inductionVariableChangeInfoMap)
  6975. {
  6976. loop->memOpInfo->inductionVariableChangeInfoMap->Clear();
  6977. JitAdelete(alloc, loop->memOpInfo->inductionVariableChangeInfoMap);
  6978. }
  6979. if (loop->memOpInfo->inductionVariableOpndPerUnrollMap)
  6980. {
  6981. loop->memOpInfo->inductionVariableOpndPerUnrollMap->Clear();
  6982. JitAdelete(alloc, loop->memOpInfo->inductionVariableOpndPerUnrollMap);
  6983. }
  6984. if (loop->memOpInfo->inductionVariablesUsedAfterLoop)
  6985. {
  6986. JitAdelete(this->tempAlloc, loop->memOpInfo->inductionVariablesUsedAfterLoop);
  6987. }
  6988. JitAdelete(alloc, loop->memOpInfo);
  6989. };
  6990. FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
  6991. {
  6992. if (IsEmptyLoopAfterMemOp(loop))
  6993. {
  6994. RestoreInductionVariableValuesAfterMemOp(loop);
  6995. RemoveEmptyLoopAfterMemOp(loop);
  6996. }
  6997. // Remove memop info as we don't need them after this point.
  6998. DeleteMemOpInfo(loop);
  6999. } NEXT_LOOP_IN_FUNC_EDITING;
  7000. }
  7001. void
  7002. BackwardPass::RemoveEmptyLoopAfterMemOp(Loop *loop)
  7003. {
  7004. BasicBlock *head = loop->GetHeadBlock();
  7005. BasicBlock *tail = head->next;
  7006. BasicBlock *landingPad = loop->landingPad;
  7007. BasicBlock *outerBlock = nullptr;
  7008. SListBaseCounted<FlowEdge *> *succList = head->GetSuccList();
  7009. Assert(succList->HasTwo());
  7010. // Between the two successors of head, one is tail and the other one is the outerBlock
  7011. SListBaseCounted<FlowEdge *>::Iterator iter(succList);
  7012. iter.Next();
  7013. if (iter.Data()->GetSucc() == tail)
  7014. {
  7015. iter.Next();
  7016. outerBlock = iter.Data()->GetSucc();
  7017. }
  7018. else
  7019. {
  7020. outerBlock = iter.Data()->GetSucc();
  7021. #ifdef DBG
  7022. iter.Next();
  7023. Assert(iter.Data()->GetSucc() == tail);
  7024. #endif
  7025. }
  7026. outerBlock->RemovePred(head, this->func->m_fg);
  7027. landingPad->RemoveSucc(head, this->func->m_fg);
  7028. this->func->m_fg->AddEdge(landingPad, outerBlock);
  7029. this->func->m_fg->RemoveBlock(head, nullptr);
  7030. if (head != tail)
  7031. {
  7032. this->func->m_fg->RemoveBlock(tail, nullptr);
  7033. }
  7034. }
  7035. #if DBG_DUMP
  7036. bool
  7037. BackwardPass::IsTraceEnabled() const
  7038. {
  7039. return
  7040. Js::Configuration::Global.flags.Trace.IsEnabled(tag, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()) &&
  7041. (PHASE_TRACE(Js::SimpleJitPhase, func) || !func->IsSimpleJit());
  7042. }
  7043. #endif