BackwardPass.cpp 357 KB

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