FlowGraph.cpp 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516
  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. FlowGraph *
  7. FlowGraph::New(Func * func, JitArenaAllocator * alloc)
  8. {
  9. FlowGraph * graph;
  10. graph = JitAnew(alloc, FlowGraph, func, alloc);
  11. return graph;
  12. }
  13. // When there is an early exit within an EH region,
  14. // Leave instructions are inserted in the bytecode to jump up the region tree one by one
  15. // We delete this Leave chain of instructions, and add an edge to Finally
  16. IR::LabelInstr * FlowGraph::DeleteLeaveChainBlocks(IR::BranchInstr *leaveInstr, IR::Instr * &instrPrev)
  17. {
  18. // Cleanup Rest of the Leave chain
  19. IR::LabelInstr * leaveTarget = leaveInstr->GetTarget();
  20. Assert(leaveTarget->GetNextBranchOrLabel()->IsBranchInstr());
  21. IR::BranchInstr *leaveChain = leaveTarget->GetNextBranchOrLabel()->AsBranchInstr();
  22. IR::LabelInstr * curLabel = leaveTarget->AsLabelInstr();
  23. while (leaveChain->m_opcode != Js::OpCode::Br)
  24. {
  25. Assert(leaveChain->m_opcode == Js::OpCode::Leave || leaveChain->m_opcode == Js::OpCode::BrOnException);
  26. IR::Instr * nextLabel = leaveChain->GetNextRealInstrOrLabel();
  27. if (!nextLabel->GetNextRealInstrOrLabel()->IsBranchInstr())
  28. {
  29. // For jit loop bodies - we can encounter ProfiledLoopEnd before every early return
  30. Assert(nextLabel->GetNextRealInstrOrLabel()->m_opcode == Js::OpCode::ProfiledLoopEnd);
  31. IR::Instr * loopEnd = nextLabel->GetNextRealInstrOrLabel();
  32. while (!loopEnd->GetNextRealInstrOrLabel()->IsBranchInstr())
  33. {
  34. Assert(loopEnd->m_opcode == Js::OpCode::ProfiledLoopEnd);
  35. loopEnd = loopEnd->GetNextRealInstrOrLabel();
  36. }
  37. leaveChain = loopEnd->GetNextRealInstrOrLabel()->AsBranchInstr();
  38. }
  39. else
  40. {
  41. leaveChain = nextLabel->GetNextRealInstrOrLabel()->AsBranchInstr();
  42. }
  43. BasicBlock *curBlock = curLabel->GetBasicBlock();
  44. this->RemoveBlock(curBlock);
  45. curLabel = nextLabel->AsLabelInstr();
  46. }
  47. instrPrev = leaveChain->m_next;
  48. IR::LabelInstr * exitLabel = leaveChain->GetTarget();
  49. BasicBlock * curBlock = curLabel->GetBasicBlock();
  50. this->RemoveBlock(curBlock);
  51. return exitLabel;
  52. }
  53. bool FlowGraph::Dominates(Region *region1, Region *region2)
  54. {
  55. Assert(region1);
  56. Assert(region2);
  57. Region *startR1 = region1;
  58. Region *startR2 = region2;
  59. int region1Depth = 0;
  60. while (startR1 != nullptr)
  61. {
  62. region1Depth++;
  63. startR1 = startR1->GetParent();
  64. }
  65. int region2Depth = 0;
  66. while (startR2 != nullptr)
  67. {
  68. region2Depth++;
  69. startR2 = startR2->GetParent();
  70. }
  71. return region1Depth > region2Depth;
  72. }
  73. bool FlowGraph::DoesExitLabelDominate(IR::BranchInstr *leaveInstr)
  74. {
  75. IR::LabelInstr * leaveTarget = leaveInstr->GetTarget();
  76. Assert(leaveTarget->GetNextRealInstr()->IsBranchInstr() || leaveTarget->GetNextRealInstr()->m_opcode == Js::OpCode::ProfiledLoopEnd);
  77. IR::BranchInstr *leaveChain = leaveTarget->GetNextBranchOrLabel()->AsBranchInstr();
  78. while (leaveChain->m_opcode != Js::OpCode::Br)
  79. {
  80. Assert(leaveChain->m_opcode == Js::OpCode::Leave || leaveChain->m_opcode == Js::OpCode::BrOnException);
  81. IR::LabelInstr * nextLabel = leaveChain->m_next->AsLabelInstr();
  82. if (!nextLabel->m_next->IsBranchInstr())
  83. {
  84. // For jit loop bodies - we can encounter ProfiledLoopEnd before every early return
  85. Assert(nextLabel->m_next->m_opcode == Js::OpCode::ProfiledLoopEnd);
  86. break;
  87. }
  88. leaveChain = nextLabel->m_next->AsBranchInstr();
  89. }
  90. IR::LabelInstr * exitLabel = leaveChain->GetTarget();
  91. return Dominates(exitLabel->GetRegion(), finallyLabelStack->Top()->GetRegion());
  92. }
  93. bool FlowGraph::CheckIfEarlyExitAndAddEdgeToFinally(IR::BranchInstr *leaveInstr, Region *currentRegion, Region *branchTargetRegion, IR::Instr * &instrPrev, IR::LabelInstr * &exitLabel)
  94. {
  95. if (finallyLabelStack->Empty())
  96. {
  97. return false;
  98. }
  99. if (currentRegion->GetType() == RegionTypeTry)
  100. {
  101. if (currentRegion->GetMatchingCatchRegion() == nullptr)
  102. {
  103. // try of try-finally
  104. bool isEarly =
  105. (branchTargetRegion != currentRegion->GetMatchingFinallyRegion(false) &&
  106. branchTargetRegion != currentRegion->GetMatchingFinallyRegion(true));
  107. if (!isEarly) return false;
  108. if (DoesExitLabelDominate(leaveInstr)) return false;
  109. // Cleanup Rest of the Leave chain
  110. exitLabel = DeleteLeaveChainBlocks(leaveInstr, instrPrev);
  111. return true;
  112. }
  113. // try of try-catch
  114. IR::BranchInstr *leaveChain = leaveInstr;
  115. IR::LabelInstr * leaveTarget = leaveChain->GetTarget();
  116. IR::Instr *target = leaveTarget->GetNextRealInstr();
  117. if (target->m_opcode == Js::OpCode::Br)
  118. {
  119. IR::BranchInstr *tryExit = target->AsBranchInstr();
  120. instrPrev = tryExit;
  121. return false;
  122. }
  123. if (DoesExitLabelDominate(leaveInstr)) return false;
  124. // Cleanup Rest of the Leave chain
  125. exitLabel = DeleteLeaveChainBlocks(leaveInstr, instrPrev);
  126. return true;
  127. }
  128. if (currentRegion->GetType() == RegionTypeCatch)
  129. {
  130. // We don't care for early exits in catch blocks, because we bailout anyway
  131. return false;
  132. }
  133. Assert(currentRegion->GetType() == RegionTypeFinally);
  134. // All Leave's inside Finally region are early exits
  135. // Since we execute non-excepting Finallys in JIT now, we should convert Leave to Br
  136. if (DoesExitLabelDominate(leaveInstr)) return false;
  137. exitLabel = DeleteLeaveChainBlocks(leaveInstr, instrPrev);
  138. return true;
  139. }
  140. ///----------------------------------------------------------------------------
  141. ///
  142. /// FlowGraph::Build
  143. ///
  144. /// Construct flow graph and loop structures for the current state of the function.
  145. ///
  146. ///----------------------------------------------------------------------------
  147. void
  148. FlowGraph::Build(void)
  149. {
  150. Func * func = this->func;
  151. BEGIN_CODEGEN_PHASE(func, Js::FGPeepsPhase);
  152. this->RunPeeps();
  153. END_CODEGEN_PHASE(func, Js::FGPeepsPhase);
  154. bool assignRegionsBeforeGlobopt = this->func->HasTry() && (this->func->DoOptimizeTry() ||
  155. (this->func->IsSimpleJit() && this->func->hasBailout) ||
  156. this->func->IsLoopBodyInTryFinally());
  157. bool createNonExceptionFinally = this->func->HasFinally() && (this->func->DoOptimizeTry() ||
  158. (this->func->IsSimpleJit() && this->func->hasBailout));
  159. // We don't optimize fully with SimpleJit. But, when JIT loop body is enabled, we do support
  160. // bailing out from a simple jitted function to do a full jit of a loop body in the function
  161. // (BailOnSimpleJitToFullJitLoopBody). For that purpose, we need the flow from try to handler.
  162. // We also need accurate flow when we are jitting a loop body and have a tryfinally, because we could be inserting BailOutOnEarlyExit
  163. if (assignRegionsBeforeGlobopt)
  164. {
  165. this->catchLabelStack = JitAnew(this->alloc, SList<IR::LabelInstr*>, this->alloc);
  166. }
  167. if (this->func->HasFinally() && assignRegionsBeforeGlobopt)
  168. {
  169. this->finallyLabelStack = JitAnew(this->alloc, SList<IR::LabelInstr*>, this->alloc);
  170. this->regToFinallyEndMap = JitAnew(this->alloc, RegionToFinallyEndMapType, this->alloc, 0);
  171. }
  172. IR::Instr * currLastInstr = nullptr;
  173. BasicBlock * currBlock = nullptr;
  174. BasicBlock * nextBlock = nullptr;
  175. bool hasCall = false;
  176. FOREACH_INSTR_IN_FUNC_BACKWARD_EDITING(instr, instrPrev, func)
  177. {
  178. if (currLastInstr == nullptr || instr->EndsBasicBlock())
  179. {
  180. // Start working on a new block.
  181. // If we're currently processing a block, then wrap it up before beginning a new one.
  182. if (currLastInstr != nullptr)
  183. {
  184. nextBlock = currBlock;
  185. currBlock = this->AddBlock(instr->m_next, currLastInstr, nextBlock);
  186. currBlock->hasCall = hasCall;
  187. hasCall = false;
  188. }
  189. currLastInstr = instr;
  190. }
  191. if (instr->StartsBasicBlock())
  192. {
  193. // Insert a BrOnException after the loop top if we are in a try-catch/try-finally. This is required to
  194. // model flow from the loop to the catch/finally block for loops that don't have a break condition.
  195. if (instr->IsLabelInstr() && instr->AsLabelInstr()->m_isLoopTop && instr->m_next->m_opcode != Js::OpCode::BrOnException)
  196. {
  197. IR::BranchInstr * brOnException = nullptr;
  198. IR::Instr *instrNext = instr->m_next;
  199. if (this->catchLabelStack && !this->catchLabelStack->Empty())
  200. {
  201. brOnException = IR::BranchInstr::New(Js::OpCode::BrOnException, this->catchLabelStack->Top(), instr->m_func);
  202. instr->InsertAfter(brOnException);
  203. }
  204. if (this->finallyLabelStack && !this->finallyLabelStack->Empty())
  205. {
  206. brOnException = IR::BranchInstr::New(Js::OpCode::BrOnException, this->finallyLabelStack->Top(), instr->m_func);
  207. instr->InsertAfter(brOnException);
  208. }
  209. if (brOnException)
  210. {
  211. instrPrev = instrNext->m_prev;
  212. continue;
  213. }
  214. }
  215. // Wrap up the current block and get ready to process a new one.
  216. nextBlock = currBlock;
  217. currBlock = this->AddBlock(instr, currLastInstr, nextBlock);
  218. currBlock->hasCall = hasCall;
  219. hasCall = false;
  220. currLastInstr = nullptr;
  221. }
  222. switch (instr->m_opcode)
  223. {
  224. case Js::OpCode::Catch:
  225. Assert(instr->m_prev->IsLabelInstr());
  226. if (this->catchLabelStack)
  227. {
  228. this->catchLabelStack->Push(instr->m_prev->AsLabelInstr());
  229. }
  230. break;
  231. case Js::OpCode::Finally:
  232. {
  233. if (!this->finallyLabelStack)
  234. {
  235. break;
  236. }
  237. //To enable globopt on functions with try finallys we transform the flowgraph as below :
  238. // TryFinally L1
  239. // <try code>
  240. // Leave L2
  241. // L2 : Br L3
  242. // L1 : Finally
  243. // <finally code>
  244. // LeaveNull
  245. // L3 : <code after try finally>
  246. //
  247. //to:
  248. //
  249. // TryFinally L1
  250. // <try code>
  251. // BrOnException L1
  252. // Leave L2
  253. // L1 : BailOnException
  254. // L2 : Finally
  255. // <finally code>
  256. // LeaveNull
  257. // L3: <code after try finally>
  258. //We generate 2 flow edges from the try - an exception path and a non exception path.
  259. //This transformation enables us to optimize on the non-excepting finally path
  260. Assert(instr->m_prev->IsLabelInstr());
  261. IR::LabelInstr * finallyLabel = instr->m_prev->AsLabelInstr();
  262. this->finallyLabelStack->Push(finallyLabel);
  263. if (!createNonExceptionFinally)
  264. {
  265. break;
  266. }
  267. // Find leave label
  268. Assert(finallyLabel->m_prev->m_opcode == Js::OpCode::Br && finallyLabel->m_prev->m_prev->m_opcode == Js::OpCode::Label);
  269. IR::Instr * insertPoint = finallyLabel->m_prev;
  270. IR::LabelInstr * leaveTarget = finallyLabel->m_prev->m_prev->AsLabelInstr();
  271. leaveTarget->Unlink();
  272. finallyLabel->InsertBefore(leaveTarget);
  273. finallyLabel->Unlink();
  274. insertPoint->InsertBefore(finallyLabel);
  275. // Bailout from the opcode following Finally
  276. IR::Instr * bailOnException = IR::BailOutInstr::New(Js::OpCode::BailOnException, IR::BailOutOnException, instr->m_next, instr->m_func);
  277. insertPoint->InsertBefore(bailOnException);
  278. insertPoint->Remove();
  279. Assert(leaveTarget->labelRefs.HasOne());
  280. IR::BranchInstr * brOnException = IR::BranchInstr::New(Js::OpCode::BrOnException, finallyLabel, instr->m_func);
  281. leaveTarget->labelRefs.Head()->InsertBefore(brOnException);
  282. instrPrev = instr->m_prev;
  283. }
  284. break;
  285. case Js::OpCode::TryCatch:
  286. if (this->catchLabelStack)
  287. {
  288. AssertOrFailFast(!this->catchLabelStack->Empty());
  289. this->catchLabelStack->Pop();
  290. }
  291. break;
  292. case Js::OpCode::TryFinally:
  293. if (this->finallyLabelStack)
  294. {
  295. AssertOrFailFast(!this->finallyLabelStack->Empty());
  296. this->finallyLabelStack->Pop();
  297. }
  298. break;
  299. case Js::OpCode::CloneBlockScope:
  300. case Js::OpCode::CloneInnerScopeSlots:
  301. // It would be nice to do this in IRBuilder, but doing so gives us
  302. // trouble when doing the DoSlotArrayCheck since it assume single def
  303. // of the sym to do its check properly. So instead we assign the dst
  304. // here in FlowGraph.
  305. instr->SetDst(instr->GetSrc1());
  306. break;
  307. }
  308. if (OpCodeAttr::UseAllFields(instr->m_opcode))
  309. {
  310. // UseAllFields opcode are call instruction or opcode that would call.
  311. hasCall = true;
  312. if (OpCodeAttr::CallInstr(instr->m_opcode))
  313. {
  314. if (!instr->isCallInstrProtectedByNoProfileBailout)
  315. {
  316. instr->m_func->SetHasCallsOnSelfAndParents();
  317. }
  318. // For ARM, ARM64 & X64 (non x86) because of their register calling convention
  319. // the ArgOuts need to be moved next to the call.
  320. #if !defined(_M_IX86)
  321. IR::Instr* argInsertInstr = instr;
  322. instr->IterateArgInstrs([&](IR::Instr* argInstr)
  323. {
  324. if (argInstr->m_opcode != Js::OpCode::LdSpreadIndices &&
  325. argInstr->m_opcode != Js::OpCode::ArgOut_A_Dynamic &&
  326. argInstr->m_opcode != Js::OpCode::ArgOut_A_FromStackArgs &&
  327. argInstr->m_opcode != Js::OpCode::ArgOut_A_SpreadArg)
  328. {
  329. // don't have bailout in asm.js so we don't need BytecodeArgOutCapture
  330. if (!argInstr->m_func->GetJITFunctionBody()->IsAsmJsMode())
  331. {
  332. // Need to always generate byte code arg out capture,
  333. // because bailout can't restore from the arg out as it is
  334. // replaced by new sym for register calling convention in lower
  335. argInstr->GenerateBytecodeArgOutCapture();
  336. }
  337. // Check if the instruction is already next
  338. if (argInstr != argInsertInstr->m_prev)
  339. {
  340. // It is not, move it.
  341. argInstr->Move(argInsertInstr);
  342. }
  343. argInsertInstr = argInstr;
  344. }
  345. return false;
  346. });
  347. #endif
  348. }
  349. }
  350. }
  351. NEXT_INSTR_IN_FUNC_BACKWARD_EDITING;
  352. this->func->isFlowGraphValid = true;
  353. Assert(!this->catchLabelStack || this->catchLabelStack->Empty());
  354. Assert(!this->finallyLabelStack || this->finallyLabelStack->Empty());
  355. // We've been walking backward so that edge lists would be in the right order. Now walk the blocks
  356. // forward to number the blocks in lexical order.
  357. unsigned int blockNum = 0;
  358. FOREACH_BLOCK(block, this)
  359. {
  360. block->SetBlockNum(blockNum++);
  361. }NEXT_BLOCK;
  362. AssertMsg(blockNum == this->blockCount, "Block count is out of whack");
  363. this->RemoveUnreachableBlocks();
  364. // Regions need to be assigned before Globopt because:
  365. // 1. FullJit: The Backward Pass will set the write-through symbols on the regions and the forward pass will
  366. // use this information to insert ToVars for those symbols. Also, for a symbol determined as write-through
  367. // in the try region to be restored correctly by the bailout, it should not be removed from the
  368. // byteCodeUpwardExposedUsed upon a def in the try region (the def might be preempted by an exception).
  369. //
  370. // 2. SimpleJit: Same case of correct restoration as above applies in SimpleJit too. However, the only bailout
  371. // we have in Simple Jitted code right now is BailOnSimpleJitToFullJitLoopBody, installed in IRBuilder. So,
  372. // for now, we can just check if the func has a bailout to assign regions pre globopt while running SimpleJit.
  373. blockNum = 0;
  374. FOREACH_BLOCK_ALL(block, this)
  375. {
  376. block->SetBlockNum(blockNum++);
  377. if (assignRegionsBeforeGlobopt)
  378. {
  379. if (block->isDeleted && !block->isDead)
  380. {
  381. continue;
  382. }
  383. this->UpdateRegionForBlock(block);
  384. }
  385. } NEXT_BLOCK_ALL;
  386. AssertMsg(blockNum == this->blockCount, "Block count is out of whack");
  387. #if DBG_DUMP
  388. if (PHASE_DUMP(Js::FGBuildPhase, this->GetFunc()))
  389. {
  390. if (assignRegionsBeforeGlobopt)
  391. {
  392. Output::Print(_u("Before adding early exit edges\n"));
  393. FOREACH_BLOCK_ALL(block, this)
  394. {
  395. block->DumpHeader(true);
  396. Region *region = block->GetFirstInstr()->AsLabelInstr()->GetRegion();
  397. if (region)
  398. {
  399. const char16 * regMap[] = { _u("RegionTypeInvalid"),
  400. _u("RegionTypeRoot"),
  401. _u("RegionTypeTry"),
  402. _u("RegionTypeCatch"),
  403. _u("RegionTypeFinally") };
  404. Output::Print(_u("Region %p RegionParent %p RegionType %s\n"), region, region->GetParent(), regMap[region->GetType()]);
  405. }
  406. } NEXT_BLOCK_ALL;
  407. this->func->Dump();
  408. }
  409. }
  410. #endif
  411. if (this->finallyLabelStack)
  412. {
  413. Assert(this->finallyLabelStack->Empty());
  414. if (createNonExceptionFinally)
  415. {
  416. // Add s0 definition at the beginning of the function
  417. // We need this because - s0 symbol can get added to bytcodeUpwardExposed use when there are early returns,
  418. // And globopt will complain that s0 is uninitialized, because we define it to undefined only at the end of the function
  419. const auto addrOpnd = IR::AddrOpnd::New(this->func->GetScriptContextInfo()->GetUndefinedAddr(), IR::AddrOpndKindDynamicVar, this->func, true);
  420. addrOpnd->SetValueType(ValueType::Undefined);
  421. IR::RegOpnd *regOpnd = IR::RegOpnd::New(this->func->m_symTable->FindStackSym(0), TyVar, this->func);
  422. IR::Instr *ldRet = IR::Instr::New(Js::OpCode::Ld_A, regOpnd, addrOpnd, this->func);
  423. this->func->m_headInstr->GetNextRealInstr()->InsertBefore(ldRet);
  424. }
  425. IR::LabelInstr * currentLabel = nullptr;
  426. // look for early exits from a try, and insert bailout
  427. FOREACH_INSTR_IN_FUNC_EDITING(instr, instrNext, func)
  428. {
  429. if (instr->IsLabelInstr())
  430. {
  431. currentLabel = instr->AsLabelInstr();
  432. }
  433. else if (instr->m_opcode == Js::OpCode::TryFinally)
  434. {
  435. Assert(instr->AsBranchInstr()->GetTarget()->GetRegion()->GetType() == RegionTypeFinally);
  436. this->finallyLabelStack->Push(instr->AsBranchInstr()->GetTarget());
  437. }
  438. else if (instr->m_opcode == Js::OpCode::Leave)
  439. {
  440. Assert(currentLabel != nullptr);
  441. __analysis_assume(currentLabel != nullptr);
  442. if (createNonExceptionFinally)
  443. {
  444. IR::LabelInstr *branchTarget = instr->AsBranchInstr()->GetTarget();
  445. IR::LabelInstr *exitLabel = nullptr;
  446. // An early exit (break, continue, return) from an EH region appears as Leave opcode
  447. // When there is an early exit within a try finally, we have to execute finally code
  448. // Currently we bailout on early exits
  449. // For all such edges add edge from eh region -> finally and finally -> earlyexit
  450. if (CheckIfEarlyExitAndAddEdgeToFinally(instr->AsBranchInstr(), currentLabel->GetRegion(), branchTarget->GetRegion(), instrNext, exitLabel))
  451. {
  452. Assert(exitLabel);
  453. IR::Instr * bailOnEarlyExit = IR::BailOutInstr::New(Js::OpCode::BailOnEarlyExit, IR::BailOutOnEarlyExit, instr, instr->m_func);
  454. instr->InsertBefore(bailOnEarlyExit);
  455. IR::LabelInstr *exceptFinallyLabel = this->finallyLabelStack->Top();
  456. IR::LabelInstr *nonExceptFinallyLabel = exceptFinallyLabel->m_next->m_next->AsLabelInstr();
  457. // It is possible for the finally region to have a non terminating loop, in which case the end of finally is eliminated
  458. // We can skip adding edge from finally to early exit in this case
  459. IR::Instr * leaveToFinally = IR::BranchInstr::New(Js::OpCode::Leave, exceptFinallyLabel, this->func);
  460. instr->InsertBefore(leaveToFinally);
  461. instr->Remove();
  462. this->AddEdge(currentLabel->GetBasicBlock(), exceptFinallyLabel->GetBasicBlock());
  463. if (this->regToFinallyEndMap->ContainsKey(nonExceptFinallyLabel->GetRegion()))
  464. {
  465. BasicBlock * finallyEndBlock = this->regToFinallyEndMap->Item(nonExceptFinallyLabel->GetRegion());
  466. Assert(finallyEndBlock);
  467. Assert(finallyEndBlock->GetFirstInstr()->AsLabelInstr()->GetRegion() == nonExceptFinallyLabel->GetRegion());
  468. InsertEdgeFromFinallyToEarlyExit(finallyEndBlock, exitLabel);
  469. }
  470. }
  471. else if (currentLabel->GetRegion()->GetType() == RegionTypeFinally)
  472. {
  473. Assert(currentLabel->GetRegion()->GetMatchingTryRegion()->GetMatchingFinallyRegion(false) == currentLabel->GetRegion());
  474. // Convert Leave to Br because we execute non-excepting Finally in native code
  475. instr->m_opcode = Js::OpCode::Br;
  476. #if DBG
  477. instr->AsBranchInstr()->m_leaveConvToBr = true;
  478. #endif
  479. }
  480. }
  481. else
  482. {
  483. if (currentLabel->GetRegion()->GetType() == RegionTypeRoot)
  484. {
  485. // Found an orphaned leave, should be an early return from the loop body, insert bailout
  486. Assert(instr->AsBranchInstr()->m_isOrphanedLeave);
  487. IR::Instr * bailOnEarlyExit = IR::BailOutInstr::New(Js::OpCode::BailOnEarlyExit, IR::BailOutOnEarlyExit, instr, instr->m_func);
  488. instr->InsertBefore(bailOnEarlyExit);
  489. }
  490. else if (currentLabel->GetRegion()->GetType() == RegionTypeCatch)
  491. {
  492. if (!this->finallyLabelStack->Empty())
  493. {
  494. BasicBlock *currentBlock = currentLabel->GetBasicBlock();
  495. Assert(currentBlock->GetSuccList()->Count() == 1);
  496. BasicBlock *succ = currentBlock->GetSuccList()->Head()->GetSucc();
  497. currentBlock->RemoveSucc(succ, this, true);
  498. // Add an edge to the finally block
  499. IR::BranchInstr * brOnException = IR::BranchInstr::New(Js::OpCode::BrOnException, this->finallyLabelStack->Top(), instr->m_func);
  500. instr->InsertBefore(brOnException);
  501. IR::LabelInstr * label = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  502. instr->InsertBefore(label);
  503. BasicBlock *leaveBlock = this->AddBlock(label, instr, currentBlock->GetNext(), currentBlock);
  504. // Add edge to finally block, leave block
  505. this->AddEdge(currentBlock, this->finallyLabelStack->Top()->GetBasicBlock());
  506. this->AddEdge(currentBlock, leaveBlock);
  507. }
  508. }
  509. }
  510. }
  511. else if (instr->m_opcode == Js::OpCode::Finally)
  512. {
  513. AssertOrFailFast(!this->finallyLabelStack->Empty());
  514. this->finallyLabelStack->Pop();
  515. }
  516. }
  517. NEXT_INSTR_IN_FUNC_EDITING;
  518. this->RemoveUnreachableBlocks();
  519. blockNum = 0;
  520. FOREACH_BLOCK_ALL(block, this)
  521. {
  522. block->SetBlockNum(blockNum++);
  523. } NEXT_BLOCK_ALL;
  524. }
  525. this->FindLoops();
  526. #if DBG_DUMP
  527. if (PHASE_DUMP(Js::FGBuildPhase, this->GetFunc()))
  528. {
  529. if (assignRegionsBeforeGlobopt)
  530. {
  531. Output::Print(_u("After adding early exit edges/Before CanonicalizeLoops\n"));
  532. FOREACH_BLOCK_ALL(block, this)
  533. {
  534. block->DumpHeader(true);
  535. Region *region = block->GetFirstInstr()->AsLabelInstr()->GetRegion();
  536. if (region)
  537. {
  538. const char16 * regMap[] = { _u("RegionTypeInvalid"),
  539. _u("RegionTypeRoot"),
  540. _u("RegionTypeTry"),
  541. _u("RegionTypeCatch"),
  542. _u("RegionTypeFinally") };
  543. Output::Print(_u("Region %p RegionParent %p RegionType %s\n"), region, region->GetParent(), regMap[region->GetType()]);
  544. }
  545. } NEXT_BLOCK_ALL;
  546. this->func->Dump();
  547. }
  548. }
  549. #endif
  550. bool breakBlocksRelocated = this->CanonicalizeLoops();
  551. blockNum = 0;
  552. FOREACH_BLOCK_ALL(block, this)
  553. {
  554. block->SetBlockNum(blockNum++);
  555. } NEXT_BLOCK_ALL;
  556. #if DBG
  557. FOREACH_BLOCK_ALL(block, this)
  558. {
  559. if (assignRegionsBeforeGlobopt)
  560. {
  561. if (block->GetFirstInstr()->AsLabelInstr()->GetRegion())
  562. {
  563. Assert(block->GetFirstInstr()->AsLabelInstr()->GetRegion()->ehBailoutData);
  564. }
  565. }
  566. } NEXT_BLOCK_ALL;
  567. #endif
  568. #if DBG_DUMP
  569. if (PHASE_DUMP(Js::FGBuildPhase, this->GetFunc()))
  570. {
  571. if (assignRegionsBeforeGlobopt)
  572. {
  573. Output::Print(_u("After CanonicalizeLoops\n"));
  574. FOREACH_BLOCK_ALL(block, this)
  575. {
  576. block->DumpHeader(true);
  577. Region *region = block->GetFirstInstr()->AsLabelInstr()->GetRegion();
  578. if (region)
  579. {
  580. const char16 * regMap[] = { _u("RegionTypeInvalid"),
  581. _u("RegionTypeRoot"),
  582. _u("RegionTypeTry"),
  583. _u("RegionTypeCatch"),
  584. _u("RegionTypeFinally") };
  585. Output::Print(_u("Region %p RegionParent %p RegionType %s\n"), region, region->GetParent(), regMap[region->GetType()]);
  586. }
  587. } NEXT_BLOCK_ALL;
  588. this->func->Dump();
  589. }
  590. }
  591. #endif
  592. if (breakBlocksRelocated)
  593. {
  594. // Sort loop lists only if there is break block removal.
  595. SortLoopLists();
  596. }
  597. #if DBG
  598. this->VerifyLoopGraph();
  599. #endif
  600. #if DBG_DUMP
  601. this->Dump(false, nullptr);
  602. #endif
  603. }
  604. void FlowGraph::InsertEdgeFromFinallyToEarlyExit(BasicBlock *finallyEndBlock, IR::LabelInstr *exitLabel)
  605. {
  606. IR::Instr * lastInstr = finallyEndBlock->GetLastInstr();
  607. IR::LabelInstr * lastLabel = finallyEndBlock->GetFirstInstr()->AsLabelInstr();
  608. Assert(lastInstr->m_opcode == Js::OpCode::LeaveNull || lastInstr->m_opcode == Js::OpCode::Leave || lastInstr->m_opcode == Js::OpCode::BrOnException);
  609. // Add a new block, add BrOnException to earlyexit, assign region
  610. // Finally
  611. // ...
  612. // L1:
  613. // LeaveNull
  614. // to
  615. // Finally
  616. // ...
  617. // L1:
  618. // BrOnException earlyExitLabel
  619. // L1':
  620. // LeaveNull
  621. BasicBlock *nextBB = finallyEndBlock->GetNext();
  622. IR::LabelInstr *leaveLabel = IR::LabelInstr::New(Js::OpCode::Label, this->func);
  623. lastInstr->InsertBefore(leaveLabel);
  624. this->AddBlock(leaveLabel, lastInstr, nextBB, finallyEndBlock /*prevBlock*/);
  625. leaveLabel->SetRegion(lastLabel->GetRegion());
  626. this->AddEdge(finallyEndBlock, leaveLabel->GetBasicBlock());
  627. // If the Leave/LeaveNull at the end of finally was not preceeded by a Label, we have to create a new block with BrOnException to early exit
  628. if (!lastInstr->GetPrevRealInstrOrLabel()->IsLabelInstr())
  629. {
  630. IR::LabelInstr *brLabel = IR::LabelInstr::New(Js::OpCode::Label, this->func);
  631. leaveLabel->InsertBefore(brLabel);
  632. IR::BranchInstr *brToExit = IR::BranchInstr::New(Js::OpCode::BrOnException, exitLabel, this->func);
  633. brToExit->m_brFinallyToEarlyExit = true;
  634. brToExit->SetByteCodeOffset(lastInstr);
  635. leaveLabel->InsertBefore(brToExit);
  636. this->AddBlock(brLabel, brToExit, finallyEndBlock->GetNext(), finallyEndBlock /*prevBlock*/);
  637. brLabel->SetRegion(lastLabel->GetRegion());
  638. this->AddEdge(finallyEndBlock, brLabel->GetBasicBlock());
  639. }
  640. else
  641. {
  642. // If the Leave/LeaveNull at the end of finally was preceeded by a Label, we reuse the block inserting BrOnException to early exit in it
  643. IR::BranchInstr *brToExit = IR::BranchInstr::New(Js::OpCode::BrOnException, exitLabel, this->func);
  644. brToExit->SetByteCodeOffset(lastInstr);
  645. brToExit->m_brFinallyToEarlyExit = true;
  646. leaveLabel->InsertBefore(brToExit);
  647. this->AddEdge(finallyEndBlock, exitLabel->GetBasicBlock());
  648. }
  649. // In case of throw/non-terminating loop, there maybe no edge to the next block
  650. if (this->FindEdge(finallyEndBlock, nextBB))
  651. {
  652. finallyEndBlock->RemoveSucc(nextBB, this);
  653. }
  654. this->regToFinallyEndMap->Item(lastLabel->GetRegion(), leaveLabel->GetBasicBlock());
  655. }
  656. void
  657. FlowGraph::SortLoopLists()
  658. {
  659. // Sort the blocks in loopList
  660. for (Loop *loop = this->loopList; loop; loop = loop->next)
  661. {
  662. unsigned int lastBlockNumber = loop->GetHeadBlock()->GetBlockNum();
  663. // Insertion sort as the blockList is almost sorted in the loop.
  664. FOREACH_BLOCK_IN_LOOP_EDITING(block, loop, iter)
  665. {
  666. if (lastBlockNumber <= block->GetBlockNum())
  667. {
  668. lastBlockNumber = block->GetBlockNum();
  669. }
  670. else
  671. {
  672. iter.UnlinkCurrent();
  673. FOREACH_BLOCK_IN_LOOP_EDITING(insertBlock,loop,newIter)
  674. {
  675. if (insertBlock->GetBlockNum() > block->GetBlockNum())
  676. {
  677. break;
  678. }
  679. }NEXT_BLOCK_IN_LOOP_EDITING;
  680. newIter.InsertBefore(block);
  681. }
  682. }NEXT_BLOCK_IN_LOOP_EDITING;
  683. }
  684. }
  685. void
  686. FlowGraph::RunPeeps()
  687. {
  688. if (this->func->HasTry())
  689. {
  690. return;
  691. }
  692. if (PHASE_OFF(Js::FGPeepsPhase, this->func))
  693. {
  694. return;
  695. }
  696. IR::Instr * instrCm = nullptr;
  697. bool tryUnsignedCmpPeep = false;
  698. FOREACH_INSTR_IN_FUNC_EDITING(instr, instrNext, this->func)
  699. {
  700. switch(instr->m_opcode)
  701. {
  702. case Js::OpCode::Br:
  703. case Js::OpCode::BrEq_I4:
  704. case Js::OpCode::BrGe_I4:
  705. case Js::OpCode::BrGt_I4:
  706. case Js::OpCode::BrLt_I4:
  707. case Js::OpCode::BrLe_I4:
  708. case Js::OpCode::BrUnGe_I4:
  709. case Js::OpCode::BrUnGt_I4:
  710. case Js::OpCode::BrUnLt_I4:
  711. case Js::OpCode::BrUnLe_I4:
  712. case Js::OpCode::BrNeq_I4:
  713. case Js::OpCode::BrEq_A:
  714. case Js::OpCode::BrGe_A:
  715. case Js::OpCode::BrGt_A:
  716. case Js::OpCode::BrLt_A:
  717. case Js::OpCode::BrLe_A:
  718. case Js::OpCode::BrUnGe_A:
  719. case Js::OpCode::BrUnGt_A:
  720. case Js::OpCode::BrUnLt_A:
  721. case Js::OpCode::BrUnLe_A:
  722. case Js::OpCode::BrNotEq_A:
  723. case Js::OpCode::BrNotNeq_A:
  724. case Js::OpCode::BrSrNotEq_A:
  725. case Js::OpCode::BrSrNotNeq_A:
  726. case Js::OpCode::BrNotGe_A:
  727. case Js::OpCode::BrNotGt_A:
  728. case Js::OpCode::BrNotLt_A:
  729. case Js::OpCode::BrNotLe_A:
  730. case Js::OpCode::BrNeq_A:
  731. case Js::OpCode::BrNotNull_A:
  732. case Js::OpCode::BrNotAddr_A:
  733. case Js::OpCode::BrAddr_A:
  734. case Js::OpCode::BrSrEq_A:
  735. case Js::OpCode::BrSrNeq_A:
  736. case Js::OpCode::BrOnHasProperty:
  737. case Js::OpCode::BrOnNoProperty:
  738. case Js::OpCode::BrHasSideEffects:
  739. case Js::OpCode::BrNotHasSideEffects:
  740. case Js::OpCode::BrFncEqApply:
  741. case Js::OpCode::BrFncNeqApply:
  742. case Js::OpCode::BrOnEmpty:
  743. case Js::OpCode::BrOnNotEmpty:
  744. case Js::OpCode::BrFncCachedScopeEq:
  745. case Js::OpCode::BrFncCachedScopeNeq:
  746. case Js::OpCode::BrOnObject_A:
  747. case Js::OpCode::BrOnClassConstructor:
  748. case Js::OpCode::BrOnBaseConstructorKind:
  749. if (tryUnsignedCmpPeep)
  750. {
  751. this->UnsignedCmpPeep(instr);
  752. }
  753. instrNext = Peeps::PeepBranch(instr->AsBranchInstr());
  754. break;
  755. case Js::OpCode::MultiBr:
  756. // TODO: Run peeps on these as well...
  757. break;
  758. case Js::OpCode::BrTrue_I4:
  759. case Js::OpCode::BrFalse_I4:
  760. case Js::OpCode::BrTrue_A:
  761. case Js::OpCode::BrFalse_A:
  762. if (instrCm)
  763. {
  764. if (instrCm->GetDst()->IsInt32())
  765. {
  766. Assert(instr->m_opcode == Js::OpCode::BrTrue_I4 || instr->m_opcode == Js::OpCode::BrFalse_I4);
  767. instrNext = this->PeepTypedCm(instrCm);
  768. }
  769. else
  770. {
  771. instrNext = this->PeepCm(instrCm);
  772. }
  773. instrCm = nullptr;
  774. if (instrNext == nullptr)
  775. {
  776. // Set instrNext back to the current instr.
  777. instrNext = instr;
  778. }
  779. }
  780. else
  781. {
  782. instrNext = Peeps::PeepBranch(instr->AsBranchInstr());
  783. }
  784. break;
  785. case Js::OpCode::CmEq_I4:
  786. case Js::OpCode::CmGe_I4:
  787. case Js::OpCode::CmGt_I4:
  788. case Js::OpCode::CmLt_I4:
  789. case Js::OpCode::CmLe_I4:
  790. case Js::OpCode::CmNeq_I4:
  791. case Js::OpCode::CmEq_A:
  792. case Js::OpCode::CmGe_A:
  793. case Js::OpCode::CmGt_A:
  794. case Js::OpCode::CmLt_A:
  795. case Js::OpCode::CmLe_A:
  796. case Js::OpCode::CmNeq_A:
  797. case Js::OpCode::CmSrEq_A:
  798. case Js::OpCode::CmSrNeq_A:
  799. if (tryUnsignedCmpPeep)
  800. {
  801. this->UnsignedCmpPeep(instr);
  802. }
  803. case Js::OpCode::CmUnGe_I4:
  804. case Js::OpCode::CmUnGt_I4:
  805. case Js::OpCode::CmUnLt_I4:
  806. case Js::OpCode::CmUnLe_I4:
  807. case Js::OpCode::CmUnGe_A:
  808. case Js::OpCode::CmUnGt_A:
  809. case Js::OpCode::CmUnLt_A:
  810. case Js::OpCode::CmUnLe_A:
  811. // There may be useless branches between the Cm instr and the branch that uses the result.
  812. // So save the last Cm instr seen, and trigger the peep on the next BrTrue/BrFalse.
  813. instrCm = instr;
  814. break;
  815. case Js::OpCode::Label:
  816. if (instr->AsLabelInstr()->IsUnreferenced())
  817. {
  818. instrNext = Peeps::PeepUnreachableLabel(instr->AsLabelInstr(), false);
  819. }
  820. break;
  821. case Js::OpCode::StatementBoundary:
  822. instr->ClearByteCodeOffset();
  823. instr->SetByteCodeOffset(instr->GetNextRealInstrOrLabel());
  824. break;
  825. case Js::OpCode::ShrU_I4:
  826. case Js::OpCode::ShrU_A:
  827. if (tryUnsignedCmpPeep)
  828. {
  829. break;
  830. }
  831. if (instr->GetDst()->AsRegOpnd()->m_sym->IsSingleDef()
  832. && instr->GetSrc2()->IsRegOpnd() && instr->GetSrc2()->AsRegOpnd()->m_sym->IsTaggableIntConst()
  833. && instr->GetSrc2()->AsRegOpnd()->m_sym->GetIntConstValue() == 0)
  834. {
  835. tryUnsignedCmpPeep = true;
  836. }
  837. break;
  838. default:
  839. Assert(!instr->IsBranchInstr());
  840. }
  841. } NEXT_INSTR_IN_FUNC_EDITING;
  842. }
  843. void
  844. Loop::InsertLandingPad(FlowGraph *fg)
  845. {
  846. BasicBlock *headBlock = this->GetHeadBlock();
  847. // Always create a landing pad. This allows globopt to easily hoist instructions
  848. // and re-optimize the block if needed.
  849. BasicBlock *landingPad = BasicBlock::New(fg);
  850. this->landingPad = landingPad;
  851. IR::Instr * headInstr = headBlock->GetFirstInstr();
  852. IR::LabelInstr *landingPadLabel = IR::LabelInstr::New(Js::OpCode::Label, headInstr->m_func);
  853. landingPadLabel->SetByteCodeOffset(headInstr);
  854. headInstr->InsertBefore(landingPadLabel);
  855. landingPadLabel->SetBasicBlock(landingPad);
  856. landingPadLabel->SetRegion(headBlock->GetFirstInstr()->AsLabelInstr()->GetRegion());
  857. landingPadLabel->m_hasNonBranchRef = headBlock->GetFirstInstr()->AsLabelInstr()->m_hasNonBranchRef;
  858. landingPad->SetBlockNum(fg->blockCount++);
  859. landingPad->SetFirstInstr(landingPadLabel);
  860. landingPad->SetLastInstr(landingPadLabel);
  861. landingPad->prev = headBlock->prev;
  862. landingPad->prev->next = landingPad;
  863. landingPad->next = headBlock;
  864. headBlock->prev = landingPad;
  865. Loop *parentLoop = this->parent;
  866. landingPad->loop = parentLoop;
  867. // We need to add this block to the block list of the parent loops
  868. while (parentLoop)
  869. {
  870. // Find the head block in the block list of the parent loop
  871. FOREACH_BLOCK_IN_LOOP_EDITING(block, parentLoop, iter)
  872. {
  873. if (block == headBlock)
  874. {
  875. // Add the landing pad to the block list
  876. iter.InsertBefore(landingPad);
  877. break;
  878. }
  879. } NEXT_BLOCK_IN_LOOP_EDITING;
  880. parentLoop = parentLoop->parent;
  881. }
  882. // Fix predecessor flow edges
  883. FOREACH_PREDECESSOR_EDGE_EDITING(edge, headBlock, iter)
  884. {
  885. // Make sure it isn't a back-edge
  886. if (edge->GetPred()->loop != this && !this->IsDescendentOrSelf(edge->GetPred()->loop))
  887. {
  888. if (edge->GetPred()->GetLastInstr()->IsBranchInstr() && headBlock->GetFirstInstr()->IsLabelInstr())
  889. {
  890. IR::BranchInstr *branch = edge->GetPred()->GetLastInstr()->AsBranchInstr();
  891. branch->ReplaceTarget(headBlock->GetFirstInstr()->AsLabelInstr(), landingPadLabel);
  892. }
  893. headBlock->UnlinkPred(edge->GetPred(), false);
  894. landingPad->AddPred(edge, fg);
  895. edge->SetSucc(landingPad);
  896. }
  897. } NEXT_PREDECESSOR_EDGE_EDITING;
  898. fg->AddEdge(landingPad, headBlock);
  899. if (headBlock->GetFirstInstr()->AsLabelInstr()->GetRegion() && headBlock->GetFirstInstr()->AsLabelInstr()->GetRegion()->GetType() != RegionTypeRoot)
  900. {
  901. landingPadLabel->m_hasNonBranchRef = true;
  902. }
  903. }
  904. bool
  905. Loop::RemoveBreakBlocks(FlowGraph *fg)
  906. {
  907. bool breakBlockRelocated = false;
  908. if (PHASE_OFF(Js::RemoveBreakBlockPhase, fg->GetFunc()))
  909. {
  910. return false;
  911. }
  912. BasicBlock *loopTailBlock = nullptr;
  913. FOREACH_BLOCK_IN_LOOP(block, this)
  914. {
  915. loopTailBlock = block;
  916. }NEXT_BLOCK_IN_LOOP;
  917. AnalysisAssert(loopTailBlock);
  918. FOREACH_BLOCK_BACKWARD_IN_RANGE_EDITING(breakBlockEnd, loopTailBlock, this->GetHeadBlock(), blockPrev)
  919. {
  920. while (!this->IsDescendentOrSelf(breakBlockEnd->loop))
  921. {
  922. // Found at least one break block;
  923. breakBlockRelocated = true;
  924. #if DBG
  925. breakBlockEnd->isBreakBlock = true;
  926. #endif
  927. // Find the first block in this break block sequence.
  928. BasicBlock *breakBlockStart = breakBlockEnd;
  929. BasicBlock *breakBlockStartPrev = breakBlockEnd->GetPrev();
  930. // Walk back the blocks until we find a block which belongs to that block.
  931. // Note: We don't really care if there are break blocks corresponding to different loops. We move the blocks conservatively to the end of the loop.
  932. // Algorithm works on one loop at a time.
  933. while((breakBlockStartPrev->loop == breakBlockEnd->loop) || !this->IsDescendentOrSelf(breakBlockStartPrev->loop))
  934. {
  935. breakBlockStart = breakBlockStartPrev;
  936. breakBlockStartPrev = breakBlockStartPrev->GetPrev();
  937. }
  938. #if DBG
  939. breakBlockStart->isBreakBlock = true; // Mark the first block as well.
  940. #endif
  941. BasicBlock *exitLoopTail = loopTailBlock;
  942. // Move these break blocks to the tail of the loop.
  943. fg->MoveBlocksBefore(breakBlockStart, breakBlockEnd, exitLoopTail->next);
  944. #if DBG_DUMP
  945. fg->Dump(true /*needs verbose flag*/, _u("\n After Each iteration of canonicalization \n"));
  946. #endif
  947. // Again be conservative, there are edits to the loop graph. Start fresh for this loop.
  948. breakBlockEnd = loopTailBlock;
  949. blockPrev = breakBlockEnd->prev;
  950. }
  951. } NEXT_BLOCK_BACKWARD_IN_RANGE_EDITING;
  952. return breakBlockRelocated;
  953. }
  954. void
  955. FlowGraph::MoveBlocksBefore(BasicBlock *blockStart, BasicBlock *blockEnd, BasicBlock *insertBlock)
  956. {
  957. BasicBlock *srcPredBlock = blockStart->prev;
  958. BasicBlock *srcNextBlock = blockEnd->next;
  959. BasicBlock *dstPredBlock = insertBlock->prev;
  960. IR::Instr* dstPredBlockLastInstr = dstPredBlock->GetLastInstr();
  961. IR::Instr* blockEndLastInstr = blockEnd->GetLastInstr();
  962. // Fix block linkage
  963. srcPredBlock->next = srcNextBlock;
  964. srcNextBlock->prev = srcPredBlock;
  965. dstPredBlock->next = blockStart;
  966. insertBlock->prev = blockEnd;
  967. blockStart->prev = dstPredBlock;
  968. blockEnd->next = insertBlock;
  969. // Fix instruction linkage
  970. IR::Instr::MoveRangeAfter(blockStart->GetFirstInstr(), blockEndLastInstr, dstPredBlockLastInstr);
  971. // Fix instruction flow
  972. IR::Instr *srcLastInstr = srcPredBlock->GetLastInstr();
  973. if (srcLastInstr->IsBranchInstr() && srcLastInstr->AsBranchInstr()->HasFallThrough())
  974. {
  975. // There was a fallthrough in the break blocks original position.
  976. IR::BranchInstr *srcBranch = srcLastInstr->AsBranchInstr();
  977. IR::Instr *srcBranchNextInstr = srcBranch->GetNextRealInstrOrLabel();
  978. // Save the target and invert the branch.
  979. IR::LabelInstr *srcBranchTarget = srcBranch->GetTarget();
  980. srcPredBlock->InvertBranch(srcBranch);
  981. IR::LabelInstr *srcLabel = blockStart->GetFirstInstr()->AsLabelInstr();
  982. // Point the inverted branch to break block.
  983. srcBranch->SetTarget(srcLabel);
  984. if (srcBranchNextInstr != srcBranchTarget)
  985. {
  986. FlowEdge *srcEdge = this->FindEdge(srcPredBlock, srcBranchTarget->GetBasicBlock());
  987. Assert(srcEdge);
  988. BasicBlock *compensationBlock = this->InsertCompensationCodeForBlockMove(srcEdge, true /*insert compensation block to loop list*/, false /*At source*/);
  989. Assert(compensationBlock);
  990. }
  991. }
  992. IR::Instr *dstLastInstr = dstPredBlockLastInstr;
  993. bool assignRegionsBeforeGlobopt = this->func->HasTry() && (this->func->DoOptimizeTry() ||
  994. (this->func->IsSimpleJit() && this->func->hasBailout) ||
  995. this->func->IsLoopBodyInTryFinally());
  996. if (dstLastInstr->IsBranchInstr() && dstLastInstr->AsBranchInstr()->HasFallThrough())
  997. {
  998. //There is a fallthrough in the block after which break block is inserted.
  999. FlowEdge *dstEdge = this->FindEdge(dstPredBlock, blockEnd->GetNext());
  1000. Assert(dstEdge);
  1001. BasicBlock *compensationBlock = this->InsertCompensationCodeForBlockMove(dstEdge, true /*insert compensation block to loop list*/, true /*At sink*/);
  1002. Assert(compensationBlock);
  1003. }
  1004. // We have to update region info for blocks whose predecessors changed
  1005. if (assignRegionsBeforeGlobopt)
  1006. {
  1007. UpdateRegionForBlockFromEHPred(dstPredBlock, true);
  1008. UpdateRegionForBlockFromEHPred(blockStart, true);
  1009. UpdateRegionForBlockFromEHPred(srcNextBlock, true);
  1010. }
  1011. }
  1012. FlowEdge *
  1013. FlowGraph::FindEdge(BasicBlock *predBlock, BasicBlock *succBlock)
  1014. {
  1015. FlowEdge *srcEdge = nullptr;
  1016. FOREACH_SUCCESSOR_EDGE(edge, predBlock)
  1017. {
  1018. if (edge->GetSucc() == succBlock)
  1019. {
  1020. srcEdge = edge;
  1021. break;
  1022. }
  1023. } NEXT_SUCCESSOR_EDGE;
  1024. return srcEdge;
  1025. }
  1026. void
  1027. BasicBlock::InvertBranch(IR::BranchInstr *branch)
  1028. {
  1029. Assert(this->GetLastInstr() == branch);
  1030. Assert(this->GetSuccList()->HasTwo());
  1031. branch->Invert();
  1032. this->GetSuccList()->Reverse();
  1033. }
  1034. bool
  1035. FlowGraph::CanonicalizeLoops()
  1036. {
  1037. if (this->func->HasProfileInfo())
  1038. {
  1039. this->implicitCallFlags = this->func->GetReadOnlyProfileInfo()->GetImplicitCallFlags();
  1040. for (Loop *loop = this->loopList; loop; loop = loop->next)
  1041. {
  1042. this->implicitCallFlags = (Js::ImplicitCallFlags)(this->implicitCallFlags | loop->GetImplicitCallFlags());
  1043. }
  1044. }
  1045. #if DBG_DUMP
  1046. this->Dump(true, _u("\n Before canonicalizeLoops \n"));
  1047. #endif
  1048. bool breakBlockRelocated = false;
  1049. for (Loop *loop = this->loopList; loop; loop = loop->next)
  1050. {
  1051. loop->InsertLandingPad(this);
  1052. if (!this->func->HasTry() || this->func->DoOptimizeTry())
  1053. {
  1054. bool relocated = loop->RemoveBreakBlocks(this);
  1055. if (!breakBlockRelocated && relocated)
  1056. {
  1057. breakBlockRelocated = true;
  1058. }
  1059. }
  1060. }
  1061. #if DBG_DUMP
  1062. this->Dump(true, _u("\n After canonicalizeLoops \n"));
  1063. #endif
  1064. return breakBlockRelocated;
  1065. }
  1066. // Find the loops in this function, build the loop structure, and build a linked
  1067. // list of the basic blocks in this loop (including blocks of inner loops). The
  1068. // list preserves the reverse post-order of the blocks in the flowgraph block list.
  1069. void
  1070. FlowGraph::FindLoops()
  1071. {
  1072. if (!this->hasLoop)
  1073. {
  1074. return;
  1075. }
  1076. Func * func = this->func;
  1077. FOREACH_BLOCK_BACKWARD_IN_FUNC(block, func)
  1078. {
  1079. if (block->loop != nullptr)
  1080. {
  1081. // Block already visited
  1082. continue;
  1083. }
  1084. FOREACH_SUCCESSOR_BLOCK(succ, block)
  1085. {
  1086. if (succ->isLoopHeader && succ->loop == nullptr)
  1087. {
  1088. // Found a loop back-edge
  1089. BuildLoop(succ, block);
  1090. }
  1091. } NEXT_SUCCESSOR_BLOCK;
  1092. if (block->isLoopHeader && block->loop == nullptr)
  1093. {
  1094. // We would have built a loop for it if it was a loop...
  1095. block->isLoopHeader = false;
  1096. block->GetFirstInstr()->AsLabelInstr()->m_isLoopTop = false;
  1097. }
  1098. } NEXT_BLOCK_BACKWARD_IN_FUNC;
  1099. }
  1100. void
  1101. FlowGraph::BuildLoop(BasicBlock *headBlock, BasicBlock *tailBlock, Loop *parentLoop)
  1102. {
  1103. // This function is recursive, so when jitting in the foreground, probe the stack
  1104. if(!func->IsBackgroundJIT())
  1105. {
  1106. PROBE_STACK_NO_DISPOSE(func->GetScriptContext(), Js::Constants::MinStackDefault);
  1107. }
  1108. if (tailBlock->number < headBlock->number)
  1109. {
  1110. // Not a loop. We didn't see any back-edge.
  1111. headBlock->isLoopHeader = false;
  1112. headBlock->GetFirstInstr()->AsLabelInstr()->m_isLoopTop = false;
  1113. return;
  1114. }
  1115. Assert(headBlock->isLoopHeader);
  1116. Loop *loop = JitAnewZ(this->GetFunc()->m_alloc, Loop, this->GetFunc()->m_alloc, this->GetFunc());
  1117. loop->next = this->loopList;
  1118. this->loopList = loop;
  1119. headBlock->loop = loop;
  1120. loop->headBlock = headBlock;
  1121. loop->int32SymsOnEntry = nullptr;
  1122. loop->lossyInt32SymsOnEntry = nullptr;
  1123. // If parentLoop is a parent of loop, it's headBlock better appear first.
  1124. if (parentLoop && loop->headBlock->number > parentLoop->headBlock->number)
  1125. {
  1126. loop->parent = parentLoop;
  1127. parentLoop->isLeaf = false;
  1128. }
  1129. loop->hasDeadStoreCollectionPass = false;
  1130. loop->hasDeadStorePrepass = false;
  1131. loop->memOpInfo = nullptr;
  1132. loop->doMemOp = true;
  1133. NoRecoverMemoryJitArenaAllocator tempAlloc(_u("BE-LoopBuilder"), this->func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  1134. WalkLoopBlocks(tailBlock, loop, &tempAlloc);
  1135. Assert(loop->GetHeadBlock() == headBlock);
  1136. IR::LabelInstr * firstInstr = loop->GetLoopTopInstr();
  1137. firstInstr->SetLoop(loop);
  1138. if (firstInstr->IsProfiledLabelInstr())
  1139. {
  1140. loop->SetImplicitCallFlags(firstInstr->AsProfiledLabelInstr()->loopImplicitCallFlags);
  1141. if (this->func->HasProfileInfo() && this->func->GetReadOnlyProfileInfo()->IsLoopImplicitCallInfoDisabled())
  1142. {
  1143. loop->SetImplicitCallFlags(this->func->GetReadOnlyProfileInfo()->GetImplicitCallFlags());
  1144. }
  1145. loop->SetLoopFlags(firstInstr->AsProfiledLabelInstr()->loopFlags);
  1146. }
  1147. else
  1148. {
  1149. // Didn't collect profile information, don't do optimizations
  1150. loop->SetImplicitCallFlags(Js::ImplicitCall_All);
  1151. }
  1152. }
  1153. Loop::MemCopyCandidate* Loop::MemOpCandidate::AsMemCopy()
  1154. {
  1155. Assert(this->IsMemCopy());
  1156. return (Loop::MemCopyCandidate*)this;
  1157. }
  1158. Loop::MemSetCandidate* Loop::MemOpCandidate::AsMemSet()
  1159. {
  1160. Assert(this->IsMemSet());
  1161. return (Loop::MemSetCandidate*)this;
  1162. }
  1163. void
  1164. Loop::EnsureMemOpVariablesInitialized()
  1165. {
  1166. Assert(this->doMemOp);
  1167. if (this->memOpInfo == nullptr)
  1168. {
  1169. JitArenaAllocator *allocator = this->GetFunc()->GetTopFunc()->m_fg->alloc;
  1170. this->memOpInfo = JitAnewStruct(allocator, Loop::MemOpInfo);
  1171. this->memOpInfo->inductionVariablesUsedAfterLoop = nullptr;
  1172. this->memOpInfo->startIndexOpndCache[0] = nullptr;
  1173. this->memOpInfo->startIndexOpndCache[1] = nullptr;
  1174. this->memOpInfo->startIndexOpndCache[2] = nullptr;
  1175. this->memOpInfo->startIndexOpndCache[3] = nullptr;
  1176. this->memOpInfo->inductionVariableChangeInfoMap = JitAnew(allocator, Loop::InductionVariableChangeInfoMap, allocator);
  1177. this->memOpInfo->inductionVariableOpndPerUnrollMap = JitAnew(allocator, Loop::InductionVariableOpndPerUnrollMap, allocator);
  1178. this->memOpInfo->candidates = JitAnew(allocator, Loop::MemOpList, allocator);
  1179. }
  1180. }
  1181. // Walk the basic blocks backwards until we find the loop header.
  1182. // Mark basic blocks in the loop by looking at the predecessors
  1183. // of blocks known to be in the loop.
  1184. // Recurse on inner loops.
  1185. void
  1186. FlowGraph::WalkLoopBlocks(BasicBlock *block, Loop *loop, JitArenaAllocator *tempAlloc)
  1187. {
  1188. AnalysisAssert(loop);
  1189. BVSparse<JitArenaAllocator> *loopBlocksBv = JitAnew(tempAlloc, BVSparse<JitArenaAllocator>, tempAlloc);
  1190. BasicBlock *tailBlock = block;
  1191. BasicBlock *lastBlock;
  1192. loopBlocksBv->Set(block->GetBlockNum());
  1193. this->AddBlockToLoop(block, loop);
  1194. if (block == loop->headBlock)
  1195. {
  1196. // Single block loop, we're done
  1197. return;
  1198. }
  1199. do
  1200. {
  1201. BOOL isInLoop = loopBlocksBv->Test(block->GetBlockNum());
  1202. FOREACH_SUCCESSOR_BLOCK(succ, block)
  1203. {
  1204. if (succ->isLoopHeader)
  1205. {
  1206. // Found a loop back-edge
  1207. if (loop->headBlock == succ)
  1208. {
  1209. isInLoop = true;
  1210. }
  1211. else if (succ->loop == nullptr || succ->loop->headBlock != succ)
  1212. {
  1213. // Recurse on inner loop
  1214. BuildLoop(succ, block, isInLoop ? loop : nullptr);
  1215. }
  1216. }
  1217. } NEXT_SUCCESSOR_BLOCK;
  1218. if (isInLoop)
  1219. {
  1220. // This block is in the loop. All of it's predecessors should be contained in the loop as well.
  1221. FOREACH_PREDECESSOR_BLOCK(pred, block)
  1222. {
  1223. // Fix up loop parent if it isn't set already.
  1224. // If pred->loop != loop, we're looking at an inner loop, which was already visited.
  1225. // If pred->loop->parent == nullptr, this is the first time we see this loop from an outer
  1226. // loop, so this must be an immediate child.
  1227. if (pred->loop && pred->loop != loop && loop->headBlock->number < pred->loop->headBlock->number
  1228. && (pred->loop->parent == nullptr || pred->loop->parent->headBlock->number < loop->headBlock->number))
  1229. {
  1230. pred->loop->parent = loop;
  1231. loop->isLeaf = false;
  1232. if (pred->loop->hasCall)
  1233. {
  1234. loop->SetHasCall();
  1235. }
  1236. loop->SetImplicitCallFlags(pred->loop->GetImplicitCallFlags());
  1237. }
  1238. // Add pred to loop bit vector
  1239. loopBlocksBv->Set(pred->GetBlockNum());
  1240. } NEXT_PREDECESSOR_BLOCK;
  1241. if (block->loop == nullptr || block->loop->IsDescendentOrSelf(loop))
  1242. {
  1243. block->loop = loop;
  1244. }
  1245. if (block != tailBlock)
  1246. {
  1247. this->AddBlockToLoop(block, loop);
  1248. }
  1249. }
  1250. lastBlock = block;
  1251. block = block->GetPrev();
  1252. } while (lastBlock != loop->headBlock);
  1253. }
  1254. // Add block to this loop, and it's parent loops.
  1255. void
  1256. FlowGraph::AddBlockToLoop(BasicBlock *block, Loop *loop)
  1257. {
  1258. loop->blockList.Prepend(block);
  1259. if (block->hasCall)
  1260. {
  1261. loop->SetHasCall();
  1262. }
  1263. }
  1264. ///----------------------------------------------------------------------------
  1265. ///
  1266. /// FlowGraph::AddBlock
  1267. ///
  1268. /// Finish processing of a new block: hook up successor arcs, note loops, etc.
  1269. ///
  1270. ///----------------------------------------------------------------------------
  1271. BasicBlock *
  1272. FlowGraph::AddBlock(
  1273. IR::Instr * firstInstr,
  1274. IR::Instr * lastInstr,
  1275. BasicBlock * nextBlock,
  1276. BasicBlock *prevBlock)
  1277. {
  1278. BasicBlock * block;
  1279. IR::LabelInstr * labelInstr;
  1280. if (firstInstr->IsLabelInstr())
  1281. {
  1282. labelInstr = firstInstr->AsLabelInstr();
  1283. }
  1284. else
  1285. {
  1286. labelInstr = IR::LabelInstr::New(Js::OpCode::Label, firstInstr->m_func);
  1287. labelInstr->SetByteCodeOffset(firstInstr);
  1288. if (firstInstr->IsEntryInstr())
  1289. {
  1290. firstInstr->InsertAfter(labelInstr);
  1291. }
  1292. else
  1293. {
  1294. firstInstr->InsertBefore(labelInstr);
  1295. }
  1296. firstInstr = labelInstr;
  1297. }
  1298. block = labelInstr->GetBasicBlock();
  1299. if (block == nullptr)
  1300. {
  1301. block = BasicBlock::New(this);
  1302. labelInstr->SetBasicBlock(block);
  1303. // Remember last block in function to target successor of RETs.
  1304. if (!this->tailBlock)
  1305. {
  1306. this->tailBlock = block;
  1307. }
  1308. }
  1309. // Hook up the successor edges
  1310. if (lastInstr->EndsBasicBlock())
  1311. {
  1312. BasicBlock * blockTarget = nullptr;
  1313. if (lastInstr->IsBranchInstr())
  1314. {
  1315. // Hook up a successor edge to the branch target.
  1316. IR::BranchInstr * branchInstr = lastInstr->AsBranchInstr();
  1317. if(branchInstr->IsMultiBranch())
  1318. {
  1319. BasicBlock * blockMultiBrTarget;
  1320. IR::MultiBranchInstr * multiBranchInstr = branchInstr->AsMultiBrInstr();
  1321. multiBranchInstr->MapUniqueMultiBrLabels([&](IR::LabelInstr * labelInstr) -> void
  1322. {
  1323. blockMultiBrTarget = SetBlockTargetAndLoopFlag(labelInstr);
  1324. this->AddEdge(block, blockMultiBrTarget);
  1325. });
  1326. }
  1327. else
  1328. {
  1329. IR::LabelInstr * targetLabelInstr = branchInstr->GetTarget();
  1330. blockTarget = SetBlockTargetAndLoopFlag(targetLabelInstr);
  1331. if (branchInstr->IsConditional())
  1332. {
  1333. IR::Instr *instrNext = branchInstr->GetNextRealInstrOrLabel();
  1334. if (instrNext->IsLabelInstr())
  1335. {
  1336. SetBlockTargetAndLoopFlag(instrNext->AsLabelInstr());
  1337. }
  1338. }
  1339. }
  1340. }
  1341. else if (lastInstr->m_opcode == Js::OpCode::Ret && block != this->tailBlock)
  1342. {
  1343. blockTarget = this->tailBlock;
  1344. }
  1345. if (blockTarget)
  1346. {
  1347. this->AddEdge(block, blockTarget);
  1348. }
  1349. }
  1350. if (lastInstr->HasFallThrough())
  1351. {
  1352. // Add a branch to next instruction so that we don't have to update the flow graph
  1353. // when the glob opt tries to insert instructions.
  1354. // We don't run the globopt with try/catch, don't need to insert branch to next for fall through blocks.
  1355. if (!this->func->HasTry() && !lastInstr->IsBranchInstr())
  1356. {
  1357. IR::BranchInstr * instr = IR::BranchInstr::New(Js::OpCode::Br,
  1358. lastInstr->m_next->AsLabelInstr(), lastInstr->m_func);
  1359. instr->SetByteCodeOffset(lastInstr->m_next);
  1360. lastInstr->InsertAfter(instr);
  1361. lastInstr = instr;
  1362. }
  1363. this->AddEdge(block, nextBlock);
  1364. }
  1365. block->SetBlockNum(this->blockCount++);
  1366. block->SetFirstInstr(firstInstr);
  1367. block->SetLastInstr(lastInstr);
  1368. if (!prevBlock)
  1369. {
  1370. if (this->blockList)
  1371. {
  1372. this->blockList->prev = block;
  1373. }
  1374. block->next = this->blockList;
  1375. this->blockList = block;
  1376. }
  1377. else
  1378. {
  1379. prevBlock->next = block;
  1380. block->prev = prevBlock;
  1381. block->next = nextBlock;
  1382. nextBlock->prev = block;
  1383. }
  1384. return block;
  1385. }
  1386. BasicBlock *
  1387. FlowGraph::SetBlockTargetAndLoopFlag(IR::LabelInstr * labelInstr)
  1388. {
  1389. BasicBlock * blockTarget = nullptr;
  1390. blockTarget = labelInstr->GetBasicBlock();
  1391. if (blockTarget == nullptr)
  1392. {
  1393. blockTarget = BasicBlock::New(this);
  1394. labelInstr->SetBasicBlock(blockTarget);
  1395. }
  1396. if (labelInstr->m_isLoopTop)
  1397. {
  1398. blockTarget->isLoopHeader = true;
  1399. this->hasLoop = true;
  1400. }
  1401. return blockTarget;
  1402. }
  1403. ///----------------------------------------------------------------------------
  1404. ///
  1405. /// FlowGraph::AddEdge
  1406. ///
  1407. /// Add an edge connecting the two given blocks.
  1408. ///
  1409. ///----------------------------------------------------------------------------
  1410. FlowEdge *
  1411. FlowGraph::AddEdge(BasicBlock * blockPred, BasicBlock * blockSucc)
  1412. {
  1413. FlowEdge * edge = FlowEdge::New(this);
  1414. edge->SetPred(blockPred);
  1415. edge->SetSucc(blockSucc);
  1416. blockPred->AddSucc(edge, this);
  1417. blockSucc->AddPred(edge, this);
  1418. return edge;
  1419. }
  1420. ///----------------------------------------------------------------------------
  1421. ///
  1422. /// FlowGraph::Destroy
  1423. ///
  1424. /// Remove all references to FG structures from the IR in preparation for freeing
  1425. /// the FG.
  1426. ///
  1427. ///----------------------------------------------------------------------------
  1428. void
  1429. FlowGraph::Destroy(void)
  1430. {
  1431. BOOL fHasTry = this->func->HasTry();
  1432. if (fHasTry)
  1433. {
  1434. // Do unreachable code removal up front to avoid problems
  1435. // with unreachable back edges, etc.
  1436. this->RemoveUnreachableBlocks();
  1437. }
  1438. FOREACH_BLOCK_ALL(block, this)
  1439. {
  1440. IR::Instr * firstInstr = block->GetFirstInstr();
  1441. if (block->isDeleted && !block->isDead)
  1442. {
  1443. if (firstInstr->IsLabelInstr())
  1444. {
  1445. IR::LabelInstr * labelInstr = firstInstr->AsLabelInstr();
  1446. labelInstr->UnlinkBasicBlock();
  1447. // Removing the label for non try blocks as we have a deleted block which has the label instruction
  1448. // still not removed; this prevents the assert for cases where the deleted blocks fall through to a helper block,
  1449. // i.e. helper introduced by polymorphic inlining bailout.
  1450. // Skipping Try blocks as we have dependency on blocks to get the last instr(see below in this function)
  1451. if (!fHasTry)
  1452. {
  1453. if (this->func->GetJITFunctionBody()->IsCoroutine())
  1454. {
  1455. // the label could be a yield resume label, in which case we also need to remove it from the YieldOffsetResumeLabels list
  1456. this->func->MapUntilYieldOffsetResumeLabels([this, &labelInstr](int i, const YieldOffsetResumeLabel& yorl)
  1457. {
  1458. if (labelInstr == yorl.Second())
  1459. {
  1460. labelInstr->m_hasNonBranchRef = false;
  1461. this->func->RemoveYieldOffsetResumeLabel(yorl);
  1462. return true;
  1463. }
  1464. return false;
  1465. });
  1466. }
  1467. Assert(labelInstr->IsUnreferenced());
  1468. labelInstr->Remove();
  1469. }
  1470. }
  1471. continue;
  1472. }
  1473. if (block->isLoopHeader && !block->isDead)
  1474. {
  1475. // Mark the tail block of this loop (the last back-edge). The register allocator
  1476. // uses this to lexically find loops.
  1477. BasicBlock *loopTail = nullptr;
  1478. AssertMsg(firstInstr->IsLabelInstr() && firstInstr->AsLabelInstr()->m_isLoopTop,
  1479. "Label not marked as loop top...");
  1480. FOREACH_BLOCK_IN_LOOP(loopBlock, block->loop)
  1481. {
  1482. FOREACH_SUCCESSOR_BLOCK(succ, loopBlock)
  1483. {
  1484. if (succ == block)
  1485. {
  1486. loopTail = loopBlock;
  1487. break;
  1488. }
  1489. } NEXT_SUCCESSOR_BLOCK;
  1490. } NEXT_BLOCK_IN_LOOP;
  1491. if (loopTail)
  1492. {
  1493. AssertMsg(loopTail->GetLastInstr()->IsBranchInstr(), "LastInstr of loop should always be a branch no?");
  1494. block->loop->SetLoopTopInstr(block->GetFirstInstr()->AsLabelInstr());
  1495. }
  1496. else
  1497. {
  1498. // This loop doesn't have a back-edge: that is, it is not a loop
  1499. // anymore...
  1500. firstInstr->AsLabelInstr()->m_isLoopTop = FALSE;
  1501. }
  1502. }
  1503. if (fHasTry)
  1504. {
  1505. this->UpdateRegionForBlock(block);
  1506. }
  1507. if (firstInstr->IsLabelInstr())
  1508. {
  1509. IR::LabelInstr * labelInstr = firstInstr->AsLabelInstr();
  1510. labelInstr->UnlinkBasicBlock();
  1511. if (labelInstr->IsUnreferenced() && !fHasTry)
  1512. {
  1513. // This is an unreferenced label, probably added by FG building.
  1514. // Delete it now to make extended basic blocks visible.
  1515. if (firstInstr == block->GetLastInstr())
  1516. {
  1517. labelInstr->Remove();
  1518. continue;
  1519. }
  1520. else
  1521. {
  1522. labelInstr->Remove();
  1523. }
  1524. }
  1525. }
  1526. IR::Instr * lastInstr = block->GetLastInstr();
  1527. if (lastInstr->IsBranchInstr())
  1528. {
  1529. IR::BranchInstr * branchInstr = lastInstr->AsBranchInstr();
  1530. if (!branchInstr->IsConditional() && branchInstr->GetTarget() == branchInstr->m_next)
  1531. {
  1532. // Remove branch to next
  1533. branchInstr->Remove();
  1534. }
  1535. }
  1536. }
  1537. NEXT_BLOCK;
  1538. #if DBG
  1539. if (fHasTry)
  1540. {
  1541. // Now that all blocks have regions, we should see consistently propagated regions at all
  1542. // block boundaries.
  1543. FOREACH_BLOCK(block, this)
  1544. {
  1545. Region * region = block->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1546. Region * predRegion = nullptr;
  1547. FOREACH_PREDECESSOR_BLOCK(predBlock, block)
  1548. {
  1549. BasicBlock* intermediateBlock = block;
  1550. // Skip blocks inserted for airlock/masking purposes
  1551. while ((predBlock->isAirLockBlock || predBlock->isAirLockCompensationBlock) && predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion() == region)
  1552. {
  1553. Assert(predBlock->GetPredList()->HasOne());
  1554. intermediateBlock = predBlock;
  1555. predBlock = predBlock->GetPredList()->Head()->GetPred();
  1556. }
  1557. predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1558. if (predBlock->GetLastInstr() == nullptr)
  1559. {
  1560. AssertMsg(region == predRegion, "Bad region propagation through empty block");
  1561. }
  1562. else
  1563. {
  1564. switch (predBlock->GetLastInstr()->m_opcode)
  1565. {
  1566. case Js::OpCode::TryCatch:
  1567. case Js::OpCode::TryFinally:
  1568. AssertMsg(region->GetParent() == predRegion, "Bad region prop on entry to try-catch/finally");
  1569. if (intermediateBlock->GetFirstInstr() == predBlock->GetLastInstr()->AsBranchInstr()->GetTarget())
  1570. {
  1571. if (predBlock->GetLastInstr()->m_opcode == Js::OpCode::TryCatch)
  1572. {
  1573. AssertMsg(region->GetType() == RegionTypeCatch, "Bad region type on entry to catch");
  1574. }
  1575. else
  1576. {
  1577. AssertMsg(region->GetType() == RegionTypeFinally, "Bad region type on entry to finally");
  1578. }
  1579. }
  1580. else
  1581. {
  1582. AssertMsg(region->GetType() == RegionTypeTry, "Bad region type on entry to try");
  1583. }
  1584. break;
  1585. case Js::OpCode::Leave:
  1586. AssertMsg(region == predRegion->GetParent() || (predRegion->GetType() == RegionTypeTry && predRegion->GetMatchingFinallyRegion(false) == region) ||
  1587. (region == predRegion && this->func->IsLoopBodyInTry() ||
  1588. // edge from early exit to finally in simplejit - in fulljit this Leave would have been deadcoded due to preceeding BailOutOnEarlyExit
  1589. (predBlock->GetLastInstr()->GetPrevRealInstr()->m_opcode == Js::OpCode::BailOnEarlyExit && region->GetType() == RegionTypeFinally && this->func->IsSimpleJit())), "Bad region prop on leaving try-catch/finally");
  1590. break;
  1591. case Js::OpCode::LeaveNull:
  1592. AssertMsg(region == predRegion->GetParent() || (region == predRegion && this->func->IsLoopBodyInTry()), "Bad region prop on leaving try-catch/finally");
  1593. break;
  1594. // If the try region has a branch out of the loop,
  1595. // - the branch is moved out of the loop as part of break block removal, and
  1596. // - BrOnException is inverted to BrOnNoException and a Br is inserted after it.
  1597. // Otherwise,
  1598. // - FullJit: BrOnException is removed in the forward pass.
  1599. case Js::OpCode::BrOnException:
  1600. Assert(!this->func->DoGlobOpt());
  1601. break;
  1602. case Js::OpCode::BrOnNoException:
  1603. Assert(region->GetType() == RegionTypeTry || region->GetType() == RegionTypeCatch || region->GetType() == RegionTypeFinally ||
  1604. // A BrOnException from finally to early exit can be converted to BrOnNoException and Br
  1605. // The Br block maybe a common successor block for early exit along with the BrOnNoException block
  1606. // Region from Br block will be picked up from a predecessor which is not BrOnNoException due to early exit
  1607. // See test0() in test/EH/tryfinallytests.js
  1608. (predRegion->GetType() == RegionTypeFinally && predBlock->GetLastInstr()->AsBranchInstr()->m_brFinallyToEarlyExit));
  1609. break;
  1610. case Js::OpCode::Br:
  1611. if (predBlock->GetLastInstr()->AsBranchInstr()->m_leaveConvToBr)
  1612. {
  1613. // Leave converted to Br in finally region
  1614. AssertMsg(region == predRegion->GetParent(), "Bad region prop in finally");
  1615. }
  1616. else if (region->GetType() == RegionTypeCatch && region != predRegion)
  1617. {
  1618. AssertMsg(predRegion->GetType() == RegionTypeTry, "Bad region type for the try");
  1619. }
  1620. else if (region->GetType() == RegionTypeFinally && region != predRegion)
  1621. {
  1622. // We may be left with edges from finally region to early exit
  1623. AssertMsg(predRegion->IsNonExceptingFinally() || predRegion->GetType() == RegionTypeTry, "Bad region type for the try");
  1624. }
  1625. else
  1626. {
  1627. // We may be left with edges from finally region to early exit
  1628. AssertMsg(predRegion->IsNonExceptingFinally() || region == predRegion, "Bad region propagation through interior block");
  1629. }
  1630. break;
  1631. default:
  1632. break;
  1633. }
  1634. }
  1635. }
  1636. NEXT_PREDECESSOR_BLOCK;
  1637. switch (region->GetType())
  1638. {
  1639. case RegionTypeRoot:
  1640. Assert(!region->GetMatchingTryRegion() && !region->GetMatchingCatchRegion() && !region->GetMatchingFinallyRegion(true) && !region->GetMatchingFinallyRegion(false));
  1641. break;
  1642. case RegionTypeTry:
  1643. if (this->func->DoOptimizeTry() || (this->func->IsSimpleJit() && this->func->hasBailout))
  1644. {
  1645. Assert((region->GetMatchingCatchRegion() != nullptr) ^ (region->GetMatchingFinallyRegion(true) && region->GetMatchingFinallyRegion(false)));
  1646. }
  1647. else
  1648. {
  1649. Assert((region->GetMatchingCatchRegion() != nullptr) ^ (region->GetMatchingFinallyRegion(true) && !region->GetMatchingFinallyRegion(false)));
  1650. }
  1651. break;
  1652. case RegionTypeCatch:
  1653. case RegionTypeFinally:
  1654. Assert(region->GetMatchingTryRegion());
  1655. break;
  1656. }
  1657. }
  1658. NEXT_BLOCK;
  1659. FOREACH_BLOCK_ALL(block, this)
  1660. {
  1661. if (block->GetFirstInstr()->IsLabelInstr())
  1662. {
  1663. IR::LabelInstr *labelInstr = block->GetFirstInstr()->AsLabelInstr();
  1664. if (labelInstr->IsUnreferenced())
  1665. {
  1666. // This is an unreferenced label, probably added by FG building.
  1667. // Delete it now to make extended basic blocks visible.
  1668. labelInstr->Remove();
  1669. }
  1670. }
  1671. } NEXT_BLOCK;
  1672. }
  1673. #endif
  1674. this->func->isFlowGraphValid = false;
  1675. }
  1676. bool FlowGraph::IsEHTransitionInstr(IR::Instr *instr)
  1677. {
  1678. Js::OpCode op = instr->m_opcode;
  1679. return (op == Js::OpCode::TryCatch || op == Js::OpCode::TryFinally || op == Js::OpCode::Leave || op == Js::OpCode::LeaveNull);
  1680. }
  1681. BasicBlock * FlowGraph::GetPredecessorForRegionPropagation(BasicBlock *block)
  1682. {
  1683. BasicBlock *ehPred = nullptr;
  1684. FOREACH_PREDECESSOR_BLOCK(predBlock, block)
  1685. {
  1686. Region * predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1687. if (IsEHTransitionInstr(predBlock->GetLastInstr()) && predRegion)
  1688. {
  1689. // MGTODO : change this to return, once you know there can exist only one eh transitioning pred
  1690. Assert(ehPred == nullptr);
  1691. ehPred = predBlock;
  1692. }
  1693. AssertMsg(predBlock->GetBlockNum() < this->blockCount, "Misnumbered block at teardown time?");
  1694. }
  1695. NEXT_PREDECESSOR_BLOCK;
  1696. return ehPred;
  1697. }
  1698. // Propagate the region forward from the block's predecessor(s), tracking the effect
  1699. // of the flow transition. Record the region in the block-to-region map provided
  1700. // and on the label at the entry to the block (if any).
  1701. // We need to know the end of finally for inserting edge at the end of finally to early exit
  1702. // Store it in regToFinallyEndMap as we visit blocks instead of recomputing later while adding early exit edges
  1703. void
  1704. FlowGraph::UpdateRegionForBlock(BasicBlock * block)
  1705. {
  1706. Region *region;
  1707. Region * predRegion = nullptr;
  1708. IR::Instr * tryInstr = nullptr;
  1709. IR::Instr * firstInstr = block->GetFirstInstr();
  1710. if (firstInstr->IsLabelInstr() && firstInstr->AsLabelInstr()->GetRegion())
  1711. {
  1712. #if DBG
  1713. bool assignRegionsBeforeGlobopt = this->func->HasTry() && (this->func->DoOptimizeTry() ||
  1714. (this->func->IsSimpleJit() && this->func->hasBailout) ||
  1715. this->func->IsLoopBodyInTryFinally());
  1716. Assert(assignRegionsBeforeGlobopt);
  1717. #endif
  1718. return;
  1719. }
  1720. if (block == this->blockList)
  1721. {
  1722. // Head of the graph: create the root region.
  1723. region = Region::New(RegionTypeRoot, nullptr, this->func);
  1724. }
  1725. else
  1726. {
  1727. // Propagate the region forward by finding a predecessor we've already processed.
  1728. region = nullptr;
  1729. FOREACH_PREDECESSOR_BLOCK(predBlock, block)
  1730. {
  1731. AssertMsg(predBlock->GetBlockNum() < this->blockCount, "Misnumbered block at teardown time?");
  1732. predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1733. if (predRegion != nullptr)
  1734. {
  1735. region = this->PropagateRegionFromPred(block, predBlock, predRegion, tryInstr);
  1736. break;
  1737. }
  1738. }
  1739. NEXT_PREDECESSOR_BLOCK;
  1740. if (block->GetLastInstr()->m_opcode == Js::OpCode::LeaveNull || block->GetLastInstr()->m_opcode == Js::OpCode::Leave)
  1741. {
  1742. if (this->regToFinallyEndMap && region->IsNonExceptingFinally())
  1743. {
  1744. BasicBlock *endOfFinally = regToFinallyEndMap->ContainsKey(region) ? regToFinallyEndMap->Item(region) : nullptr;
  1745. if (!endOfFinally)
  1746. {
  1747. regToFinallyEndMap->Add(region, block);
  1748. }
  1749. else
  1750. {
  1751. Assert(endOfFinally->GetLastInstr()->m_opcode != Js::OpCode::LeaveNull || block == endOfFinally);
  1752. regToFinallyEndMap->Item(region, block);
  1753. }
  1754. }
  1755. }
  1756. }
  1757. Assert(region || block->GetPredList()->Count() == 0);
  1758. if (region && !region->ehBailoutData)
  1759. {
  1760. region->AllocateEHBailoutData(this->func, tryInstr);
  1761. }
  1762. Assert(firstInstr->IsLabelInstr());
  1763. if (firstInstr->IsLabelInstr())
  1764. {
  1765. // Record the region on the label and make sure it stays around as a region
  1766. // marker if we're entering a region at this point.
  1767. IR::LabelInstr * labelInstr = firstInstr->AsLabelInstr();
  1768. labelInstr->SetRegion(region);
  1769. if (region != predRegion)
  1770. {
  1771. labelInstr->m_hasNonBranchRef = true;
  1772. }
  1773. // One of the pred blocks maybe an eh region, in that case it is important to mark this label's m_hasNonBranchRef
  1774. // If not later in codegen, this label can get deleted. And during SccLiveness, region is propagated to newly created labels in lowerer from the previous label's region
  1775. // We can end up assigning an eh region to a label in a non eh region. And if there is a bailout in such a region, bad things will happen in the interpreter :)
  1776. // See test2()/test3() in tryfinallytests.js
  1777. if (!labelInstr->m_hasNonBranchRef)
  1778. {
  1779. FOREACH_PREDECESSOR_BLOCK(predBlock, block)
  1780. {
  1781. AssertMsg(predBlock->GetBlockNum() < this->blockCount, "Misnumbered block at teardown time?");
  1782. predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1783. if (predRegion != region)
  1784. {
  1785. labelInstr->m_hasNonBranchRef = true;
  1786. break;
  1787. }
  1788. }
  1789. NEXT_PREDECESSOR_BLOCK;
  1790. }
  1791. }
  1792. }
  1793. void
  1794. FlowGraph::UpdateRegionForBlockFromEHPred(BasicBlock * block, bool reassign)
  1795. {
  1796. Region *region = nullptr;
  1797. Region * predRegion = nullptr;
  1798. IR::Instr * tryInstr = nullptr;
  1799. IR::Instr * firstInstr = block->GetFirstInstr();
  1800. if (!reassign && firstInstr->IsLabelInstr() && firstInstr->AsLabelInstr()->GetRegion())
  1801. {
  1802. Assert(this->func->HasTry() && (this->func->DoOptimizeTry() || (this->func->IsSimpleJit() && this->func->hasBailout)));
  1803. return;
  1804. }
  1805. if (block->isDead || block->isDeleted)
  1806. {
  1807. // We can end up calling this function with such blocks, return doing nothing
  1808. // See test5() in tryfinallytests.js
  1809. return;
  1810. }
  1811. if (block == this->blockList)
  1812. {
  1813. // Head of the graph: create the root region.
  1814. region = Region::New(RegionTypeRoot, nullptr, this->func);
  1815. }
  1816. else if (block->GetPredList()->Count() == 1)
  1817. {
  1818. BasicBlock *predBlock = block->GetPredList()->Head()->GetPred();
  1819. AssertMsg(predBlock->GetBlockNum() < this->blockCount, "Misnumbered block at teardown time?");
  1820. predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1821. Assert(predRegion);
  1822. region = this->PropagateRegionFromPred(block, predBlock, predRegion, tryInstr);
  1823. }
  1824. else
  1825. {
  1826. // Propagate the region forward by finding a predecessor we've already processed.
  1827. // Since we do break block remval after region propagation, we cannot pick the first predecessor which has an assigned region
  1828. // If there is a eh transitioning pred, we pick that
  1829. // There cannot be more than one eh transitioning pred (?)
  1830. BasicBlock *ehPred = this->GetPredecessorForRegionPropagation(block);
  1831. if (ehPred)
  1832. {
  1833. predRegion = ehPred->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1834. Assert(predRegion != nullptr);
  1835. region = this->PropagateRegionFromPred(block, ehPred, predRegion, tryInstr);
  1836. }
  1837. else
  1838. {
  1839. FOREACH_PREDECESSOR_BLOCK(predBlock, block)
  1840. {
  1841. predRegion = predBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  1842. if (predRegion != nullptr)
  1843. {
  1844. if ((predBlock->GetLastInstr()->m_opcode == Js::OpCode::BrOnException || predBlock->GetLastInstr()->m_opcode == Js::OpCode::BrOnNoException) &&
  1845. predBlock->GetLastInstr()->AsBranchInstr()->m_brFinallyToEarlyExit)
  1846. {
  1847. Assert(predRegion->IsNonExceptingFinally());
  1848. // BrOnException from finally region to early exit
  1849. // Skip this edge
  1850. continue;
  1851. }
  1852. if (predBlock->GetLastInstr()->m_opcode == Js::OpCode::Br &&
  1853. predBlock->GetLastInstr()->GetPrevRealInstr()->m_opcode == Js::OpCode::BrOnNoException)
  1854. {
  1855. Assert(predBlock->GetLastInstr()->GetPrevRealInstr()->AsBranchInstr()->m_brFinallyToEarlyExit);
  1856. Assert(predRegion->IsNonExceptingFinally());
  1857. // BrOnException from finally region to early exit changed to BrOnNoException and Br during break block removal
  1858. continue;
  1859. }
  1860. region = this->PropagateRegionFromPred(block, predBlock, predRegion, tryInstr);
  1861. break;
  1862. }
  1863. }
  1864. NEXT_PREDECESSOR_BLOCK;
  1865. }
  1866. }
  1867. Assert(region || block->GetPredList()->Count() == 0 || block->firstInstr->AsLabelInstr()->GetRegion());
  1868. if (region)
  1869. {
  1870. if (!region->ehBailoutData)
  1871. {
  1872. region->AllocateEHBailoutData(this->func, tryInstr);
  1873. }
  1874. Assert(firstInstr->IsLabelInstr());
  1875. if (firstInstr->IsLabelInstr())
  1876. {
  1877. // Record the region on the label and make sure it stays around as a region
  1878. // marker if we're entering a region at this point.
  1879. IR::LabelInstr * labelInstr = firstInstr->AsLabelInstr();
  1880. labelInstr->SetRegion(region);
  1881. if (region != predRegion)
  1882. {
  1883. labelInstr->m_hasNonBranchRef = true;
  1884. }
  1885. }
  1886. }
  1887. }
  1888. Region *
  1889. FlowGraph::PropagateRegionFromPred(BasicBlock * block, BasicBlock * predBlock, Region * predRegion, IR::Instr * &tryInstr)
  1890. {
  1891. // Propagate predRegion to region, looking at the flow transition for an opcode
  1892. // that affects the region.
  1893. Region * region = nullptr;
  1894. IR::Instr * predLastInstr = predBlock->GetLastInstr();
  1895. IR::Instr * firstInstr = block->GetFirstInstr();
  1896. if (predLastInstr == nullptr)
  1897. {
  1898. // Empty block: trivially propagate the region.
  1899. region = predRegion;
  1900. }
  1901. else
  1902. {
  1903. Region * tryRegion = nullptr;
  1904. IR::LabelInstr * tryInstrNext = nullptr;
  1905. switch (predLastInstr->m_opcode)
  1906. {
  1907. case Js::OpCode::TryCatch:
  1908. // Entry to a try-catch. See whether we're entering the try or the catch
  1909. // by looking for the handler label.
  1910. Assert(predLastInstr->m_next->IsLabelInstr());
  1911. tryInstrNext = predLastInstr->m_next->AsLabelInstr();
  1912. tryRegion = tryInstrNext->GetRegion();
  1913. if (firstInstr == predLastInstr->AsBranchInstr()->GetTarget())
  1914. {
  1915. region = Region::New(RegionTypeCatch, predRegion, this->func);
  1916. Assert(tryRegion);
  1917. region->SetMatchingTryRegion(tryRegion);
  1918. tryRegion->SetMatchingCatchRegion(region);
  1919. }
  1920. else
  1921. {
  1922. region = Region::New(RegionTypeTry, predRegion, this->func);
  1923. tryInstr = predLastInstr;
  1924. }
  1925. break;
  1926. case Js::OpCode::TryFinally:
  1927. // Entry to a try-finally. See whether we're entering the try or the finally
  1928. // by looking for the handler label.
  1929. Assert(predLastInstr->m_next->IsLabelInstr());
  1930. tryInstrNext = predLastInstr->m_next->AsLabelInstr();
  1931. tryRegion = tryInstrNext->GetRegion();
  1932. if (firstInstr == predLastInstr->AsBranchInstr()->GetTarget())
  1933. {
  1934. Assert(tryRegion && tryRegion->GetType() == RegionType::RegionTypeTry);
  1935. region = Region::New(RegionTypeFinally, predRegion, this->func);
  1936. region->SetMatchingTryRegion(tryRegion);
  1937. tryRegion->SetMatchingFinallyRegion(region, true);
  1938. tryInstr = predLastInstr;
  1939. }
  1940. else
  1941. {
  1942. region = Region::New(RegionTypeTry, predRegion, this->func);
  1943. tryInstr = predLastInstr;
  1944. }
  1945. break;
  1946. case Js::OpCode::Leave:
  1947. if (firstInstr->m_next && firstInstr->m_next->m_opcode == Js::OpCode::Finally)
  1948. {
  1949. tryRegion = predRegion;
  1950. Assert(tryRegion->GetMatchingFinallyRegion(true) != nullptr);
  1951. region = Region::New(RegionTypeFinally, predRegion->GetParent(), this->func);
  1952. Assert(tryRegion && tryRegion->GetType() == RegionType::RegionTypeTry);
  1953. region->SetMatchingTryRegion(tryRegion);
  1954. tryRegion->SetMatchingFinallyRegion(region, false);
  1955. break;
  1956. }
  1957. // Exiting a try or handler. Retrieve the current region's parent.
  1958. region = predRegion->GetParent();
  1959. if (region == nullptr)
  1960. {
  1961. // We found a Leave in the root region- this can only happen when a jitted loop body
  1962. // in a try block has a return statement.
  1963. Assert(this->func->IsLoopBodyInTry());
  1964. predLastInstr->AsBranchInstr()->m_isOrphanedLeave = true;
  1965. region = predRegion;
  1966. }
  1967. break;
  1968. case Js::OpCode::LeaveNull:
  1969. // Exiting a try or handler. Retrieve the current region's parent.
  1970. region = predRegion->GetParent();
  1971. if (region == nullptr)
  1972. {
  1973. // We found a Leave in the root region- this can only happen when a jitted loop body
  1974. // in a try block has a return statement.
  1975. Assert(this->func->IsLoopBodyInTry());
  1976. predLastInstr->AsBranchInstr()->m_isOrphanedLeave = true;
  1977. region = predRegion;
  1978. }
  1979. break;
  1980. case Js::OpCode::BailOnException:
  1981. // Infinite loop, no edge to non excepting finally
  1982. if (firstInstr->m_next && firstInstr->m_next->m_opcode == Js::OpCode::Finally)
  1983. {
  1984. tryRegion = predRegion->GetMatchingTryRegion();
  1985. region = Region::New(RegionTypeFinally, predRegion->GetParent(), this->func);
  1986. Assert(tryRegion && tryRegion->GetType() == RegionType::RegionTypeTry);
  1987. region->SetMatchingTryRegion(tryRegion);
  1988. tryRegion->SetMatchingFinallyRegion(region, false);
  1989. }
  1990. break;
  1991. case Js::OpCode::BrOnException:
  1992. // Infinite loop inside another EH region within finally,
  1993. // We have added edges for all infinite loops inside a finally, identify that and transition to parent
  1994. if (predRegion->GetType() != RegionTypeFinally && firstInstr->GetNextRealInstr()->m_opcode == Js::OpCode::LeaveNull)
  1995. {
  1996. region = predRegion->GetParent();
  1997. }
  1998. else
  1999. {
  2000. region = predRegion;
  2001. }
  2002. break;
  2003. default:
  2004. // Normal (non-EH) transition: just propagate the region.
  2005. region = predRegion;
  2006. break;
  2007. }
  2008. }
  2009. return region;
  2010. }
  2011. void
  2012. FlowGraph::InsertCompBlockToLoopList(Loop *loop, BasicBlock* compBlock, BasicBlock* targetBlock, bool postTarget)
  2013. {
  2014. if (loop)
  2015. {
  2016. bool found = false;
  2017. FOREACH_BLOCK_IN_LOOP_EDITING(loopBlock, loop, iter)
  2018. {
  2019. if (loopBlock == targetBlock)
  2020. {
  2021. found = true;
  2022. break;
  2023. }
  2024. } NEXT_BLOCK_IN_LOOP_EDITING;
  2025. if (found)
  2026. {
  2027. if (postTarget)
  2028. {
  2029. iter.Next();
  2030. }
  2031. iter.InsertBefore(compBlock);
  2032. }
  2033. InsertCompBlockToLoopList(loop->parent, compBlock, targetBlock, postTarget);
  2034. }
  2035. }
  2036. // Insert a block on the given edge
  2037. BasicBlock *
  2038. FlowGraph::InsertAirlockBlock(FlowEdge * edge)
  2039. {
  2040. BasicBlock * airlockBlock = BasicBlock::New(this);
  2041. BasicBlock * sourceBlock = edge->GetPred();
  2042. BasicBlock * sinkBlock = edge->GetSucc();
  2043. IR::Instr * sourceLastInstr = sourceBlock->GetLastInstr();
  2044. //
  2045. // Normalize block
  2046. //
  2047. if(!sourceLastInstr->IsBranchInstr())
  2048. {
  2049. // There are some cases where the last instruction of a block can be not a branch;
  2050. // for example, if it was previously a conditional branch that was impossible to take.
  2051. // In these situations, we can insert an unconditional branch to fallthrough for that
  2052. // block, to renormalize it.
  2053. SListBaseCounted<FlowEdge*>* successors = sourceBlock->GetSuccList();
  2054. // Only handling the case for one arc left at the moment; other cases are likely bugs.
  2055. AssertOrFailFastMsg(successors->HasOne(), "Failed to normalize weird block before airlock");
  2056. FlowEdge* onlyLink = successors->Head();
  2057. AssertOrFailFastMsg(onlyLink == edge, "Found duplicate of edge?");
  2058. AssertOrFailFastMsg(onlyLink->GetSucc() == sinkBlock, "State inconsistent");
  2059. sourceLastInstr->InsertAfter(IR::BranchInstr::New(Js::OpCode::Br, onlyLink->GetSucc()->GetFirstInstr()->AsLabelInstr(), sourceLastInstr->m_func));
  2060. sourceLastInstr = sourceLastInstr->m_next;
  2061. }
  2062. BasicBlock * sinkPrevBlock = sinkBlock->prev;
  2063. IR::Instr * sinkPrevBlockLastInstr = sinkPrevBlock->GetLastInstr();
  2064. airlockBlock->loop = sinkBlock->loop;
  2065. airlockBlock->SetBlockNum(this->blockCount++);
  2066. #ifdef DBG
  2067. airlockBlock->isAirLockBlock = true;
  2068. #endif
  2069. //
  2070. // Fixup block linkage
  2071. //
  2072. // airlock block is inserted right before sourceBlock
  2073. airlockBlock->prev = sinkBlock->prev;
  2074. sinkBlock->prev = airlockBlock;
  2075. airlockBlock->next = sinkBlock;
  2076. airlockBlock->prev->next = airlockBlock;
  2077. //
  2078. // Fixup flow edges
  2079. //
  2080. sourceBlock->RemoveSucc(sinkBlock, this, false);
  2081. // Add sourceBlock -> airlockBlock
  2082. this->AddEdge(sourceBlock, airlockBlock);
  2083. // Add airlockBlock -> sinkBlock
  2084. edge->SetPred(airlockBlock);
  2085. airlockBlock->AddSucc(edge, this);
  2086. // Fixup data use count
  2087. airlockBlock->SetDataUseCount(1);
  2088. sourceBlock->DecrementDataUseCount();
  2089. //
  2090. // Fixup IR
  2091. //
  2092. // Maintain the instruction region for inlining
  2093. IR::LabelInstr *sinkLabel = sinkBlock->GetFirstInstr()->AsLabelInstr();
  2094. Func * sinkLabelFunc = sinkLabel->m_func;
  2095. IR::LabelInstr *airlockLabel = IR::LabelInstr::New(Js::OpCode::Label, sinkLabelFunc);
  2096. sinkPrevBlockLastInstr->InsertAfter(airlockLabel);
  2097. airlockBlock->SetFirstInstr(airlockLabel);
  2098. airlockLabel->SetBasicBlock(airlockBlock);
  2099. // Add br to sinkBlock from airlock block
  2100. IR::BranchInstr *airlockBr = IR::BranchInstr::New(Js::OpCode::Br, sinkLabel, sinkLabelFunc);
  2101. airlockBr->SetByteCodeOffset(sinkLabel);
  2102. airlockLabel->InsertAfter(airlockBr);
  2103. airlockBlock->SetLastInstr(airlockBr);
  2104. airlockLabel->SetByteCodeOffset(sinkLabel);
  2105. airlockLabel->SetRegion(sinkLabel->GetRegion());
  2106. // Fixup flow out of sourceBlock
  2107. IR::BranchInstr *sourceBr = sourceLastInstr->AsBranchInstr();
  2108. if (sourceBr->IsMultiBranch())
  2109. {
  2110. const bool replaced = sourceBr->AsMultiBrInstr()->ReplaceTarget(sinkLabel, airlockLabel);
  2111. Assert(replaced);
  2112. }
  2113. else if (sourceBr->GetTarget() == sinkLabel)
  2114. {
  2115. sourceBr->SetTarget(airlockLabel);
  2116. }
  2117. if (!sinkPrevBlockLastInstr->IsBranchInstr() || sinkPrevBlockLastInstr->AsBranchInstr()->HasFallThrough())
  2118. {
  2119. if (!sinkPrevBlock->isDeleted)
  2120. {
  2121. FlowEdge *dstEdge = this->FindEdge(sinkPrevBlock, sinkBlock);
  2122. if (dstEdge) // Possibility that sourceblock may be same as sinkPrevBlock
  2123. {
  2124. BasicBlock* compensationBlock = this->InsertCompensationCodeForBlockMove(dstEdge, true /*insert comp block to loop list*/, true);
  2125. compensationBlock->IncrementDataUseCount();
  2126. // We need to skip airlock compensation block in globopt as its inserted while globopt is iteration over the blocks.
  2127. compensationBlock->isAirLockCompensationBlock = true;
  2128. }
  2129. }
  2130. }
  2131. #if DBG_DUMP
  2132. this->Dump(true, _u("\n After insertion of airlock block \n"));
  2133. #endif
  2134. return airlockBlock;
  2135. }
  2136. // Insert a block on the given edge
  2137. BasicBlock *
  2138. FlowGraph::InsertCompensationCodeForBlockMove(FlowEdge * edge, bool insertToLoopList, bool sinkBlockLoop)
  2139. {
  2140. BasicBlock * compBlock = BasicBlock::New(this);
  2141. BasicBlock * sourceBlock = edge->GetPred();
  2142. BasicBlock * sinkBlock = edge->GetSucc();
  2143. BasicBlock * fallthroughBlock = sourceBlock->next;
  2144. IR::Instr * sourceLastInstr = sourceBlock->GetLastInstr();
  2145. compBlock->SetBlockNum(this->blockCount++);
  2146. if (insertToLoopList)
  2147. {
  2148. // For flow graph edits in
  2149. if (sinkBlockLoop)
  2150. {
  2151. if (sinkBlock->loop && sinkBlock->loop->GetHeadBlock() == sinkBlock)
  2152. {
  2153. // BLUE 531255: sinkblock may be the head block of new loop, we shouldn't insert compensation block to that loop
  2154. // Insert it to all the parent loop lists.
  2155. compBlock->loop = sinkBlock->loop->parent;
  2156. InsertCompBlockToLoopList(compBlock->loop, compBlock, sinkBlock, false);
  2157. }
  2158. else
  2159. {
  2160. compBlock->loop = sinkBlock->loop;
  2161. InsertCompBlockToLoopList(compBlock->loop, compBlock, sinkBlock, false); // sinkBlock or fallthroughBlock?
  2162. }
  2163. #ifdef DBG
  2164. compBlock->isBreakCompensationBlockAtSink = true;
  2165. #endif
  2166. }
  2167. else
  2168. {
  2169. compBlock->loop = sourceBlock->loop;
  2170. InsertCompBlockToLoopList(compBlock->loop, compBlock, sourceBlock, true);
  2171. #ifdef DBG
  2172. compBlock->isBreakCompensationBlockAtSource = true;
  2173. #endif
  2174. }
  2175. }
  2176. //
  2177. // Fixup block linkage
  2178. //
  2179. // compensation block is inserted right after sourceBlock
  2180. compBlock->next = fallthroughBlock;
  2181. fallthroughBlock->prev = compBlock;
  2182. compBlock->prev = sourceBlock;
  2183. sourceBlock->next = compBlock;
  2184. //
  2185. // Fixup flow edges
  2186. //
  2187. sourceBlock->RemoveSucc(sinkBlock, this, false);
  2188. // Add sourceBlock -> airlockBlock
  2189. this->AddEdge(sourceBlock, compBlock);
  2190. // Add airlockBlock -> sinkBlock
  2191. edge->SetPred(compBlock);
  2192. compBlock->AddSucc(edge, this);
  2193. //
  2194. // Fixup IR
  2195. //
  2196. // Maintain the instruction region for inlining
  2197. IR::LabelInstr *sinkLabel = sinkBlock->GetFirstInstr()->AsLabelInstr();
  2198. Func * sinkLabelFunc = sinkLabel->m_func;
  2199. IR::LabelInstr *compLabel = IR::LabelInstr::New(Js::OpCode::Label, sinkLabelFunc);
  2200. sourceLastInstr->InsertAfter(compLabel);
  2201. compBlock->SetFirstInstr(compLabel);
  2202. compLabel->SetBasicBlock(compBlock);
  2203. // Add br to sinkBlock from compensation block
  2204. IR::BranchInstr *compBr = IR::BranchInstr::New(Js::OpCode::Br, sinkLabel, sinkLabelFunc);
  2205. compBr->SetByteCodeOffset(sinkLabel);
  2206. compLabel->InsertAfter(compBr);
  2207. compBlock->SetLastInstr(compBr);
  2208. compLabel->SetByteCodeOffset(sinkLabel);
  2209. compLabel->SetRegion(sinkLabel->GetRegion());
  2210. // Fixup flow out of sourceBlock
  2211. if (sourceLastInstr->IsBranchInstr())
  2212. {
  2213. IR::BranchInstr *sourceBr = sourceLastInstr->AsBranchInstr();
  2214. Assert(sourceBr->IsMultiBranch() || sourceBr->IsConditional());
  2215. if (sourceBr->IsMultiBranch())
  2216. {
  2217. const bool replaced = sourceBr->AsMultiBrInstr()->ReplaceTarget(sinkLabel, compLabel);
  2218. Assert(replaced);
  2219. }
  2220. }
  2221. bool assignRegionsBeforeGlobopt = this->func->HasTry() && (this->func->DoOptimizeTry() ||
  2222. (this->func->IsSimpleJit() && this->func->hasBailout) ||
  2223. this->func->IsLoopBodyInTryFinally());
  2224. if (assignRegionsBeforeGlobopt)
  2225. {
  2226. UpdateRegionForBlockFromEHPred(compBlock);
  2227. }
  2228. return compBlock;
  2229. }
  2230. void
  2231. FlowGraph::RemoveUnreachableBlocks()
  2232. {
  2233. AnalysisAssert(this->blockList);
  2234. FOREACH_BLOCK(block, this)
  2235. {
  2236. block->isVisited = false;
  2237. }
  2238. NEXT_BLOCK;
  2239. this->blockList->isVisited = true;
  2240. FOREACH_BLOCK_EDITING(block, this)
  2241. {
  2242. if (block->isVisited)
  2243. {
  2244. FOREACH_SUCCESSOR_BLOCK(succ, block)
  2245. {
  2246. succ->isVisited = true;
  2247. } NEXT_SUCCESSOR_BLOCK;
  2248. }
  2249. else
  2250. {
  2251. this->RemoveBlock(block);
  2252. }
  2253. }
  2254. NEXT_BLOCK_EDITING;
  2255. }
  2256. // If block has no predecessor, remove it.
  2257. bool
  2258. FlowGraph::RemoveUnreachableBlock(BasicBlock *block, GlobOpt * globOpt)
  2259. {
  2260. bool isDead = false;
  2261. if ((block->GetPredList() == nullptr || block->GetPredList()->Empty()) && block != this->func->m_fg->blockList)
  2262. {
  2263. isDead = true;
  2264. }
  2265. else if (block->isLoopHeader)
  2266. {
  2267. // A dead loop still has back-edges pointing to it...
  2268. isDead = true;
  2269. FOREACH_PREDECESSOR_BLOCK(pred, block)
  2270. {
  2271. if (!block->loop->IsDescendentOrSelf(pred->loop))
  2272. {
  2273. isDead = false;
  2274. }
  2275. } NEXT_PREDECESSOR_BLOCK;
  2276. }
  2277. if (isDead)
  2278. {
  2279. this->RemoveBlock(block, globOpt);
  2280. return true;
  2281. }
  2282. return false;
  2283. }
  2284. IR::Instr *
  2285. FlowGraph::PeepTypedCm(IR::Instr *instr)
  2286. {
  2287. // Basic pattern, peep:
  2288. // t1 = CmEq a, b
  2289. // BrTrue_I4 $L1, t1
  2290. // Into:
  2291. // t1 = 1
  2292. // BrEq $L1, a, b
  2293. // t1 = 0
  2294. IR::Instr * instrNext = instr->GetNextRealInstrOrLabel();
  2295. // find intermediate Lds
  2296. IR::Instr * instrLd = nullptr;
  2297. if (instrNext->m_opcode == Js::OpCode::Ld_I4)
  2298. {
  2299. instrLd = instrNext;
  2300. instrNext = instrNext->GetNextRealInstrOrLabel();
  2301. }
  2302. IR::Instr * instrLd2 = nullptr;
  2303. if (instrNext->m_opcode == Js::OpCode::Ld_I4)
  2304. {
  2305. instrLd2 = instrNext;
  2306. instrNext = instrNext->GetNextRealInstrOrLabel();
  2307. }
  2308. // Find BrTrue/BrFalse
  2309. IR::Instr *instrBr;
  2310. bool brIsTrue;
  2311. if (instrNext->m_opcode == Js::OpCode::BrTrue_I4)
  2312. {
  2313. instrBr = instrNext;
  2314. brIsTrue = true;
  2315. }
  2316. else if (instrNext->m_opcode == Js::OpCode::BrFalse_I4)
  2317. {
  2318. instrBr = instrNext;
  2319. brIsTrue = false;
  2320. }
  2321. else
  2322. {
  2323. return nullptr;
  2324. }
  2325. AssertMsg(instrLd || (!instrLd && !instrLd2), "Either instrLd is non-null or both null");
  2326. // if we have intermediate Lds, then make sure pattern is:
  2327. // t1 = CmEq a, b
  2328. // t2 = Ld_A t1
  2329. // BrTrue $L1, t2
  2330. if (instrLd && !instrLd->GetSrc1()->IsEqual(instr->GetDst()))
  2331. {
  2332. return nullptr;
  2333. }
  2334. if (instrLd2 && !instrLd2->GetSrc1()->IsEqual(instrLd->GetDst()))
  2335. {
  2336. return nullptr;
  2337. }
  2338. // Make sure we have:
  2339. // t1 = CmEq a, b
  2340. // BrTrue/BrFalse t1
  2341. if (!(instr->GetDst()->IsEqual(instrBr->GetSrc1()) || (instrLd && instrLd->GetDst()->IsEqual(instrBr->GetSrc1())) || (instrLd2 && instrLd2->GetDst()->IsEqual(instrBr->GetSrc1()))))
  2342. {
  2343. return nullptr;
  2344. }
  2345. IR::Opnd * src1 = instr->UnlinkSrc1();
  2346. IR::Opnd * src2 = instr->UnlinkSrc2();
  2347. IR::Instr * instrNew;
  2348. IR::Opnd * tmpOpnd;
  2349. if (instr->GetDst()->IsEqual(src1) || (instrLd && instrLd->GetDst()->IsEqual(src1)) || (instrLd2 && instrLd2->GetDst()->IsEqual(src1)))
  2350. {
  2351. Assert(src1->IsInt32());
  2352. tmpOpnd = IR::RegOpnd::New(TyInt32, instr->m_func);
  2353. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, tmpOpnd, src1, instr->m_func);
  2354. instrNew->SetByteCodeOffset(instr);
  2355. instr->InsertBefore(instrNew);
  2356. src1 = tmpOpnd;
  2357. }
  2358. if (instr->GetDst()->IsEqual(src2) || (instrLd && instrLd->GetDst()->IsEqual(src2)) || (instrLd2 && instrLd2->GetDst()->IsEqual(src2)))
  2359. {
  2360. Assert(src2->IsInt32());
  2361. tmpOpnd = IR::RegOpnd::New(TyInt32, instr->m_func);
  2362. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, tmpOpnd, src2, instr->m_func);
  2363. instrNew->SetByteCodeOffset(instr);
  2364. instr->InsertBefore(instrNew);
  2365. src2 = tmpOpnd;
  2366. }
  2367. instrBr->ReplaceSrc1(src1);
  2368. instrBr->SetSrc2(src2);
  2369. Js::OpCode newOpcode;
  2370. switch (instr->m_opcode)
  2371. {
  2372. case Js::OpCode::CmEq_I4:
  2373. newOpcode = Js::OpCode::BrEq_I4;
  2374. break;
  2375. case Js::OpCode::CmGe_I4:
  2376. newOpcode = Js::OpCode::BrGe_I4;
  2377. break;
  2378. case Js::OpCode::CmGt_I4:
  2379. newOpcode = Js::OpCode::BrGt_I4;
  2380. break;
  2381. case Js::OpCode::CmLt_I4:
  2382. newOpcode = Js::OpCode::BrLt_I4;
  2383. break;
  2384. case Js::OpCode::CmLe_I4:
  2385. newOpcode = Js::OpCode::BrLe_I4;
  2386. break;
  2387. case Js::OpCode::CmUnGe_I4:
  2388. newOpcode = Js::OpCode::BrUnGe_I4;
  2389. break;
  2390. case Js::OpCode::CmUnGt_I4:
  2391. newOpcode = Js::OpCode::BrUnGt_I4;
  2392. break;
  2393. case Js::OpCode::CmUnLt_I4:
  2394. newOpcode = Js::OpCode::BrUnLt_I4;
  2395. break;
  2396. case Js::OpCode::CmUnLe_I4:
  2397. newOpcode = Js::OpCode::BrUnLe_I4;
  2398. break;
  2399. case Js::OpCode::CmNeq_I4:
  2400. newOpcode = Js::OpCode::BrNeq_I4;
  2401. break;
  2402. case Js::OpCode::CmEq_A:
  2403. newOpcode = Js::OpCode::BrEq_A;
  2404. break;
  2405. case Js::OpCode::CmGe_A:
  2406. newOpcode = Js::OpCode::BrGe_A;
  2407. break;
  2408. case Js::OpCode::CmGt_A:
  2409. newOpcode = Js::OpCode::BrGt_A;
  2410. break;
  2411. case Js::OpCode::CmLt_A:
  2412. newOpcode = Js::OpCode::BrLt_A;
  2413. break;
  2414. case Js::OpCode::CmLe_A:
  2415. newOpcode = Js::OpCode::BrLe_A;
  2416. break;
  2417. case Js::OpCode::CmUnGe_A:
  2418. newOpcode = Js::OpCode::BrUnGe_A;
  2419. break;
  2420. case Js::OpCode::CmUnGt_A:
  2421. newOpcode = Js::OpCode::BrUnGt_A;
  2422. break;
  2423. case Js::OpCode::CmUnLt_A:
  2424. newOpcode = Js::OpCode::BrUnLt_A;
  2425. break;
  2426. case Js::OpCode::CmUnLe_A:
  2427. newOpcode = Js::OpCode::BrUnLe_A;
  2428. break;
  2429. case Js::OpCode::CmNeq_A:
  2430. newOpcode = Js::OpCode::BrNeq_A;
  2431. break;
  2432. case Js::OpCode::CmSrEq_A:
  2433. newOpcode = Js::OpCode::BrSrEq_A;
  2434. break;
  2435. case Js::OpCode::CmSrNeq_A:
  2436. newOpcode = Js::OpCode::BrSrNeq_A;
  2437. break;
  2438. default:
  2439. newOpcode = Js::OpCode::InvalidOpCode;
  2440. Assume(UNREACHED);
  2441. }
  2442. instrBr->m_opcode = newOpcode;
  2443. if (brIsTrue)
  2444. {
  2445. instr->SetSrc1(IR::IntConstOpnd::New(1, TyInt8, instr->m_func));
  2446. instr->m_opcode = Js::OpCode::Ld_I4;
  2447. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instr->GetDst(), IR::IntConstOpnd::New(0, TyInt8, instr->m_func), instr->m_func);
  2448. instrNew->SetByteCodeOffset(instrBr);
  2449. instrBr->InsertAfter(instrNew);
  2450. if (instrLd)
  2451. {
  2452. instrLd->ReplaceSrc1(IR::IntConstOpnd::New(1, TyInt8, instr->m_func));
  2453. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instrLd->GetDst(), IR::IntConstOpnd::New(0, TyInt8, instr->m_func), instr->m_func);
  2454. instrNew->SetByteCodeOffset(instrBr);
  2455. instrBr->InsertAfter(instrNew);
  2456. if (instrLd2)
  2457. {
  2458. instrLd2->ReplaceSrc1(IR::IntConstOpnd::New(1, TyInt8, instr->m_func));
  2459. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instrLd2->GetDst(), IR::IntConstOpnd::New(0, TyInt8, instr->m_func), instr->m_func);
  2460. instrNew->SetByteCodeOffset(instrBr);
  2461. instrBr->InsertAfter(instrNew);
  2462. }
  2463. }
  2464. }
  2465. else
  2466. {
  2467. instrBr->AsBranchInstr()->Invert();
  2468. instr->SetSrc1(IR::IntConstOpnd::New(0, TyInt8, instr->m_func));
  2469. instr->m_opcode = Js::OpCode::Ld_I4;
  2470. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instr->GetDst(), IR::IntConstOpnd::New(1, TyInt8, instr->m_func), instr->m_func);
  2471. instrNew->SetByteCodeOffset(instrBr);
  2472. instrBr->InsertAfter(instrNew);
  2473. if (instrLd)
  2474. {
  2475. instrLd->ReplaceSrc1(IR::IntConstOpnd::New(0, TyInt8, instr->m_func));
  2476. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instrLd->GetDst(), IR::IntConstOpnd::New(1, TyInt8, instr->m_func), instr->m_func);
  2477. instrNew->SetByteCodeOffset(instrBr);
  2478. instrBr->InsertAfter(instrNew);
  2479. if (instrLd2)
  2480. {
  2481. instrLd2->ReplaceSrc1(IR::IntConstOpnd::New(0, TyInt8, instr->m_func));
  2482. instrNew = IR::Instr::New(Js::OpCode::Ld_I4, instrLd2->GetDst(), IR::IntConstOpnd::New(1, TyInt8, instr->m_func), instr->m_func);
  2483. instrNew->SetByteCodeOffset(instrBr);
  2484. instrBr->InsertAfter(instrNew);
  2485. }
  2486. }
  2487. }
  2488. return instrBr;
  2489. }
  2490. IR::Instr *
  2491. FlowGraph::PeepCm(IR::Instr *instr)
  2492. {
  2493. // Basic pattern, peep:
  2494. // t1 = CmEq a, b
  2495. // t2 = Ld_A t1
  2496. // BrTrue $L1, t2
  2497. // Into:
  2498. // t1 = True
  2499. // t2 = True
  2500. // BrEq $L1, a, b
  2501. // t1 = False
  2502. // t2 = False
  2503. //
  2504. // The true/false Ld_A's will most likely end up being dead-stores...
  2505. // Alternate Pattern
  2506. // t1= CmEq a, b
  2507. // BrTrue $L1, t1
  2508. // Into:
  2509. // BrEq $L1, a, b
  2510. Func *func = instr->m_func;
  2511. // Find Ld_A
  2512. IR::Instr *instrNext = instr->GetNextRealInstrOrLabel();
  2513. IR::Instr *inlineeEndInstr = nullptr;
  2514. IR::Instr *instrNew;
  2515. IR::Instr *instrLd = nullptr, *instrLd2 = nullptr;
  2516. IR::Instr *instrByteCode = instrNext;
  2517. bool ldFound = false;
  2518. IR::Opnd *brSrc = instr->GetDst();
  2519. if (instrNext->m_opcode == Js::OpCode::Ld_A && instrNext->GetSrc1()->IsEqual(instr->GetDst()))
  2520. {
  2521. ldFound = true;
  2522. instrLd = instrNext;
  2523. brSrc = instrNext->GetDst();
  2524. if (brSrc->IsEqual(instr->GetSrc1()) || brSrc->IsEqual(instr->GetSrc2()))
  2525. {
  2526. return nullptr;
  2527. }
  2528. instrNext = instrLd->GetNextRealInstrOrLabel();
  2529. // Is there a second Ld_A?
  2530. if (instrNext->m_opcode == Js::OpCode::Ld_A && instrNext->GetSrc1()->IsEqual(brSrc))
  2531. {
  2532. // We have:
  2533. // t1 = Cm
  2534. // t2 = t1 // ldSrc = t1
  2535. // t3 = t2 // ldDst = t3
  2536. // BrTrue/BrFalse t3
  2537. instrLd2 = instrNext;
  2538. brSrc = instrLd2->GetDst();
  2539. instrNext = instrLd2->GetNextRealInstrOrLabel();
  2540. if (brSrc->IsEqual(instr->GetSrc1()) || brSrc->IsEqual(instr->GetSrc2()))
  2541. {
  2542. return nullptr;
  2543. }
  2544. }
  2545. }
  2546. // Skip over InlineeEnd
  2547. if (instrNext->m_opcode == Js::OpCode::InlineeEnd)
  2548. {
  2549. inlineeEndInstr = instrNext;
  2550. instrNext = inlineeEndInstr->GetNextRealInstrOrLabel();
  2551. }
  2552. // Find BrTrue/BrFalse
  2553. bool brIsTrue;
  2554. if (instrNext->m_opcode == Js::OpCode::BrTrue_A)
  2555. {
  2556. brIsTrue = true;
  2557. }
  2558. else if (instrNext->m_opcode == Js::OpCode::BrFalse_A)
  2559. {
  2560. brIsTrue = false;
  2561. }
  2562. else
  2563. {
  2564. return nullptr;
  2565. }
  2566. IR::Instr *instrBr = instrNext;
  2567. // Make sure we have:
  2568. // t1 = Ld_A
  2569. // BrTrue/BrFalse t1
  2570. if (!instr->GetDst()->IsEqual(instrBr->GetSrc1()) && !brSrc->IsEqual(instrBr->GetSrc1()))
  2571. {
  2572. return nullptr;
  2573. }
  2574. //
  2575. // We have a match. Generate the new branch
  2576. //
  2577. // BrTrue/BrFalse t1
  2578. // Keep a copy of the inliner func and the bytecode offset of the original BrTrue/BrFalse if we end up inserting a new branch out of the inlinee,
  2579. // and sym id of t1 for proper restoration on a bailout before the branch.
  2580. Func* origBrFunc = instrBr->m_func;
  2581. uint32 origBrByteCodeOffset = instrBr->GetByteCodeOffset();
  2582. uint32 origBranchSrcSymId = instrBr->GetSrc1()->GetStackSym()->m_id;
  2583. bool origBranchSrcOpndIsJITOpt = instrBr->GetSrc1()->GetIsJITOptimizedReg();
  2584. instrBr->Unlink();
  2585. instr->InsertBefore(instrBr);
  2586. instrBr->ClearByteCodeOffset();
  2587. instrBr->SetByteCodeOffset(instr);
  2588. instrBr->FreeSrc1();
  2589. instrBr->SetSrc1(instr->UnlinkSrc1());
  2590. instrBr->SetSrc2(instr->UnlinkSrc2());
  2591. instrBr->m_func = instr->m_func;
  2592. Js::OpCode newOpcode = Js::OpCode::InvalidOpCode;
  2593. switch(instr->m_opcode)
  2594. {
  2595. case Js::OpCode::CmEq_A:
  2596. newOpcode = Js::OpCode::BrEq_A;
  2597. break;
  2598. case Js::OpCode::CmGe_A:
  2599. newOpcode = Js::OpCode::BrGe_A;
  2600. break;
  2601. case Js::OpCode::CmGt_A:
  2602. newOpcode = Js::OpCode::BrGt_A;
  2603. break;
  2604. case Js::OpCode::CmLt_A:
  2605. newOpcode = Js::OpCode::BrLt_A;
  2606. break;
  2607. case Js::OpCode::CmLe_A:
  2608. newOpcode = Js::OpCode::BrLe_A;
  2609. break;
  2610. case Js::OpCode::CmUnGe_A:
  2611. newOpcode = Js::OpCode::BrUnGe_A;
  2612. break;
  2613. case Js::OpCode::CmUnGt_A:
  2614. newOpcode = Js::OpCode::BrUnGt_A;
  2615. break;
  2616. case Js::OpCode::CmUnLt_A:
  2617. newOpcode = Js::OpCode::BrUnLt_A;
  2618. break;
  2619. case Js::OpCode::CmUnLe_A:
  2620. newOpcode = Js::OpCode::BrUnLe_A;
  2621. break;
  2622. case Js::OpCode::CmNeq_A:
  2623. newOpcode = Js::OpCode::BrNeq_A;
  2624. break;
  2625. case Js::OpCode::CmSrEq_A:
  2626. newOpcode = Js::OpCode::BrSrEq_A;
  2627. break;
  2628. case Js::OpCode::CmSrNeq_A:
  2629. newOpcode = Js::OpCode::BrSrNeq_A;
  2630. break;
  2631. default:
  2632. Assert(UNREACHED);
  2633. __assume(UNREACHED);
  2634. }
  2635. instrBr->m_opcode = newOpcode;
  2636. IR::AddrOpnd* trueOpnd = IR::AddrOpnd::New(func->GetScriptContextInfo()->GetTrueAddr(), IR::AddrOpndKindDynamicVar, func, true);
  2637. IR::AddrOpnd* falseOpnd = IR::AddrOpnd::New(func->GetScriptContextInfo()->GetFalseAddr(), IR::AddrOpndKindDynamicVar, func, true);
  2638. trueOpnd->SetValueType(ValueType::Boolean);
  2639. falseOpnd->SetValueType(ValueType::Boolean);
  2640. if (!brIsTrue)
  2641. {
  2642. instrBr->AsBranchInstr()->Invert();
  2643. }
  2644. if (ldFound)
  2645. {
  2646. // Split Ld_A into "Ld_A TRUE"/"Ld_A FALSE"
  2647. if (brIsTrue)
  2648. {
  2649. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetSrc1(), trueOpnd, instrBr->m_func);
  2650. instrNew->SetByteCodeOffset(instrBr);
  2651. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2652. instrBr->InsertBefore(instrNew);
  2653. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetDst(), trueOpnd, instrBr->m_func);
  2654. instrNew->SetByteCodeOffset(instrBr);
  2655. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2656. instrBr->InsertBefore(instrNew);
  2657. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetSrc1(), falseOpnd, instrLd->m_func);
  2658. instrLd->InsertBefore(instrNew);
  2659. instrNew->SetByteCodeOffset(instrLd);
  2660. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2661. instrLd->ReplaceSrc1(falseOpnd);
  2662. if (instrLd2)
  2663. {
  2664. instrLd2->ReplaceSrc1(falseOpnd);
  2665. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd2->GetDst(), trueOpnd, instrBr->m_func);
  2666. instrBr->InsertBefore(instrNew);
  2667. instrNew->SetByteCodeOffset(instrBr);
  2668. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2669. }
  2670. }
  2671. else
  2672. {
  2673. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetSrc1(), falseOpnd, instrBr->m_func);
  2674. instrBr->InsertBefore(instrNew);
  2675. instrNew->SetByteCodeOffset(instrBr);
  2676. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2677. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetDst(), falseOpnd, instrBr->m_func);
  2678. instrBr->InsertBefore(instrNew);
  2679. instrNew->SetByteCodeOffset(instrBr);
  2680. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2681. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd->GetSrc1(), trueOpnd, instrLd->m_func);
  2682. instrLd->InsertBefore(instrNew);
  2683. instrNew->SetByteCodeOffset(instrLd);
  2684. instrLd->ReplaceSrc1(trueOpnd);
  2685. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2686. if (instrLd2)
  2687. {
  2688. instrLd2->ReplaceSrc1(trueOpnd);
  2689. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd2->GetDst(), falseOpnd, instrBr->m_func);
  2690. instrBr->InsertBefore(instrNew);
  2691. instrNew->SetByteCodeOffset(instrBr);
  2692. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2693. }
  2694. }
  2695. }
  2696. // Fix InlineeEnd
  2697. if (inlineeEndInstr)
  2698. {
  2699. this->InsertInlineeOnFLowEdge(instrBr->AsBranchInstr(), inlineeEndInstr, instrByteCode , origBrFunc, origBrByteCodeOffset, origBranchSrcOpndIsJITOpt, origBranchSrcSymId);
  2700. }
  2701. if (instr->GetDst()->AsRegOpnd()->m_sym->HasByteCodeRegSlot())
  2702. {
  2703. Assert(!instrBr->AsBranchInstr()->HasByteCodeReg());
  2704. StackSym *dstSym = instr->GetDst()->AsRegOpnd()->m_sym;
  2705. instrBr->AsBranchInstr()->SetByteCodeReg(dstSym->GetByteCodeRegSlot());
  2706. }
  2707. brSrc = brSrc->Copy(this->func);
  2708. // We need brSrc later, but instr->Remove() might delete it...
  2709. IR::AutoReuseOpnd brSrcAutoCopy(brSrc, this->func, true);
  2710. instr->Remove();
  2711. //
  2712. // Try optimizing through a second branch.
  2713. // Peep:
  2714. //
  2715. // t2 = True;
  2716. // BrTrue $L1
  2717. // ...
  2718. // L1:
  2719. // t1 = Ld_A t2
  2720. // BrTrue $L2
  2721. //
  2722. // Into:
  2723. // t2 = True;
  2724. // t1 = True;
  2725. // BrTrue $L2 <---
  2726. // ...
  2727. // L1:
  2728. // t1 = Ld_A t2
  2729. // BrTrue $L2
  2730. //
  2731. // This cleanup helps expose second level Cm peeps.
  2732. IR::Instr *instrLd3 = instrBr->AsBranchInstr()->GetTarget()->GetNextRealInstrOrLabel();
  2733. // Skip over branch to branch
  2734. while (instrLd3->m_opcode == Js::OpCode::Br)
  2735. {
  2736. instrLd3 = instrLd3->AsBranchInstr()->GetTarget()->GetNextRealInstrOrLabel();
  2737. }
  2738. // Find Ld_A
  2739. if (instrLd3->m_opcode != Js::OpCode::Ld_A)
  2740. {
  2741. return instrBr;
  2742. }
  2743. IR::Instr *instrBr2 = instrLd3->GetNextRealInstrOrLabel();
  2744. IR::Instr *inlineeEndInstr2 = nullptr;
  2745. // InlineeEnd?
  2746. // REVIEW: Can we handle 2 inlineeEnds?
  2747. if (instrBr2->m_opcode == Js::OpCode::InlineeEnd && !inlineeEndInstr)
  2748. {
  2749. inlineeEndInstr2 = instrBr2;
  2750. instrBr2 = instrBr2->GetNextRealInstrOrLabel();
  2751. }
  2752. // Find branch
  2753. bool brIsTrue2;
  2754. if (instrBr2->m_opcode == Js::OpCode::BrTrue_A)
  2755. {
  2756. brIsTrue2 = true;
  2757. }
  2758. else if (instrBr2->m_opcode == Js::OpCode::BrFalse_A)
  2759. {
  2760. brIsTrue2 = false;
  2761. }
  2762. else
  2763. {
  2764. return nullptr;
  2765. }
  2766. // Make sure Ld_A operates on the right tmps.
  2767. if (!instrLd3->GetDst()->IsEqual(instrBr2->GetSrc1()) || !brSrc->IsEqual(instrLd3->GetSrc1()))
  2768. {
  2769. return nullptr;
  2770. }
  2771. if (instrLd3->GetDst()->IsEqual(instrBr->GetSrc1()) || instrLd3->GetDst()->IsEqual(instrBr->GetSrc2()))
  2772. {
  2773. return nullptr;
  2774. }
  2775. // Make sure that the reg we're assigning to is not live in the intervening instructions (if this is a forward branch).
  2776. if (instrLd3->GetByteCodeOffset() > instrBr->GetByteCodeOffset())
  2777. {
  2778. StackSym *symLd3 = instrLd3->GetDst()->AsRegOpnd()->m_sym;
  2779. if (IR::Instr::HasSymUseInRange(symLd3, instrBr->m_next, instrLd3))
  2780. {
  2781. return nullptr;
  2782. }
  2783. }
  2784. //
  2785. // We have a match!
  2786. //
  2787. if(inlineeEndInstr2)
  2788. {
  2789. origBrFunc = instrBr2->m_func;
  2790. origBrByteCodeOffset = instrBr2->GetByteCodeOffset();
  2791. origBranchSrcSymId = instrBr2->GetSrc1()->GetStackSym()->m_id;
  2792. }
  2793. // Fix Ld_A
  2794. if (brIsTrue)
  2795. {
  2796. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd3->GetDst(), trueOpnd, instrBr->m_func);
  2797. instrBr->InsertBefore(instrNew);
  2798. instrNew->SetByteCodeOffset(instrBr);
  2799. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2800. }
  2801. else
  2802. {
  2803. instrNew = IR::Instr::New(Js::OpCode::Ld_A, instrLd3->GetDst(), falseOpnd, instrBr->m_func);
  2804. instrBr->InsertBefore(instrNew);
  2805. instrNew->SetByteCodeOffset(instrBr);
  2806. instrNew->GetDst()->AsRegOpnd()->m_fgPeepTmp = true;
  2807. }
  2808. IR::LabelInstr *brTarget2;
  2809. // Retarget branch
  2810. if (brIsTrue2 == brIsTrue)
  2811. {
  2812. brTarget2 = instrBr2->AsBranchInstr()->GetTarget();
  2813. }
  2814. else
  2815. {
  2816. brTarget2 = IR::LabelInstr::New(Js::OpCode::Label, instrBr2->m_func);
  2817. brTarget2->SetByteCodeOffset(instrBr2->m_next);
  2818. instrBr2->InsertAfter(brTarget2);
  2819. }
  2820. instrBr->AsBranchInstr()->SetTarget(brTarget2);
  2821. // InlineeEnd?
  2822. if (inlineeEndInstr2)
  2823. {
  2824. this->InsertInlineeOnFLowEdge(instrBr->AsBranchInstr(), inlineeEndInstr2, instrByteCode, origBrFunc, origBrByteCodeOffset, origBranchSrcOpndIsJITOpt, origBranchSrcSymId);
  2825. }
  2826. return instrBr;
  2827. }
  2828. void
  2829. FlowGraph::InsertInlineeOnFLowEdge(IR::BranchInstr *instrBr, IR::Instr *inlineeEndInstr, IR::Instr *instrBytecode, Func* origBrFunc, uint32 origByteCodeOffset, bool origBranchSrcOpndIsJITOpt, uint32 origBranchSrcSymId)
  2830. {
  2831. // Helper for PeepsCm code.
  2832. //
  2833. // We've skipped some InlineeEnd. Globopt expects to see these
  2834. // on all flow paths out of the inlinee. Insert an InlineeEnd
  2835. // on the new path:
  2836. // BrEq $L1, a, b
  2837. // Becomes:
  2838. // BrNeq $L2, a, b
  2839. // InlineeEnd
  2840. // Br $L1
  2841. // L2:
  2842. instrBr->AsBranchInstr()->Invert();
  2843. IR::BranchInstr *newBr = IR::BranchInstr::New(Js::OpCode::Br, instrBr->AsBranchInstr()->GetTarget(), origBrFunc);
  2844. newBr->SetByteCodeOffset(origByteCodeOffset);
  2845. instrBr->InsertAfter(newBr);
  2846. IR::LabelInstr *newLabel = IR::LabelInstr::New(Js::OpCode::Label, instrBr->m_func);
  2847. newLabel->SetByteCodeOffset(instrBytecode);
  2848. newBr->InsertAfter(newLabel);
  2849. instrBr->AsBranchInstr()->SetTarget(newLabel);
  2850. IR::Instr *newInlineeEnd = IR::Instr::New(Js::OpCode::InlineeEnd, inlineeEndInstr->m_func);
  2851. newInlineeEnd->SetSrc1(inlineeEndInstr->GetSrc1());
  2852. newInlineeEnd->SetSrc2(inlineeEndInstr->GetSrc2());
  2853. newInlineeEnd->SetByteCodeOffset(instrBytecode);
  2854. newInlineeEnd->SetIsCloned(true); // Mark it as cloned - this is used later by the inlinee args optimization
  2855. newBr->InsertBefore(newInlineeEnd);
  2856. IR::ByteCodeUsesInstr * useOrigBranchSrcInstr = IR::ByteCodeUsesInstr::New(origBrFunc, origByteCodeOffset);
  2857. useOrigBranchSrcInstr->SetRemovedOpndSymbol(origBranchSrcOpndIsJITOpt, origBranchSrcSymId);
  2858. newBr->InsertBefore(useOrigBranchSrcInstr);
  2859. uint newBrFnNumber = newBr->m_func->GetFunctionNumber();
  2860. Assert(newBrFnNumber == origBrFunc->GetFunctionNumber());
  2861. // The function numbers of the new branch and the inlineeEnd instruction should be different (ensuring that the new branch is not added in the inlinee but in the inliner).
  2862. // Only case when they can be same is recursive calls - inlinee and inliner are the same function
  2863. Assert(newBrFnNumber != inlineeEndInstr->m_func->GetFunctionNumber() ||
  2864. newBrFnNumber == inlineeEndInstr->m_func->GetParentFunc()->GetFunctionNumber());
  2865. }
  2866. BasicBlock *
  2867. BasicBlock::New(FlowGraph * graph)
  2868. {
  2869. BasicBlock * block;
  2870. block = JitAnew(graph->alloc, BasicBlock, graph->alloc, graph->GetFunc());
  2871. return block;
  2872. }
  2873. void
  2874. BasicBlock::AddPred(FlowEdge * edge, FlowGraph * graph)
  2875. {
  2876. this->predList.Prepend(graph->alloc, edge);
  2877. }
  2878. void
  2879. BasicBlock::AddSucc(FlowEdge * edge, FlowGraph * graph)
  2880. {
  2881. this->succList.Prepend(graph->alloc, edge);
  2882. }
  2883. void
  2884. BasicBlock::RemovePred(BasicBlock *block, FlowGraph * graph)
  2885. {
  2886. this->RemovePred(block, graph, true, false);
  2887. }
  2888. void
  2889. BasicBlock::RemoveSucc(BasicBlock *block, FlowGraph * graph)
  2890. {
  2891. this->RemoveSucc(block, graph, true, false);
  2892. }
  2893. void
  2894. BasicBlock::RemoveDeadPred(BasicBlock *block, FlowGraph * graph)
  2895. {
  2896. this->RemovePred(block, graph, true, true);
  2897. }
  2898. void
  2899. BasicBlock::RemoveDeadSucc(BasicBlock *block, FlowGraph * graph)
  2900. {
  2901. this->RemoveSucc(block, graph, true, true);
  2902. }
  2903. void
  2904. BasicBlock::RemovePred(BasicBlock *block, FlowGraph * graph, bool doCleanSucc, bool moveToDead)
  2905. {
  2906. FOREACH_SLISTBASECOUNTED_ENTRY_EDITING(FlowEdge*, edge, this->GetPredList(), iter)
  2907. {
  2908. if (edge->GetPred() == block)
  2909. {
  2910. BasicBlock *blockSucc = edge->GetSucc();
  2911. if (moveToDead)
  2912. {
  2913. iter.MoveCurrentTo(this->GetDeadPredList());
  2914. }
  2915. else
  2916. {
  2917. iter.RemoveCurrent(graph->alloc);
  2918. }
  2919. if (doCleanSucc)
  2920. {
  2921. block->RemoveSucc(this, graph, false, moveToDead);
  2922. }
  2923. if (blockSucc->isLoopHeader && blockSucc->loop && blockSucc->GetPredList()->HasOne())
  2924. {
  2925. Loop *loop = blockSucc->loop;
  2926. loop->isDead = true;
  2927. }
  2928. return;
  2929. }
  2930. } NEXT_SLISTBASECOUNTED_ENTRY_EDITING;
  2931. AssertMsg(UNREACHED, "Edge not found.");
  2932. }
  2933. void
  2934. BasicBlock::RemoveSucc(BasicBlock *block, FlowGraph * graph, bool doCleanPred, bool moveToDead)
  2935. {
  2936. FOREACH_SLISTBASECOUNTED_ENTRY_EDITING(FlowEdge*, edge, this->GetSuccList(), iter)
  2937. {
  2938. if (edge->GetSucc() == block)
  2939. {
  2940. if (moveToDead)
  2941. {
  2942. iter.MoveCurrentTo(this->GetDeadSuccList());
  2943. }
  2944. else
  2945. {
  2946. iter.RemoveCurrent(graph->alloc);
  2947. }
  2948. if (doCleanPred)
  2949. {
  2950. block->RemovePred(this, graph, false, moveToDead);
  2951. }
  2952. if (block->isLoopHeader && block->loop && block->GetPredList()->HasOne())
  2953. {
  2954. Loop *loop = block->loop;
  2955. loop->isDead = true;
  2956. }
  2957. return;
  2958. }
  2959. } NEXT_SLISTBASECOUNTED_ENTRY_EDITING;
  2960. AssertMsg(UNREACHED, "Edge not found.");
  2961. }
  2962. void
  2963. BasicBlock::UnlinkPred(BasicBlock *block)
  2964. {
  2965. this->UnlinkPred(block, true);
  2966. }
  2967. void
  2968. BasicBlock::UnlinkSucc(BasicBlock *block)
  2969. {
  2970. this->UnlinkSucc(block, true);
  2971. }
  2972. void
  2973. BasicBlock::UnlinkPred(BasicBlock *block, bool doCleanSucc)
  2974. {
  2975. FOREACH_SLISTBASECOUNTED_ENTRY_EDITING(FlowEdge*, edge, this->GetPredList(), iter)
  2976. {
  2977. if (edge->GetPred() == block)
  2978. {
  2979. iter.UnlinkCurrent();
  2980. if (doCleanSucc)
  2981. {
  2982. block->UnlinkSucc(this, false);
  2983. }
  2984. return;
  2985. }
  2986. } NEXT_SLISTBASECOUNTED_ENTRY_EDITING;
  2987. AssertMsg(UNREACHED, "Edge not found.");
  2988. }
  2989. void
  2990. BasicBlock::UnlinkSucc(BasicBlock *block, bool doCleanPred)
  2991. {
  2992. FOREACH_SLISTBASECOUNTED_ENTRY_EDITING(FlowEdge*, edge, this->GetSuccList(), iter)
  2993. {
  2994. if (edge->GetSucc() == block)
  2995. {
  2996. iter.UnlinkCurrent();
  2997. if (doCleanPred)
  2998. {
  2999. block->UnlinkPred(this, false);
  3000. }
  3001. return;
  3002. }
  3003. } NEXT_SLISTBASECOUNTED_ENTRY_EDITING;
  3004. AssertMsg(UNREACHED, "Edge not found.");
  3005. }
  3006. bool
  3007. BasicBlock::IsLandingPad()
  3008. {
  3009. BasicBlock * nextBlock = this->GetNext();
  3010. return nextBlock && nextBlock->loop && nextBlock->isLoopHeader && nextBlock->loop->landingPad == this;
  3011. }
  3012. BailOutInfo *
  3013. BasicBlock::CreateLoopTopBailOutInfo(GlobOpt * globOpt)
  3014. {
  3015. IR::Instr * firstInstr = this->GetFirstInstr();
  3016. BailOutInfo* bailOutInfo = JitAnew(globOpt->func->m_alloc, BailOutInfo, firstInstr->GetByteCodeOffset(), firstInstr->m_func);
  3017. bailOutInfo->isLoopTopBailOutInfo = true;
  3018. globOpt->FillBailOutInfo(this, bailOutInfo);
  3019. #if ENABLE_DEBUG_CONFIG_OPTIONS
  3020. bailOutInfo->bailOutOpcode = Js::OpCode::LoopBodyStart;
  3021. #endif
  3022. return bailOutInfo;
  3023. }
  3024. IR::Instr *
  3025. FlowGraph::RemoveInstr(IR::Instr *instr, GlobOpt * globOpt)
  3026. {
  3027. IR::Instr *instrPrev = instr->m_prev;
  3028. if (globOpt)
  3029. {
  3030. // Removing block during glob opt. Need to maintain the graph so that
  3031. // bailout will record the byte code use in case the dead code is exposed
  3032. // by dyno-pogo optimization (where bailout need the byte code uses from
  3033. // the dead blocks where it may not be dead after bailing out)
  3034. if (instr->IsLabelInstr())
  3035. {
  3036. instr->AsLabelInstr()->m_isLoopTop = false;
  3037. return instr;
  3038. }
  3039. else if (instr->IsByteCodeUsesInstr())
  3040. {
  3041. return instr;
  3042. }
  3043. /*
  3044. * Scope object has to be implicitly live whenever Heap Arguments object is live.
  3045. * - When we restore HeapArguments object in the bail out path, it expects the scope object also to be restored - if one was created.
  3046. */
  3047. Js::OpCode opcode = instr->m_opcode;
  3048. if (opcode == Js::OpCode::LdElemI_A && instr->DoStackArgsOpt(this->func) &&
  3049. globOpt->CurrentBlockData()->IsArgumentsOpnd(instr->GetSrc1()) && instr->m_func->GetScopeObjSym())
  3050. {
  3051. IR::ByteCodeUsesInstr * byteCodeUsesInstr = IR::ByteCodeUsesInstr::New(instr);
  3052. byteCodeUsesInstr->SetNonOpndSymbol(instr->m_func->GetScopeObjSym()->m_id);
  3053. instr->InsertAfter(byteCodeUsesInstr);
  3054. }
  3055. IR::ByteCodeUsesInstr * newByteCodeUseInstr = globOpt->ConvertToByteCodeUses(instr);
  3056. if (newByteCodeUseInstr != nullptr)
  3057. {
  3058. // We don't care about property used in these instruction
  3059. // It is only necessary for field copy prop so that we will keep the implicit call
  3060. // up to the copy prop location.
  3061. newByteCodeUseInstr->propertySymUse = nullptr;
  3062. if (opcode == Js::OpCode::Yield)
  3063. {
  3064. IR::Instr *instrLabel = newByteCodeUseInstr->m_next;
  3065. while (instrLabel->m_opcode != Js::OpCode::Label)
  3066. {
  3067. instrLabel = instrLabel->m_next;
  3068. }
  3069. func->RemoveDeadYieldOffsetResumeLabel(instrLabel->AsLabelInstr());
  3070. instrLabel->AsLabelInstr()->m_hasNonBranchRef = false;
  3071. }
  3072. // Save the last instruction to update the block with
  3073. return newByteCodeUseInstr;
  3074. }
  3075. else
  3076. {
  3077. return instrPrev;
  3078. }
  3079. }
  3080. else
  3081. {
  3082. instr->Remove();
  3083. return instrPrev;
  3084. }
  3085. }
  3086. void
  3087. FlowGraph::RemoveBlock(BasicBlock *block, GlobOpt * globOpt, bool tailDuping)
  3088. {
  3089. Assert(!block->isDead && !block->isDeleted);
  3090. IR::Instr * lastInstr = nullptr;
  3091. FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrNext, block)
  3092. {
  3093. if (instr->m_opcode == Js::OpCode::FunctionExit)
  3094. {
  3095. // Removing FunctionExit causes problems downstream...
  3096. // We could change the opcode, or have FunctionEpilog/FunctionExit to get
  3097. // rid of the epilog.
  3098. break;
  3099. }
  3100. if (instr == block->GetFirstInstr())
  3101. {
  3102. Assert(instr->IsLabelInstr());
  3103. instr->AsLabelInstr()->m_isLoopTop = false;
  3104. instr->AsLabelInstr()->m_hasNonBranchRef = false;
  3105. }
  3106. else
  3107. {
  3108. lastInstr = this->RemoveInstr(instr, globOpt);
  3109. }
  3110. } NEXT_INSTR_IN_BLOCK_EDITING;
  3111. if (lastInstr)
  3112. {
  3113. block->SetLastInstr(lastInstr);
  3114. }
  3115. FOREACH_SLISTBASECOUNTED_ENTRY(FlowEdge*, edge, block->GetPredList())
  3116. {
  3117. edge->GetPred()->RemoveSucc(block, this, false, globOpt != nullptr);
  3118. } NEXT_SLISTBASECOUNTED_ENTRY;
  3119. FOREACH_SLISTBASECOUNTED_ENTRY(FlowEdge*, edge, block->GetSuccList())
  3120. {
  3121. edge->GetSucc()->RemovePred(block, this, false, globOpt != nullptr);
  3122. } NEXT_SLISTBASECOUNTED_ENTRY;
  3123. if (block->isLoopHeader && this->loopList)
  3124. {
  3125. // If loop graph is built, remove loop from loopList
  3126. Loop **pPrevLoop = &this->loopList;
  3127. while (*pPrevLoop != block->loop)
  3128. {
  3129. pPrevLoop = &((*pPrevLoop)->next);
  3130. }
  3131. *pPrevLoop = (*pPrevLoop)->next;
  3132. this->hasLoop = (this->loopList != nullptr);
  3133. }
  3134. if (globOpt != nullptr)
  3135. {
  3136. block->isDead = true;
  3137. block->GetPredList()->MoveTo(block->GetDeadPredList());
  3138. block->GetSuccList()->MoveTo(block->GetDeadSuccList());
  3139. }
  3140. if (tailDuping)
  3141. {
  3142. block->isDead = true;
  3143. }
  3144. block->isDeleted = true;
  3145. block->SetDataUseCount(0);
  3146. }
  3147. void
  3148. BasicBlock::UnlinkInstr(IR::Instr * instr)
  3149. {
  3150. Assert(this->Contains(instr));
  3151. Assert(this->GetFirstInstr() != this->GetLastInstr());
  3152. if (instr == this->GetFirstInstr())
  3153. {
  3154. Assert(!this->GetFirstInstr()->IsLabelInstr());
  3155. this->SetFirstInstr(instr->m_next);
  3156. }
  3157. else if (instr == this->GetLastInstr())
  3158. {
  3159. this->SetLastInstr(instr->m_prev);
  3160. }
  3161. instr->Unlink();
  3162. }
  3163. void
  3164. BasicBlock::RemoveInstr(IR::Instr * instr)
  3165. {
  3166. Assert(this->Contains(instr));
  3167. if (instr == this->GetFirstInstr())
  3168. {
  3169. this->SetFirstInstr(instr->m_next);
  3170. }
  3171. else if (instr == this->GetLastInstr())
  3172. {
  3173. this->SetLastInstr(instr->m_prev);
  3174. }
  3175. instr->Remove();
  3176. }
  3177. void
  3178. BasicBlock::InsertInstrBefore(IR::Instr *newInstr, IR::Instr *beforeThisInstr)
  3179. {
  3180. Assert(this->Contains(beforeThisInstr));
  3181. beforeThisInstr->InsertBefore(newInstr);
  3182. if(this->GetFirstInstr() == beforeThisInstr)
  3183. {
  3184. Assert(!beforeThisInstr->IsLabelInstr());
  3185. this->SetFirstInstr(newInstr);
  3186. }
  3187. }
  3188. void
  3189. BasicBlock::InsertInstrAfter(IR::Instr *newInstr, IR::Instr *afterThisInstr)
  3190. {
  3191. Assert(this->Contains(afterThisInstr));
  3192. afterThisInstr->InsertAfter(newInstr);
  3193. if (this->GetLastInstr() == afterThisInstr)
  3194. {
  3195. Assert(afterThisInstr->HasFallThrough());
  3196. this->SetLastInstr(newInstr);
  3197. }
  3198. }
  3199. void
  3200. BasicBlock::InsertAfter(IR::Instr *newInstr)
  3201. {
  3202. Assert(this->GetLastInstr()->HasFallThrough());
  3203. this->GetLastInstr()->InsertAfter(newInstr);
  3204. this->SetLastInstr(newInstr);
  3205. }
  3206. void
  3207. Loop::SetHasCall()
  3208. {
  3209. Loop * current = this;
  3210. do
  3211. {
  3212. if (current->hasCall)
  3213. {
  3214. #if DBG
  3215. current = current->parent;
  3216. while (current)
  3217. {
  3218. Assert(current->hasCall);
  3219. current = current->parent;
  3220. }
  3221. #endif
  3222. break;
  3223. }
  3224. current->hasCall = true;
  3225. current = current->parent;
  3226. }
  3227. while (current != nullptr);
  3228. }
  3229. void
  3230. Loop::SetImplicitCallFlags(Js::ImplicitCallFlags newFlags)
  3231. {
  3232. Loop * current = this;
  3233. do
  3234. {
  3235. if ((current->implicitCallFlags & newFlags) == newFlags)
  3236. {
  3237. #if DBG
  3238. current = current->parent;
  3239. while (current)
  3240. {
  3241. Assert((current->implicitCallFlags & newFlags) == newFlags);
  3242. current = current->parent;
  3243. }
  3244. #endif
  3245. break;
  3246. }
  3247. newFlags = (Js::ImplicitCallFlags)(implicitCallFlags | newFlags);
  3248. current->implicitCallFlags = newFlags;
  3249. current = current->parent;
  3250. }
  3251. while (current != nullptr);
  3252. }
  3253. Js::ImplicitCallFlags
  3254. Loop::GetImplicitCallFlags()
  3255. {
  3256. if (this->implicitCallFlags == Js::ImplicitCall_HasNoInfo)
  3257. {
  3258. if (this->parent == nullptr)
  3259. {
  3260. // We don't have any information, and we don't have any parent, so just assume that there aren't any implicit calls
  3261. this->implicitCallFlags = Js::ImplicitCall_None;
  3262. }
  3263. else
  3264. {
  3265. // We don't have any information, get it from the parent and hope for the best
  3266. this->implicitCallFlags = this->parent->GetImplicitCallFlags();
  3267. }
  3268. }
  3269. return this->implicitCallFlags;
  3270. }
  3271. bool
  3272. Loop::CanDoFieldCopyProp()
  3273. {
  3274. #if DBG_DUMP
  3275. if (((this->implicitCallFlags & ~(Js::ImplicitCall_External)) == 0) &&
  3276. Js::Configuration::Global.flags.Trace.IsEnabled(Js::HostOptPhase))
  3277. {
  3278. Output::Print(_u("fieldcopyprop disabled because external: loop count: %d"), GetLoopNumber());
  3279. GetFunc()->DumpFullFunctionName();
  3280. Output::Print(_u("\n"));
  3281. Output::Flush();
  3282. }
  3283. #endif
  3284. return GlobOpt::ImplicitCallFlagsAllowOpts(this);
  3285. }
  3286. bool
  3287. Loop::CanHoistInvariants() const
  3288. {
  3289. Func * func = this->GetHeadBlock()->firstInstr->m_func->GetTopFunc();
  3290. if (PHASE_OFF(Js::InvariantsPhase, func))
  3291. {
  3292. return false;
  3293. }
  3294. return true;
  3295. }
  3296. IR::LabelInstr *
  3297. Loop::GetLoopTopInstr() const
  3298. {
  3299. IR::LabelInstr * instr = nullptr;
  3300. if (this->topFunc->isFlowGraphValid)
  3301. {
  3302. instr = this->GetHeadBlock()->GetFirstInstr()->AsLabelInstr();
  3303. }
  3304. else
  3305. {
  3306. // Flowgraph gets torn down after the globopt, so can't get the loopTop from the head block.
  3307. instr = this->loopTopLabel;
  3308. }
  3309. if (instr)
  3310. {
  3311. Assert(instr->m_isLoopTop);
  3312. }
  3313. return instr;
  3314. }
  3315. void
  3316. Loop::SetLoopTopInstr(IR::LabelInstr * loopTop)
  3317. {
  3318. this->loopTopLabel = loopTop;
  3319. }
  3320. bool
  3321. Loop::IsSymAssignedToInSelfOrParents(StackSym * const sym) const
  3322. {
  3323. for (const Loop* curLoop = this; curLoop != nullptr; curLoop = curLoop->parent)
  3324. {
  3325. if (curLoop->symsAssignedToInLoop->Test(sym->m_id))
  3326. {
  3327. return true;
  3328. }
  3329. }
  3330. return false;
  3331. }
  3332. BasicBlock *
  3333. Loop::GetAnyTailBlock() const
  3334. {
  3335. BasicBlock * tail = nullptr;
  3336. BasicBlock * loopHeader = this->GetHeadBlock();
  3337. FOREACH_PREDECESSOR_BLOCK(pred, loopHeader)
  3338. {
  3339. if (this->IsDescendentOrSelf(pred->loop))
  3340. {
  3341. tail = pred;
  3342. }
  3343. } NEXT_PREDECESSOR_BLOCK;
  3344. Assert(tail);
  3345. return tail;
  3346. }
  3347. #if DBG_DUMP
  3348. uint
  3349. Loop::GetLoopNumber() const
  3350. {
  3351. IR::LabelInstr * loopTopInstr = this->GetLoopTopInstr();
  3352. if (loopTopInstr->IsProfiledLabelInstr())
  3353. {
  3354. return loopTopInstr->AsProfiledLabelInstr()->loopNum;
  3355. }
  3356. return Js::LoopHeader::NoLoop;
  3357. }
  3358. bool
  3359. BasicBlock::Contains(IR::Instr * instr)
  3360. {
  3361. FOREACH_INSTR_IN_BLOCK(blockInstr, this)
  3362. {
  3363. if (instr == blockInstr)
  3364. {
  3365. return true;
  3366. }
  3367. }
  3368. NEXT_INSTR_IN_BLOCK;
  3369. return false;
  3370. }
  3371. #endif
  3372. FlowEdge *
  3373. FlowEdge::New(FlowGraph * graph)
  3374. {
  3375. FlowEdge * edge;
  3376. edge = JitAnew(graph->alloc, FlowEdge);
  3377. return edge;
  3378. }
  3379. bool
  3380. Loop::IsDescendentOrSelf(Loop const * loop) const
  3381. {
  3382. Loop const * currentLoop = loop;
  3383. while (currentLoop != nullptr)
  3384. {
  3385. if (currentLoop == this)
  3386. {
  3387. return true;
  3388. }
  3389. currentLoop = currentLoop->parent;
  3390. }
  3391. return false;
  3392. }
  3393. void FlowGraph::SafeRemoveInstr(IR::Instr *instr)
  3394. {
  3395. BasicBlock *block;
  3396. if (instr->m_next->IsLabelInstr())
  3397. {
  3398. block = instr->m_next->AsLabelInstr()->GetBasicBlock()->GetPrev();
  3399. block->RemoveInstr(instr);
  3400. }
  3401. else if (instr->IsLabelInstr())
  3402. {
  3403. block = instr->AsLabelInstr()->GetBasicBlock();
  3404. block->RemoveInstr(instr);
  3405. }
  3406. else
  3407. {
  3408. Assert(!instr->EndsBasicBlock() && !instr->StartsBasicBlock());
  3409. instr->Remove();
  3410. }
  3411. }
  3412. bool FlowGraph::IsUnsignedOpnd(IR::Opnd *src, IR::Opnd **pShrSrc1)
  3413. {
  3414. // Look for an unsigned constant, or the result of an unsigned shift by zero
  3415. if (!src->IsRegOpnd())
  3416. {
  3417. return false;
  3418. }
  3419. if (!src->AsRegOpnd()->m_sym->IsSingleDef())
  3420. {
  3421. return false;
  3422. }
  3423. if (src->AsRegOpnd()->m_sym->IsIntConst())
  3424. {
  3425. int32 intConst = src->AsRegOpnd()->m_sym->GetIntConstValue();
  3426. if (intConst >= 0)
  3427. {
  3428. *pShrSrc1 = src;
  3429. return true;
  3430. }
  3431. else
  3432. {
  3433. return false;
  3434. }
  3435. }
  3436. IR::Instr * shrUInstr = src->AsRegOpnd()->m_sym->GetInstrDef();
  3437. if (shrUInstr->m_opcode != Js::OpCode::ShrU_A)
  3438. {
  3439. return false;
  3440. }
  3441. IR::Opnd *shrCnt = shrUInstr->GetSrc2();
  3442. if (!shrCnt->IsRegOpnd() || !shrCnt->AsRegOpnd()->m_sym->IsTaggableIntConst() || shrCnt->AsRegOpnd()->m_sym->GetIntConstValue() != 0)
  3443. {
  3444. return false;
  3445. }
  3446. IR::Opnd *shrSrc = shrUInstr->GetSrc1();
  3447. *pShrSrc1 = shrSrc;
  3448. return true;
  3449. }
  3450. bool FlowGraph::UnsignedCmpPeep(IR::Instr *cmpInstr)
  3451. {
  3452. IR::Opnd *cmpSrc1 = cmpInstr->GetSrc1();
  3453. IR::Opnd *cmpSrc2 = cmpInstr->GetSrc2();
  3454. IR::Opnd *newSrc1;
  3455. IR::Opnd *newSrc2;
  3456. // Look for something like:
  3457. // t1 = ShrU_A x, 0
  3458. // t2 = 10;
  3459. // BrGt t1, t2, L
  3460. //
  3461. // Peep to:
  3462. //
  3463. // t1 = ShrU_A x, 0
  3464. // t2 = 10;
  3465. // t3 = Or_A x, 0
  3466. // BrUnGt x, t3, L
  3467. // ByteCodeUse t1
  3468. //
  3469. // Hopefully dead-store can get rid of the ShrU
  3470. if (!this->func->DoGlobOpt() || !GlobOpt::DoAggressiveIntTypeSpec(this->func) || !GlobOpt::DoLossyIntTypeSpec(this->func))
  3471. {
  3472. return false;
  3473. }
  3474. if (cmpInstr->IsBranchInstr() && !cmpInstr->AsBranchInstr()->IsConditional())
  3475. {
  3476. return false;
  3477. }
  3478. if (!cmpInstr->GetSrc2())
  3479. {
  3480. return false;
  3481. }
  3482. if (!this->IsUnsignedOpnd(cmpSrc1, &newSrc1))
  3483. {
  3484. return false;
  3485. }
  3486. if (!this->IsUnsignedOpnd(cmpSrc2, &newSrc2))
  3487. {
  3488. return false;
  3489. }
  3490. switch(cmpInstr->m_opcode)
  3491. {
  3492. case Js::OpCode::BrEq_A:
  3493. case Js::OpCode::BrNeq_A:
  3494. case Js::OpCode::BrSrEq_A:
  3495. case Js::OpCode::BrSrNeq_A:
  3496. case Js::OpCode::CmEq_A:
  3497. case Js::OpCode::CmNeq_A:
  3498. case Js::OpCode::CmSrEq_A:
  3499. case Js::OpCode::CmSrNeq_A:
  3500. break;
  3501. case Js::OpCode::BrLe_A:
  3502. cmpInstr->m_opcode = Js::OpCode::BrUnLe_A;
  3503. break;
  3504. case Js::OpCode::BrLt_A:
  3505. cmpInstr->m_opcode = Js::OpCode::BrUnLt_A;
  3506. break;
  3507. case Js::OpCode::BrGe_A:
  3508. cmpInstr->m_opcode = Js::OpCode::BrUnGe_A;
  3509. break;
  3510. case Js::OpCode::BrGt_A:
  3511. cmpInstr->m_opcode = Js::OpCode::BrUnGt_A;
  3512. break;
  3513. case Js::OpCode::CmLe_A:
  3514. cmpInstr->m_opcode = Js::OpCode::CmUnLe_A;
  3515. break;
  3516. case Js::OpCode::CmLt_A:
  3517. cmpInstr->m_opcode = Js::OpCode::CmUnLt_A;
  3518. break;
  3519. case Js::OpCode::CmGe_A:
  3520. cmpInstr->m_opcode = Js::OpCode::CmUnGe_A;
  3521. break;
  3522. case Js::OpCode::CmGt_A:
  3523. cmpInstr->m_opcode = Js::OpCode::CmUnGt_A;
  3524. break;
  3525. default:
  3526. return false;
  3527. }
  3528. IR::ByteCodeUsesInstr * bytecodeInstr = IR::ByteCodeUsesInstr::New(cmpInstr);
  3529. cmpInstr->InsertAfter(bytecodeInstr);
  3530. if (cmpSrc1 != newSrc1)
  3531. {
  3532. if (cmpSrc1->IsRegOpnd() && !cmpSrc1->GetIsJITOptimizedReg())
  3533. {
  3534. bytecodeInstr->Set(cmpSrc1);
  3535. }
  3536. IR::RegOpnd * unsignedSrc = IR::RegOpnd::New(newSrc1->GetType(), cmpInstr->m_func);
  3537. IR::Instr * orZero = IR::Instr::New(Js::OpCode::Or_A, unsignedSrc, newSrc1, IR::IntConstOpnd::New(0, TyMachReg, cmpInstr->m_func), cmpInstr->m_func);
  3538. orZero->SetByteCodeOffset(cmpInstr);
  3539. cmpInstr->InsertBefore(orZero);
  3540. cmpInstr->ReplaceSrc1(unsignedSrc);
  3541. if (newSrc1->IsRegOpnd())
  3542. {
  3543. cmpInstr->GetSrc1()->AsRegOpnd()->SetIsJITOptimizedReg(true);
  3544. orZero->GetSrc1()->SetIsJITOptimizedReg(true);
  3545. }
  3546. }
  3547. if (cmpSrc2 != newSrc2)
  3548. {
  3549. if (cmpSrc2->IsRegOpnd() && !cmpSrc2->GetIsJITOptimizedReg())
  3550. {
  3551. bytecodeInstr->Set(cmpSrc2);
  3552. }
  3553. IR::RegOpnd * unsignedSrc = IR::RegOpnd::New(newSrc2->GetType(), cmpInstr->m_func);
  3554. IR::Instr * orZero = IR::Instr::New(Js::OpCode::Or_A, unsignedSrc, newSrc2, IR::IntConstOpnd::New(0, TyMachReg, cmpInstr->m_func), cmpInstr->m_func);
  3555. orZero->SetByteCodeOffset(cmpInstr);
  3556. cmpInstr->InsertBefore(orZero);
  3557. cmpInstr->ReplaceSrc2(unsignedSrc);
  3558. if (newSrc2->IsRegOpnd())
  3559. {
  3560. cmpInstr->GetSrc2()->AsRegOpnd()->SetIsJITOptimizedReg(true);
  3561. orZero->GetSrc1()->SetIsJITOptimizedReg(true);
  3562. }
  3563. }
  3564. return true;
  3565. }
  3566. #if DBG
  3567. void
  3568. FlowGraph::VerifyLoopGraph()
  3569. {
  3570. FOREACH_BLOCK(block, this)
  3571. {
  3572. Loop *loop = block->loop;
  3573. FOREACH_SUCCESSOR_BLOCK(succ, block)
  3574. {
  3575. if (loop == succ->loop)
  3576. {
  3577. Assert(succ->isLoopHeader == false || loop->GetHeadBlock() == succ);
  3578. continue;
  3579. }
  3580. if (succ->isLoopHeader)
  3581. {
  3582. Assert(succ->loop->parent == loop
  3583. || (!loop->IsDescendentOrSelf(succ->loop)));
  3584. continue;
  3585. }
  3586. Assert(succ->loop == nullptr || succ->loop->IsDescendentOrSelf(loop));
  3587. } NEXT_SUCCESSOR_BLOCK;
  3588. if (!PHASE_OFF(Js::RemoveBreakBlockPhase, this->GetFunc()))
  3589. {
  3590. // Make sure all break blocks have been removed.
  3591. if (loop && !block->isLoopHeader && !(this->func->HasTry() && !this->func->DoOptimizeTry()))
  3592. {
  3593. Assert(loop->IsDescendentOrSelf(block->GetPrev()->loop));
  3594. }
  3595. }
  3596. } NEXT_BLOCK;
  3597. }
  3598. #endif
  3599. #if DBG_DUMP
  3600. void
  3601. FlowGraph::Dump(bool onlyOnVerboseMode, const char16 *form)
  3602. {
  3603. if(PHASE_DUMP(Js::FGBuildPhase, this->GetFunc()))
  3604. {
  3605. if (!onlyOnVerboseMode || Js::Configuration::Global.flags.Verbose)
  3606. {
  3607. if (form)
  3608. {
  3609. Output::Print(form);
  3610. }
  3611. this->Dump();
  3612. }
  3613. }
  3614. }
  3615. void
  3616. FlowGraph::Dump()
  3617. {
  3618. Output::Print(_u("\nFlowGraph\n"));
  3619. FOREACH_BLOCK(block, this)
  3620. {
  3621. Loop * loop = block->loop;
  3622. while (loop)
  3623. {
  3624. Output::Print(_u(" "));
  3625. loop = loop->parent;
  3626. }
  3627. block->DumpHeader(false);
  3628. } NEXT_BLOCK;
  3629. Output::Print(_u("\nLoopGraph\n"));
  3630. for (Loop *loop = this->loopList; loop; loop = loop->next)
  3631. {
  3632. Output::Print(_u("\nLoop\n"));
  3633. FOREACH_BLOCK_IN_LOOP(block, loop)
  3634. {
  3635. block->DumpHeader(false);
  3636. }NEXT_BLOCK_IN_LOOP;
  3637. Output::Print(_u("Loop Ends\n"));
  3638. }
  3639. }
  3640. void
  3641. BasicBlock::DumpHeader(bool insertCR)
  3642. {
  3643. if (insertCR)
  3644. {
  3645. Output::Print(_u("\n"));
  3646. }
  3647. Output::Print(_u("BLOCK %d:"), this->number);
  3648. if (this->isDead)
  3649. {
  3650. Output::Print(_u(" **** DEAD ****"));
  3651. }
  3652. if (this->isBreakBlock)
  3653. {
  3654. Output::Print(_u(" **** Break Block ****"));
  3655. }
  3656. else if (this->isAirLockBlock)
  3657. {
  3658. Output::Print(_u(" **** Air lock Block ****"));
  3659. }
  3660. else if (this->isBreakCompensationBlockAtSource)
  3661. {
  3662. Output::Print(_u(" **** Break Source Compensation Code ****"));
  3663. }
  3664. else if (this->isBreakCompensationBlockAtSink)
  3665. {
  3666. Output::Print(_u(" **** Break Sink Compensation Code ****"));
  3667. }
  3668. else if (this->isAirLockCompensationBlock)
  3669. {
  3670. Output::Print(_u(" **** Airlock block Compensation Code ****"));
  3671. }
  3672. if (!this->predList.Empty())
  3673. {
  3674. BOOL fFirst = TRUE;
  3675. Output::Print(_u(" In("));
  3676. FOREACH_PREDECESSOR_BLOCK(blockPred, this)
  3677. {
  3678. if (!fFirst)
  3679. {
  3680. Output::Print(_u(", "));
  3681. }
  3682. Output::Print(_u("%d"), blockPred->GetBlockNum());
  3683. fFirst = FALSE;
  3684. }
  3685. NEXT_PREDECESSOR_BLOCK;
  3686. Output::Print(_u(")"));
  3687. }
  3688. if (!this->succList.Empty())
  3689. {
  3690. BOOL fFirst = TRUE;
  3691. Output::Print(_u(" Out("));
  3692. FOREACH_SUCCESSOR_BLOCK(blockSucc, this)
  3693. {
  3694. if (!fFirst)
  3695. {
  3696. Output::Print(_u(", "));
  3697. }
  3698. Output::Print(_u("%d"), blockSucc->GetBlockNum());
  3699. fFirst = FALSE;
  3700. }
  3701. NEXT_SUCCESSOR_BLOCK;
  3702. Output::Print(_u(")"));
  3703. }
  3704. if (!this->deadPredList.Empty())
  3705. {
  3706. BOOL fFirst = TRUE;
  3707. Output::Print(_u(" DeadIn("));
  3708. FOREACH_DEAD_PREDECESSOR_BLOCK(blockPred, this)
  3709. {
  3710. if (!fFirst)
  3711. {
  3712. Output::Print(_u(", "));
  3713. }
  3714. Output::Print(_u("%d"), blockPred->GetBlockNum());
  3715. fFirst = FALSE;
  3716. }
  3717. NEXT_DEAD_PREDECESSOR_BLOCK;
  3718. Output::Print(_u(")"));
  3719. }
  3720. if (!this->deadSuccList.Empty())
  3721. {
  3722. BOOL fFirst = TRUE;
  3723. Output::Print(_u(" DeadOut("));
  3724. FOREACH_DEAD_SUCCESSOR_BLOCK(blockSucc, this)
  3725. {
  3726. if (!fFirst)
  3727. {
  3728. Output::Print(_u(", "));
  3729. }
  3730. Output::Print(_u("%d"), blockSucc->GetBlockNum());
  3731. fFirst = FALSE;
  3732. }
  3733. NEXT_DEAD_SUCCESSOR_BLOCK;
  3734. Output::Print(_u(")"));
  3735. }
  3736. if (this->loop)
  3737. {
  3738. Output::Print(_u(" Loop(%d) header: %d"), this->loop->loopNumber - 1, this->loop->GetHeadBlock()->GetBlockNum());
  3739. if (this->loop->parent)
  3740. {
  3741. Output::Print(_u(" parent(%d): %d"), this->loop->parent->loopNumber, this->loop->parent->GetHeadBlock()->GetBlockNum());
  3742. }
  3743. if (this->loop->GetHeadBlock() == this)
  3744. {
  3745. Output::SkipToColumn(50);
  3746. Output::Print(_u("Call Exp/Imp: "));
  3747. if (this->loop->GetHasCall())
  3748. {
  3749. Output::Print(_u("yes/"));
  3750. }
  3751. else
  3752. {
  3753. Output::Print(_u(" no/"));
  3754. }
  3755. Output::Print(Js::DynamicProfileInfo::GetImplicitCallFlagsString(this->loop->GetImplicitCallFlags()));
  3756. }
  3757. }
  3758. Output::Print(_u("\n"));
  3759. if (insertCR)
  3760. {
  3761. Output::Print(_u("\n"));
  3762. }
  3763. }
  3764. void
  3765. BasicBlock::Dump()
  3766. {
  3767. // Dumping the first instruction (label) will dump the block header as well.
  3768. FOREACH_INSTR_IN_BLOCK(instr, this)
  3769. {
  3770. instr->Dump();
  3771. }
  3772. NEXT_INSTR_IN_BLOCK;
  3773. }
  3774. void
  3775. AddPropertyCacheBucket::Dump() const
  3776. {
  3777. Assert(this->initialType != nullptr);
  3778. Assert(this->finalType != nullptr);
  3779. Output::Print(_u(" initial type: 0x%x, final type: 0x%x "), this->initialType->GetAddr(), this->finalType->GetAddr());
  3780. }
  3781. void
  3782. ObjTypeGuardBucket::Dump() const
  3783. {
  3784. Assert(this->guardedPropertyOps != nullptr);
  3785. this->guardedPropertyOps->Dump();
  3786. }
  3787. void
  3788. ObjWriteGuardBucket::Dump() const
  3789. {
  3790. Assert(this->writeGuards != nullptr);
  3791. this->writeGuards->Dump();
  3792. }
  3793. #endif
  3794. void
  3795. BasicBlock::CleanUpValueMaps()
  3796. {
  3797. // Don't do cleanup if it's been done recently.
  3798. // Landing pad could get optimized twice...
  3799. // We want the same info out the first and second time. So always cleanup.
  3800. // Increasing the cleanup threshold count for asmjs to 500
  3801. uint cleanupCount = (!this->globOptData.globOpt->GetIsAsmJSFunc()) ? CONFIG_FLAG(GoptCleanupThreshold) : CONFIG_FLAG(AsmGoptCleanupThreshold);
  3802. if (!this->IsLandingPad() && this->globOptData.globOpt->instrCountSinceLastCleanUp < cleanupCount)
  3803. {
  3804. return;
  3805. }
  3806. this->globOptData.globOpt->instrCountSinceLastCleanUp = 0;
  3807. JitArenaAllocator* tempAlloc = this->globOptData.globOpt->tempAlloc;
  3808. GlobHashTable *thisTable = this->globOptData.symToValueMap;
  3809. BVSparse<JitArenaAllocator> deadSymsBv(tempAlloc);
  3810. BVSparse<JitArenaAllocator> keepAliveSymsBv(tempAlloc);
  3811. BVSparse<JitArenaAllocator> availableValueNumbers(tempAlloc);
  3812. availableValueNumbers.Copy(this->globOptData.globOpt->byteCodeConstantValueNumbersBv);
  3813. BVSparse<JitArenaAllocator> *upwardExposedUses = this->upwardExposedUses;
  3814. BVSparse<JitArenaAllocator> *upwardExposedFields = this->upwardExposedFields;
  3815. bool isInLoop = !!this->loop;
  3816. BVSparse<JitArenaAllocator> symsInCallSequence(tempAlloc);
  3817. SListBase<IR::Opnd *> * callSequence = this->globOptData.callSequence;
  3818. if (callSequence && !callSequence->Empty())
  3819. {
  3820. FOREACH_SLISTBASE_ENTRY(IR::Opnd *, opnd, callSequence)
  3821. {
  3822. StackSym * sym = opnd->GetStackSym();
  3823. symsInCallSequence.Set(sym->m_id);
  3824. }
  3825. }
  3826. NEXT_SLISTBASE_ENTRY;
  3827. for (uint i = 0; i < thisTable->tableSize; i++)
  3828. {
  3829. FOREACH_SLISTBASE_ENTRY_EDITING(GlobHashBucket, bucket, &thisTable->table[i], iter)
  3830. {
  3831. Sym * sym = bucket.value;
  3832. bool isSymUpwardExposed = upwardExposedUses->Test(sym->m_id) || upwardExposedFields->Test(sym->m_id);
  3833. if (!isSymUpwardExposed && symsInCallSequence.Test(sym->m_id))
  3834. {
  3835. // Don't remove/shrink sym-value pair if the sym is referenced in callSequence even if the sym is dead according to backward data flow.
  3836. // This is possible in some edge cases that an infinite loop is involved when evaluating parameter for a function (between StartCall and Call),
  3837. // there is no backward data flow into the infinite loop block, but non empty callSequence still populates to it in this (forward) pass
  3838. // which causes error when looking up value for the syms in callSequence (cannot find the value).
  3839. // It would cause error to fill out the bailout information for the loop blocks.
  3840. // Remove dead syms from callSequence has some risk because there are various associated counters which need to be consistent.
  3841. continue;
  3842. }
  3843. // Make sure symbol was created before backward pass.
  3844. // If symbols isn't upward exposed, mark it as dead.
  3845. // If a symbol was copy-prop'd in a loop prepass, the upwardExposedUses info could be wrong. So wait until we are out of the loop before clearing it.
  3846. bool isSymFieldPRESymStore = isInLoop && this->loop->fieldPRESymStores->Test(sym->m_id);
  3847. if ((SymID)sym->m_id <= this->globOptData.globOpt->maxInitialSymID && !isSymUpwardExposed && !isSymFieldPRESymStore
  3848. && (!isInLoop || !this->globOptData.globOpt->prePassCopyPropSym->Test(sym->m_id)))
  3849. {
  3850. Value *val = bucket.element;
  3851. ValueInfo *valueInfo = val->GetValueInfo();
  3852. Sym *symStore = valueInfo->GetSymStore();
  3853. if (symStore && symStore == sym)
  3854. {
  3855. // Keep constants around, as we don't know if there will be further uses
  3856. if (!bucket.element->GetValueInfo()->IsVarConstant() && !bucket.element->GetValueInfo()->HasIntConstantValue())
  3857. {
  3858. // Symbol may still be a copy-prop candidate. Wait before deleting it.
  3859. deadSymsBv.Set(sym->m_id);
  3860. // Make sure the type sym is added to the dead syms vector as well, because type syms are
  3861. // created in backward pass and so their symIds > maxInitialSymID.
  3862. if (sym->IsStackSym() && sym->AsStackSym()->HasObjectTypeSym())
  3863. {
  3864. deadSymsBv.Set(sym->AsStackSym()->GetObjectTypeSym()->m_id);
  3865. }
  3866. }
  3867. availableValueNumbers.Set(val->GetValueNumber());
  3868. }
  3869. else
  3870. {
  3871. // Make sure the type sym is added to the dead syms vector as well, because type syms are
  3872. // created in backward pass and so their symIds > maxInitialSymID. Perhaps we could remove
  3873. // it explicitly here, but would it work alright with the iterator?
  3874. if (sym->IsStackSym() && sym->AsStackSym()->HasObjectTypeSym())
  3875. {
  3876. deadSymsBv.Set(sym->AsStackSym()->GetObjectTypeSym()->m_id);
  3877. }
  3878. // Not a copy-prop candidate; delete it right away.
  3879. iter.RemoveCurrent(thisTable->alloc);
  3880. this->globOptData.liveInt32Syms->Clear(sym->m_id);
  3881. this->globOptData.liveLossyInt32Syms->Clear(sym->m_id);
  3882. this->globOptData.liveFloat64Syms->Clear(sym->m_id);
  3883. this->globOptData.SetChangedSym(sym);
  3884. }
  3885. }
  3886. else
  3887. {
  3888. if (sym->IsPropertySym() && !this->globOptData.liveFields->Test(sym->m_id))
  3889. {
  3890. // Remove propertySyms which are not live anymore.
  3891. iter.RemoveCurrent(thisTable->alloc);
  3892. this->globOptData.liveInt32Syms->Clear(sym->m_id);
  3893. this->globOptData.liveLossyInt32Syms->Clear(sym->m_id);
  3894. this->globOptData.liveFloat64Syms->Clear(sym->m_id);
  3895. }
  3896. else
  3897. {
  3898. // Look at the copy-prop candidate. We don't want to get rid of the data for a symbol which is
  3899. // a copy-prop candidate.
  3900. Value *val = bucket.element;
  3901. ValueInfo *valueInfo = val->GetValueInfo();
  3902. Sym *symStore = valueInfo->GetSymStore();
  3903. if (symStore && symStore != sym)
  3904. {
  3905. keepAliveSymsBv.Set(symStore->m_id);
  3906. if (symStore->IsStackSym() && symStore->AsStackSym()->HasObjectTypeSym())
  3907. {
  3908. keepAliveSymsBv.Set(symStore->AsStackSym()->GetObjectTypeSym()->m_id);
  3909. }
  3910. }
  3911. availableValueNumbers.Set(val->GetValueNumber());
  3912. }
  3913. }
  3914. } NEXT_SLISTBASE_ENTRY_EDITING;
  3915. }
  3916. deadSymsBv.Minus(&keepAliveSymsBv);
  3917. // Now cleanup exprToValueMap table
  3918. ExprHashTable *thisExprTable = this->globOptData.exprToValueMap;
  3919. bool oldHasCSECandidatesValue = this->globOptData.hasCSECandidates; // Could be false if none need bailout.
  3920. this->globOptData.hasCSECandidates = false;
  3921. for (uint i = 0; i < thisExprTable->tableSize; i++)
  3922. {
  3923. FOREACH_SLISTBASE_ENTRY_EDITING(ExprHashBucket, bucket, &thisExprTable->table[i], iter)
  3924. {
  3925. ExprHash hash = bucket.value;
  3926. ValueNumber src1ValNum = hash.GetSrc1ValueNumber();
  3927. ValueNumber src2ValNum = hash.GetSrc2ValueNumber();
  3928. // If src1Val or src2Val are not available anymore, no point keeping this CSE candidate
  3929. bool removeCurrent = false;
  3930. if ((src1ValNum && !availableValueNumbers.Test(src1ValNum))
  3931. || (src2ValNum && !availableValueNumbers.Test(src2ValNum)))
  3932. {
  3933. removeCurrent = true;
  3934. }
  3935. else
  3936. {
  3937. // If we are keeping this value, make sure we also keep the symStore in the value table
  3938. removeCurrent = true; // Remove by default, unless it's set to false later below.
  3939. Value *val = bucket.element;
  3940. if (val)
  3941. {
  3942. Sym *symStore = val->GetValueInfo()->GetSymStore();
  3943. if (symStore)
  3944. {
  3945. Value *symStoreVal = this->globOptData.FindValue(symStore);
  3946. if (symStoreVal && symStoreVal->GetValueNumber() == val->GetValueNumber())
  3947. {
  3948. removeCurrent = false;
  3949. deadSymsBv.Clear(symStore->m_id);
  3950. if (symStore->IsStackSym() && symStore->AsStackSym()->HasObjectTypeSym())
  3951. {
  3952. deadSymsBv.Clear(symStore->AsStackSym()->GetObjectTypeSym()->m_id);
  3953. }
  3954. }
  3955. }
  3956. }
  3957. }
  3958. if(removeCurrent)
  3959. {
  3960. iter.RemoveCurrent(thisExprTable->alloc);
  3961. }
  3962. else
  3963. {
  3964. this->globOptData.hasCSECandidates = oldHasCSECandidatesValue;
  3965. }
  3966. } NEXT_SLISTBASE_ENTRY_EDITING;
  3967. }
  3968. FOREACH_BITSET_IN_SPARSEBV(dead_id, &deadSymsBv)
  3969. {
  3970. thisTable->Clear(dead_id);
  3971. Sym* sym = this->func->m_symTable->Find(dead_id);
  3972. this->globOptData.SetChangedSym(sym);
  3973. }
  3974. NEXT_BITSET_IN_SPARSEBV;
  3975. if (!deadSymsBv.IsEmpty())
  3976. {
  3977. if (this->func->IsJitInDebugMode())
  3978. {
  3979. // Do not remove non-temp local vars from liveVarSyms (i.e. do not let them become dead).
  3980. // We will need to restore all initialized/used so far non-temp local during bail out.
  3981. // (See BackwardPass::ProcessBailOutInfo)
  3982. Assert(this->func->m_nonTempLocalVars);
  3983. BVSparse<JitArenaAllocator> tempBv(tempAlloc);
  3984. tempBv.Minus(&deadSymsBv, this->func->m_nonTempLocalVars);
  3985. this->globOptData.liveVarSyms->Minus(&tempBv);
  3986. #if DBG
  3987. tempBv.And(this->globOptData.liveInt32Syms, this->func->m_nonTempLocalVars);
  3988. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveInt32Syms?");
  3989. tempBv.And(this->globOptData.liveLossyInt32Syms, this->func->m_nonTempLocalVars);
  3990. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveLossyInt32Syms?");
  3991. tempBv.And(this->globOptData.liveFloat64Syms, this->func->m_nonTempLocalVars);
  3992. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveFloat64Syms?");
  3993. #endif
  3994. }
  3995. else
  3996. {
  3997. this->globOptData.liveVarSyms->Minus(&deadSymsBv);
  3998. }
  3999. this->globOptData.liveInt32Syms->Minus(&deadSymsBv);
  4000. this->globOptData.liveLossyInt32Syms->Minus(&deadSymsBv);
  4001. this->globOptData.liveFloat64Syms->Minus(&deadSymsBv);
  4002. }
  4003. JitAdelete(this->globOptData.globOpt->alloc, upwardExposedUses);
  4004. this->upwardExposedUses = nullptr;
  4005. JitAdelete(this->globOptData.globOpt->alloc, upwardExposedFields);
  4006. this->upwardExposedFields = nullptr;
  4007. if (this->cloneStrCandidates)
  4008. {
  4009. JitAdelete(this->globOptData.globOpt->alloc, this->cloneStrCandidates);
  4010. this->cloneStrCandidates = nullptr;
  4011. }
  4012. }
  4013. static bool IsLegalOpcodeForPathDepBrFold(IR::Instr *instr)
  4014. {
  4015. if (!instr->IsRealInstr())
  4016. {
  4017. return true;
  4018. }
  4019. switch (instr->m_opcode)
  4020. {
  4021. case Js::OpCode::Ld_A:
  4022. case Js::OpCode::Ld_I4:
  4023. case Js::OpCode::LdFld:
  4024. case Js::OpCode::ByteCodeUses:
  4025. case Js::OpCode::InlineeEnd:
  4026. return true;
  4027. }
  4028. #if DBG
  4029. if (PHASE_TRACE(Js::PathDepBranchFoldingPhase, instr->m_func) && Js::Configuration::Global.flags.Verbose)
  4030. {
  4031. Output::Print(_u("Skipping PathDependentBranchFolding due to: "));
  4032. instr->Dump();
  4033. }
  4034. #endif
  4035. return false;
  4036. }
  4037. static bool IsCopyTypeInstr(IR::Instr *instr)
  4038. {
  4039. switch (instr->m_opcode)
  4040. {
  4041. case Js::OpCode::LdC_A_I4:
  4042. case Js::OpCode::Ld_I4:
  4043. case Js::OpCode::Ld_A:
  4044. case Js::OpCode::StFld:
  4045. case Js::OpCode::LdFld:
  4046. case Js::OpCode::InitFld: return true;
  4047. default:
  4048. return false;
  4049. }
  4050. };
  4051. Value * BasicBlock::FindValueInLocalThenGlobalValueTableAndUpdate(GlobOpt *globOpt, GlobHashTable * localSymToValueMap, IR::Instr *instr, Sym *dstSym, Sym *srcSym)
  4052. {
  4053. Value ** localDstValue = nullptr;
  4054. Value * srcVal = nullptr;
  4055. if (dstSym)
  4056. {
  4057. localDstValue = localSymToValueMap->FindOrInsertNew(dstSym);
  4058. }
  4059. Value ** localSrcValue = localSymToValueMap->Get(srcSym);
  4060. if (!localSrcValue)
  4061. {
  4062. Value *globalValue = this->globOptData.FindValue(srcSym);
  4063. if (globOpt->IsLoopPrePass() && globalValue && (!srcSym->IsStackSym() || !globOpt->IsSafeToTransferInPrepass(srcSym->AsStackSym(), globalValue->GetValueInfo())))
  4064. {
  4065. srcVal = nullptr;
  4066. }
  4067. else
  4068. {
  4069. srcVal = globalValue;
  4070. }
  4071. }
  4072. else
  4073. {
  4074. srcVal = *localSrcValue;
  4075. }
  4076. if (dstSym)
  4077. {
  4078. Assert(IsCopyTypeInstr(instr));
  4079. *localDstValue = srcVal;
  4080. }
  4081. return srcVal;
  4082. }
  4083. IR::LabelInstr* BasicBlock::CanProveConditionalBranch(IR::BranchInstr *branch, GlobOpt* globOpt, GlobHashTable * localSymToValueMap)
  4084. {
  4085. if (!branch->GetSrc1() || !branch->GetSrc1()->GetStackSym())
  4086. {
  4087. return nullptr;
  4088. }
  4089. Value *src1Val = nullptr, *src2Val = nullptr;
  4090. Js::Var src1Var = nullptr, src2Var = nullptr;
  4091. src1Val = FindValueInLocalThenGlobalValueTableAndUpdate(globOpt, localSymToValueMap, branch, nullptr, branch->GetSrc1()->GetStackSym());
  4092. if (!src1Val)
  4093. {
  4094. return nullptr;
  4095. }
  4096. src1Var = globOpt->GetConstantVar(branch->GetSrc1(), src1Val);
  4097. if (branch->GetSrc2() != nullptr)
  4098. {
  4099. if (branch->GetSrc2()->GetStackSym())
  4100. {
  4101. src2Val = FindValueInLocalThenGlobalValueTableAndUpdate(globOpt, localSymToValueMap, branch, nullptr, branch->GetSrc2()->GetStackSym());
  4102. }
  4103. if (!src2Val)
  4104. {
  4105. return nullptr;
  4106. }
  4107. src2Var = globOpt->GetConstantVar(branch->GetSrc2(), src2Val);
  4108. }
  4109. bool provenTrue;
  4110. if (!globOpt->CanProveConditionalBranch(branch, src1Val, src2Val, src1Var, src2Var, &provenTrue))
  4111. {
  4112. return nullptr;
  4113. }
  4114. IR::LabelInstr * newTarget = provenTrue ? branch->GetTarget() : branch->GetNextRealInstrOrLabel()->AsLabelInstr();
  4115. return newTarget;
  4116. }
  4117. void
  4118. BasicBlock::CheckLegalityAndFoldPathDepBranches(GlobOpt* globOpt)
  4119. {
  4120. IR::LabelInstr * lastBranchTarget = nullptr;
  4121. // For the block we start processing from, we maintain a valueTable, we go over the instrs in the block
  4122. // If we find a Ld_A, we find if the src1 already has a value in the local valueTable, if not we use the value from the pred's valueTable merge
  4123. // For other instrs, we assign null value
  4124. GlobHashTable * localSymToValueMap = GlobHashTable::New(globOpt->alloc, 8);
  4125. BVSparse<JitArenaAllocator> currentPathDefines(globOpt->alloc);
  4126. IR::Instr *currentInlineeEnd = nullptr, *unskippedInlineeEnd = nullptr;
  4127. auto UpdateValueForCopyTypeInstr = [&](IR::Instr *instr) {
  4128. if (instr->m_opcode == Js::OpCode::LdFld)
  4129. {
  4130. // Special handling for LdFld
  4131. Assert(instr->GetSrc1()->IsSymOpnd());
  4132. IR::SymOpnd *symOpnd = instr->GetSrc1()->AsSymOpnd();
  4133. if (symOpnd->m_sym->IsPropertySym())
  4134. {
  4135. PropertySym * originalPropertySym = symOpnd->m_sym->AsPropertySym();
  4136. Value *const objectValue = FindValueInLocalThenGlobalValueTableAndUpdate(globOpt, localSymToValueMap, instr, nullptr, originalPropertySym->m_stackSym);
  4137. Sym* objSym = objectValue ? objectValue->GetValueInfo()->GetSymStore() : nullptr;
  4138. PropertySym *prop = PropertySym::Find(objSym ? objSym->m_id : originalPropertySym->m_stackSym->m_id, originalPropertySym->m_propertyId, globOpt->func);
  4139. if (prop)
  4140. {
  4141. FindValueInLocalThenGlobalValueTableAndUpdate(globOpt, localSymToValueMap, instr, instr->GetDst()->GetStackSym(), prop);
  4142. }
  4143. else
  4144. {
  4145. Value ** localDstValue = localSymToValueMap->FindOrInsertNew(instr->GetDst()->GetStackSym());
  4146. *localDstValue = nullptr;
  4147. }
  4148. }
  4149. }
  4150. else if (instr->GetSrc1()->GetStackSym())
  4151. {
  4152. StackSym* src1Sym = instr->GetSrc1()->GetStackSym();
  4153. FindValueInLocalThenGlobalValueTableAndUpdate(globOpt, localSymToValueMap, instr, instr->GetDst()->GetSym(), src1Sym);
  4154. }
  4155. else if (!instr->GetSrc1()->IsIntConstOpnd())
  4156. {
  4157. ValueType src1Value = instr->GetSrc1()->GetValueType();
  4158. Value **localValue = localSymToValueMap->FindOrInsertNew(instr->GetDst()->GetSym());
  4159. if (src1Value.IsUndefined() || src1Value.IsBoolean())
  4160. {
  4161. *localValue = globOpt->GetVarConstantValue(instr->GetSrc1()->AsAddrOpnd());
  4162. }
  4163. else
  4164. {
  4165. *localValue = nullptr;
  4166. }
  4167. }
  4168. };
  4169. FOREACH_INSTR_IN_BLOCK(instr, this)
  4170. {
  4171. if (OpCodeAttr::HasDeadFallThrough(instr->m_opcode))
  4172. {
  4173. return;
  4174. }
  4175. if (instr->m_opcode == Js::OpCode::InlineeEnd)
  4176. {
  4177. unskippedInlineeEnd = currentInlineeEnd = instr;
  4178. }
  4179. else if (instr->GetDst())
  4180. {
  4181. if (instr->GetDst()->GetSym())
  4182. {
  4183. if (IsCopyTypeInstr(instr))
  4184. {
  4185. UpdateValueForCopyTypeInstr(instr);
  4186. }
  4187. else if(instr->m_opcode == Js::OpCode::NewScObjectLiteral)
  4188. {
  4189. Value **localValue = localSymToValueMap->FindOrInsertNew(instr->GetDst()->GetSym());
  4190. if (instr->GetDst()->GetValueType() == ValueType::UninitializedObject)
  4191. {
  4192. *localValue = globOpt->NewGenericValue(ValueType::UninitializedObject, instr->GetDst());
  4193. }
  4194. }
  4195. else
  4196. {
  4197. // complex instr, can't track value, insert nullptr
  4198. Value **localValue = localSymToValueMap->FindOrInsertNew(instr->GetDst()->GetSym());
  4199. *localValue = nullptr;
  4200. }
  4201. }
  4202. }
  4203. } NEXT_INSTR_IN_BLOCK;
  4204. IR::Instr * instr = this->GetLastInstr();
  4205. /* We start from the current instruction and go on scanning for legality, as long as it is legal to skip an instruction, skip.
  4206. * When we see an unconditional branch, start scanning from the branchTarget
  4207. * When we see a conditional branch, check if we can prove the branch target, if we can, adjust the flowgraph, and continue in the direction of the proven target
  4208. * We stop, when we no longer can skip instructions, either due to legality check or a non provable conditional branch
  4209. */
  4210. while (instr)
  4211. {
  4212. if (!instr->IsBranchInstr() && !instr->IsLabelInstr() && !IsLegalOpcodeForPathDepBrFold(instr))
  4213. {
  4214. return;
  4215. }
  4216. if (OpCodeAttr::HasDeadFallThrough(instr->m_opcode)) // BailOnNoProfile etc
  4217. {
  4218. return;
  4219. }
  4220. if (instr->m_opcode == Js::OpCode::InlineeEnd)
  4221. {
  4222. if (currentInlineeEnd != nullptr)
  4223. {
  4224. return;
  4225. }
  4226. currentInlineeEnd = instr;
  4227. }
  4228. else if (instr->GetDst())
  4229. {
  4230. if (!instr->GetDst()->IsRegOpnd()) // complex dstOpnd, stop.
  4231. {
  4232. return;
  4233. }
  4234. IR::RegOpnd *dst = instr->GetDst()->AsRegOpnd();
  4235. currentPathDefines.Set(dst->GetStackSym()->m_id);
  4236. if (IsCopyTypeInstr(instr))
  4237. {
  4238. UpdateValueForCopyTypeInstr(instr);
  4239. }
  4240. else
  4241. {
  4242. Value ** localDstValue = localSymToValueMap->FindOrInsertNew(instr->GetDst()->GetStackSym());
  4243. *localDstValue = nullptr;
  4244. }
  4245. }
  4246. if (instr->IsLabelInstr())
  4247. {
  4248. if (instr->AsLabelInstr()->m_isLoopTop)
  4249. {
  4250. // don't cross over to loops
  4251. return;
  4252. }
  4253. }
  4254. if (instr->IsBranchInstr())
  4255. {
  4256. IR::BranchInstr* branch = instr->AsBranchInstr();
  4257. IR::LabelInstr* branchTarget = nullptr;
  4258. if (branch->IsUnconditional())
  4259. {
  4260. branchTarget = branch->GetTarget();
  4261. if (!branchTarget)
  4262. {
  4263. return;
  4264. }
  4265. if (branchTarget->m_isLoopTop)
  4266. {
  4267. return;
  4268. }
  4269. }
  4270. else
  4271. {
  4272. if (branch->GetTarget()->m_isLoopTop)
  4273. {
  4274. return;
  4275. }
  4276. branchTarget = CanProveConditionalBranch(branch, globOpt, localSymToValueMap);
  4277. if (!branchTarget)
  4278. {
  4279. return;
  4280. }
  4281. }
  4282. FOREACH_BITSET_IN_SPARSEBV(id, &currentPathDefines)
  4283. {
  4284. if (branchTarget->GetBasicBlock()->upwardExposedUses->Test(id))
  4285. {
  4286. // it is used in the direction of the branch, we can't skip it
  4287. return;
  4288. }
  4289. } NEXT_BITSET_IN_SPARSEBV;
  4290. if (PHASE_TRACE(Js::PathDepBranchFoldingPhase, this->func))
  4291. {
  4292. if (!branch->IsUnconditional())
  4293. {
  4294. Output::Print(_u("TRACE PathDependentBranchFolding: "));
  4295. Output::Print(_u("Can prove retarget of branch in Block %d from Block %d to Block %d in func %s\n"),
  4296. this->GetBlockNum(),
  4297. this->GetLastInstr()->IsBranchInstr() ? this->GetLastInstr()->AsBranchInstr()->GetTarget()->GetBasicBlock()->GetBlockNum() : this->GetNext()->GetBlockNum(),
  4298. branchTarget->GetBasicBlock()->GetBlockNum(),
  4299. this->func->GetJITFunctionBody()->GetDisplayName());
  4300. if (globOpt->IsLoopPrePass())
  4301. {
  4302. Output::Print(_u("In LoopPrePass\n"));
  4303. }
  4304. Output::Flush();
  4305. }
  4306. }
  4307. if (this->GetLastInstr()->IsBranchInstr() && (this->GetLastInstr()->AsBranchInstr()->GetTarget() == branchTarget))
  4308. {
  4309. // happens on the first block we start from only
  4310. lastBranchTarget = branchTarget;
  4311. instr = lastBranchTarget;
  4312. continue;
  4313. }
  4314. if (branchTarget != this->GetLastInstr()->GetNextRealInstrOrLabel())
  4315. {
  4316. IR::Instr* lastInstr = this->GetLastInstr();
  4317. IR::BranchInstr * newBranch = IR::BranchInstr::New(Js::OpCode::Br, branchTarget, branchTarget->m_func);
  4318. newBranch->SetByteCodeOffset(lastInstr);
  4319. if (lastInstr->IsBranchInstr())
  4320. {
  4321. globOpt->ConvertToByteCodeUses(lastInstr);
  4322. }
  4323. this->GetLastInstr()->InsertAfter(newBranch);
  4324. globOpt->func->m_fg->AddEdge(this, branchTarget->GetBasicBlock());
  4325. this->IncrementDataUseCount();
  4326. }
  4327. else
  4328. {
  4329. // If the new target is a fall through label, delete the branch
  4330. globOpt->ConvertToByteCodeUses(this->GetLastInstr());
  4331. }
  4332. if (currentInlineeEnd != nullptr && currentInlineeEnd != unskippedInlineeEnd)
  4333. {
  4334. this->GetLastInstr()->InsertBefore(currentInlineeEnd->Copy());
  4335. currentInlineeEnd = nullptr;
  4336. }
  4337. // We are adding an unconditional branch, go over all the current successors and remove the ones that are dead now
  4338. FOREACH_SUCCESSOR_BLOCK_EDITING(blockSucc, this, iter)
  4339. {
  4340. if (branchTarget != blockSucc->GetFirstInstr()->AsLabelInstr())
  4341. {
  4342. // Change the old succ edge to dead
  4343. this->RemoveDeadSucc(blockSucc, globOpt->func->m_fg);
  4344. if (this->GetDataUseCount() > 0)
  4345. {
  4346. this->DecrementDataUseCount();
  4347. }
  4348. if (blockSucc->GetPredList()->Count() == 0)
  4349. {
  4350. this->func->m_fg->RemoveBlock(blockSucc, globOpt);
  4351. }
  4352. }
  4353. }NEXT_SUCCESSOR_BLOCK_EDITING;
  4354. lastBranchTarget = branchTarget;
  4355. instr = lastBranchTarget;
  4356. #if DBG
  4357. if (PHASE_TRACE(Js::PathDepBranchFoldingPhase, instr->m_func) && Js::Configuration::Global.flags.Verbose)
  4358. {
  4359. Output::Print(_u("After PathDependentBranchFolding: "));
  4360. this->func->Dump();
  4361. }
  4362. #endif
  4363. }
  4364. else
  4365. {
  4366. instr = instr->m_next;
  4367. }
  4368. }
  4369. return;
  4370. }
  4371. bool
  4372. BasicBlock::PathDepBranchFolding(GlobOpt* globOpt)
  4373. {
  4374. if (PHASE_OFF(Js::PathDepBranchFoldingPhase, this->func))
  4375. {
  4376. return false;
  4377. }
  4378. CheckLegalityAndFoldPathDepBranches(globOpt);
  4379. return true;
  4380. }
  4381. void
  4382. BasicBlock::MergePredBlocksValueMaps(GlobOpt* globOpt)
  4383. {
  4384. Assert(!globOpt->isCallHelper);
  4385. // We keep a local temporary copy for the merge
  4386. GlobOptBlockData blockData(this->globOptData.curFunc);
  4387. if (!globOpt->isRecursiveCallOnLandingPad)
  4388. {
  4389. blockData.NullOutBlockData(globOpt, globOpt->func);
  4390. }
  4391. else
  4392. {
  4393. // If we are going over the landing pad again after field PRE, just start again
  4394. // with the value table where we left off.
  4395. blockData.CopyBlockData(&this->globOptData);
  4396. return;
  4397. }
  4398. BVSparse<JitArenaAllocator> symsRequiringCompensation(globOpt->tempAlloc);
  4399. {
  4400. BVSparse<JitArenaAllocator> symsCreatedForMerge(globOpt->tempAlloc);
  4401. bool forceTypeSpecOnLoopHeader = true;
  4402. FOREACH_PREDECESSOR_BLOCK(pred, this)
  4403. {
  4404. if (pred->globOptData.callSequence && pred->globOptData.callSequence->Empty())
  4405. {
  4406. JitAdelete(globOpt->alloc, pred->globOptData.callSequence);
  4407. pred->globOptData.callSequence = nullptr;
  4408. }
  4409. if (this->isLoopHeader && globOpt->IsLoopPrePass() && globOpt->prePassLoop == this->loop && this->loop->IsDescendentOrSelf(pred->loop))
  4410. {
  4411. // Loop back-edge.
  4412. // First pass on loop runs optimistically, without doing transforms.
  4413. // Skip this edge for now.
  4414. continue;
  4415. }
  4416. PathDependentInfo *const pathDependentInfo = __edge->GetPathDependentInfo();
  4417. PathDependentInfoToRestore pathDependentInfoToRestore;
  4418. if (pathDependentInfo)
  4419. {
  4420. pathDependentInfoToRestore = globOpt->UpdatePathDependentInfo(pathDependentInfo);
  4421. }
  4422. Assert(pred->GetDataUseCount());
  4423. // First pred?
  4424. if (blockData.symToValueMap == nullptr)
  4425. {
  4426. // Only one edge?
  4427. if (pred->GetSuccList()->HasOne() && this->GetPredList()->HasOne() && this->loop == nullptr)
  4428. {
  4429. blockData.ReuseBlockData(&pred->globOptData);
  4430. // Don't need to restore the old value info
  4431. pathDependentInfoToRestore.Clear();
  4432. }
  4433. else
  4434. {
  4435. blockData.CloneBlockData(this, pred);
  4436. }
  4437. }
  4438. else
  4439. {
  4440. const bool isLoopPrePass = globOpt->IsLoopPrePass();
  4441. blockData.MergeBlockData(
  4442. this,
  4443. pred,
  4444. isLoopPrePass ? nullptr : &symsRequiringCompensation,
  4445. isLoopPrePass ? nullptr : &symsCreatedForMerge,
  4446. forceTypeSpecOnLoopHeader);
  4447. forceTypeSpecOnLoopHeader = false; // can force type-spec on the loop header only for the first back edge.
  4448. }
  4449. // Restore the value for the next edge
  4450. if (pathDependentInfo)
  4451. {
  4452. globOpt->RestorePathDependentInfo(pathDependentInfo, pathDependentInfoToRestore);
  4453. __edge->ClearPathDependentInfo(globOpt->alloc);
  4454. }
  4455. } NEXT_PREDECESSOR_BLOCK;
  4456. }
  4457. // Consider: We can recreate values for hoisted field so it can copy prop out of the loop
  4458. if (blockData.symToValueMap == nullptr)
  4459. {
  4460. blockData.InitBlockData(globOpt, globOpt->func);
  4461. }
  4462. if (!globOpt->DoObjTypeSpec())
  4463. {
  4464. // Object type specialization is off, but if copy prop is on (e.g., /force:fieldhoist) we're not clearing liveFields,
  4465. // so we may be letting type syms slip through this block.
  4466. globOpt->KillAllObjectTypes(this->globOptData.liveFields);
  4467. }
  4468. this->globOptData.CopyBlockData(&blockData);
  4469. if (globOpt->IsLoopPrePass())
  4470. {
  4471. Assert(this->loop);
  4472. if(globOpt->DoBoundCheckHoist())
  4473. {
  4474. globOpt->SetInductionVariableValueNumbers(&blockData);
  4475. }
  4476. if (this->isLoopHeader && globOpt->rootLoopPrePass == this->loop)
  4477. {
  4478. // Capture bail out info in case we have optimization that needs it
  4479. Assert(this->loop->bailOutInfo == nullptr);
  4480. this->loop->bailOutInfo = this->CreateLoopTopBailOutInfo(globOpt);
  4481. }
  4482. // If loop pre-pass, don't insert convert from type-spec to var
  4483. return;
  4484. }
  4485. this->CleanUpValueMaps();
  4486. Sym *symIV = nullptr;
  4487. // Clean up the syms requiring compensation by checking the final value in the merged block to see if the sym still requires
  4488. // compensation. All the while, create a mapping from sym to value info in the merged block. This dictionary helps avoid a
  4489. // value lookup in the merged block per predecessor.
  4490. SymToValueInfoMap symsRequiringCompensationToMergedValueInfoMap(globOpt->tempAlloc);
  4491. if(!symsRequiringCompensation.IsEmpty())
  4492. {
  4493. const SymTable *const symTable = func->m_symTable;
  4494. FOREACH_BITSET_IN_SPARSEBV(id, &symsRequiringCompensation)
  4495. {
  4496. Sym *const sym = symTable->Find(id);
  4497. Assert(sym);
  4498. Value *const value = blockData.FindValue(sym);
  4499. if(!value)
  4500. {
  4501. continue;
  4502. }
  4503. ValueInfo *const valueInfo = value->GetValueInfo();
  4504. if(!valueInfo->IsArrayValueInfo())
  4505. {
  4506. continue;
  4507. }
  4508. // At least one new sym was created while merging and associated with the merged value info, so those syms will
  4509. // require compensation in predecessors. For now, the dead store phase is relied upon to remove compensation that is
  4510. // dead due to no further uses of the new sym.
  4511. symsRequiringCompensationToMergedValueInfoMap.Add(sym, valueInfo);
  4512. } NEXT_BITSET_IN_SPARSEBV;
  4513. symsRequiringCompensation.ClearAll();
  4514. }
  4515. if (this->isLoopHeader)
  4516. {
  4517. BVSparse<JitArenaAllocator> * tempBv = globOpt->tempBv;
  4518. // Values on the back-edge in the prepass may be conservative for syms defined in the loop, and type specialization in
  4519. // the prepass is not reflective of the value, but rather, is used to determine whether the sym should be specialized
  4520. // around the loop. Additionally, some syms that are used before defined in the loop may be specialized in the loop
  4521. // header despite not being specialized in the landing pad. Now that the type specialization bit-vectors are merged,
  4522. // specialize the corresponding value infos in the loop header too.
  4523. Assert(tempBv->IsEmpty());
  4524. Loop *const loop = this->loop;
  4525. SymTable *const symTable = func->m_symTable;
  4526. JitArenaAllocator *const alloc = globOpt->alloc;
  4527. // Int-specialized syms
  4528. tempBv->Or(loop->likelyIntSymsUsedBeforeDefined, loop->symsDefInLoop);
  4529. tempBv->And(blockData.liveInt32Syms);
  4530. tempBv->Minus(blockData.liveLossyInt32Syms);
  4531. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  4532. {
  4533. StackSym *const varSym = symTable->FindStackSym(id);
  4534. Assert(varSym);
  4535. Value *const value = blockData.FindValue(varSym);
  4536. Assert(value);
  4537. ValueInfo *const valueInfo = value->GetValueInfo();
  4538. if(!valueInfo->IsInt())
  4539. {
  4540. globOpt->ChangeValueInfo(nullptr, value, valueInfo->SpecializeToInt32(alloc));
  4541. }
  4542. } NEXT_BITSET_IN_SPARSEBV;
  4543. // Float-specialized syms
  4544. tempBv->Or(loop->likelyNumberSymsUsedBeforeDefined, loop->symsDefInLoop);
  4545. tempBv->Or(loop->forceFloat64SymsOnEntry);
  4546. tempBv->And(blockData.liveFloat64Syms);
  4547. GlobOptBlockData &landingPadBlockData = loop->landingPad->globOptData;
  4548. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  4549. {
  4550. StackSym *const varSym = symTable->FindStackSym(id);
  4551. Assert(varSym);
  4552. // If the type-spec sym is null or if the sym is not float-specialized in the loop landing pad, the sym may have
  4553. // been merged to float on a loop back-edge when it was live as float on the back-edge, and live as int in the loop
  4554. // header. In this case, compensation inserted in the loop landing pad will use BailOutNumberOnly, and so it is
  4555. // guaranteed that the value will be float. Otherwise, if the type-spec sym exists, its field can be checked to see
  4556. // if it's prevented from being anything but a number.
  4557. StackSym *const typeSpecSym = varSym->GetFloat64EquivSym(nullptr);
  4558. if(!typeSpecSym ||
  4559. typeSpecSym->m_requiresBailOnNotNumber ||
  4560. !landingPadBlockData.IsFloat64TypeSpecialized(varSym))
  4561. {
  4562. Value *const value = blockData.FindValue(varSym);
  4563. if(value)
  4564. {
  4565. ValueInfo *const valueInfo = value->GetValueInfo();
  4566. if(!valueInfo->IsNumber())
  4567. {
  4568. globOpt->ChangeValueInfo(this, value, valueInfo->SpecializeToFloat64(alloc));
  4569. }
  4570. }
  4571. else
  4572. {
  4573. this->globOptData.SetValue(globOpt->NewGenericValue(ValueType::Float), varSym);
  4574. }
  4575. }
  4576. } NEXT_BITSET_IN_SPARSEBV;
  4577. tempBv->ClearAll();
  4578. }
  4579. // We need to handle the case where a symbol is type-spec'd coming from some predecessors,
  4580. // but not from others.
  4581. //
  4582. // We can do this by inserting the right conversion in the predecessor block, but we
  4583. // can only do this if we are the first successor of that block, since the previous successors
  4584. // would have already been processed. Instead, we'll need to break the edge and insert a block
  4585. // (airlock block) to put in the conversion code.
  4586. Assert(globOpt->tempBv->IsEmpty());
  4587. BVSparse<JitArenaAllocator> symsNeedingLossyIntConversion(globOpt->tempAlloc);
  4588. BVSparse<JitArenaAllocator> symsNeedingLosslessIntConversion(globOpt->tempAlloc);
  4589. BVSparse<JitArenaAllocator> symsNeedingFloatConversion(globOpt->tempAlloc);
  4590. FOREACH_PREDECESSOR_EDGE_EDITING(edge, this, iter)
  4591. {
  4592. BasicBlock *pred = edge->GetPred();
  4593. if (pred->loop && pred->loop->GetHeadBlock() == this)
  4594. {
  4595. pred->DecrementDataUseCount();
  4596. // Skip loop back-edges. We will handle these when we get to the exit blocks.
  4597. continue;
  4598. }
  4599. BasicBlock *orgPred = nullptr;
  4600. if (pred->isAirLockCompensationBlock)
  4601. {
  4602. Assert(pred->GetPredList()->HasOne());
  4603. orgPred = pred;
  4604. pred = (pred->GetPredList()->Head())->GetPred();
  4605. }
  4606. // Lossy int in the merged block, and no int in the predecessor - need a lossy conversion to int
  4607. symsNeedingLossyIntConversion.Minus(blockData.liveLossyInt32Syms, pred->globOptData.liveInt32Syms);
  4608. // Lossless int in the merged block, and no lossless int in the predecessor - need a lossless conversion to int
  4609. symsNeedingLosslessIntConversion.Minus(blockData.liveInt32Syms, blockData.liveLossyInt32Syms);
  4610. globOpt->tempBv->Minus(pred->globOptData.liveInt32Syms, pred->globOptData.liveLossyInt32Syms);
  4611. symsNeedingLosslessIntConversion.Minus(globOpt->tempBv);
  4612. globOpt->tempBv->Minus(blockData.liveVarSyms, pred->globOptData.liveVarSyms);
  4613. symsNeedingFloatConversion.Minus(blockData.liveFloat64Syms, pred->globOptData.liveFloat64Syms);
  4614. bool symIVNeedsSpecializing = (symIV && !pred->globOptData.liveInt32Syms->Test(symIV->m_id) && !symsNeedingLosslessIntConversion.Test(symIV->m_id));
  4615. if (!globOpt->tempBv->IsEmpty() ||
  4616. !symsNeedingLossyIntConversion.IsEmpty() ||
  4617. !symsNeedingLosslessIntConversion.IsEmpty() ||
  4618. !symsNeedingFloatConversion.IsEmpty() ||
  4619. symIVNeedsSpecializing ||
  4620. symsRequiringCompensationToMergedValueInfoMap.Count() != 0)
  4621. {
  4622. // We can't un-specialize a symbol in a predecessor if we've already processed
  4623. // a successor of that block. Instead, insert a new block on the flow edge
  4624. // (an airlock block) and do the un-specialization there.
  4625. //
  4626. // Alternatively, the current block could be an exit block out of this loop, and so the predecessor may exit the
  4627. // loop. In that case, if the predecessor may continue into the loop without exiting, then we need an airlock block
  4628. // to do the appropriate conversions only on the exit path (preferring not to do the conversions inside the loop).
  4629. // If, on the other hand, the predecessor always flows into the current block, then it always exits, so we don't need
  4630. // an airlock block and can just do the conversions in the predecessor.
  4631. if (pred->GetSuccList()->Head()->GetSucc() != this||
  4632. (pred->loop && pred->loop->parent == this->loop && pred->GetSuccList()->Count() > 1))
  4633. {
  4634. BasicBlock *airlockBlock = nullptr;
  4635. if (!orgPred)
  4636. {
  4637. if (PHASE_TRACE(Js::GlobOptPhase, this->func) && !globOpt->IsLoopPrePass())
  4638. {
  4639. Output::Print(_u("TRACE: "));
  4640. Output::Print(_u("Inserting airlock block to convert syms to var between block %d and %d\n"),
  4641. pred->GetBlockNum(), this->GetBlockNum());
  4642. Output::Flush();
  4643. }
  4644. airlockBlock = globOpt->func->m_fg->InsertAirlockBlock(edge);
  4645. }
  4646. else
  4647. {
  4648. Assert(orgPred->isAirLockCompensationBlock);
  4649. airlockBlock = orgPred;
  4650. pred->DecrementDataUseCount();
  4651. airlockBlock->isAirLockCompensationBlock = false; // This is airlock block now. So remove the attribute.
  4652. }
  4653. globOpt->CloneBlockData(airlockBlock, pred);
  4654. pred = airlockBlock;
  4655. }
  4656. if (!globOpt->tempBv->IsEmpty())
  4657. {
  4658. globOpt->ToVar(globOpt->tempBv, pred);
  4659. }
  4660. if (!symsNeedingLossyIntConversion.IsEmpty())
  4661. {
  4662. globOpt->ToInt32(&symsNeedingLossyIntConversion, pred, true /* lossy */);
  4663. }
  4664. if (!symsNeedingLosslessIntConversion.IsEmpty())
  4665. {
  4666. globOpt->ToInt32(&symsNeedingLosslessIntConversion, pred, false /* lossy */);
  4667. }
  4668. if (!symsNeedingFloatConversion.IsEmpty())
  4669. {
  4670. globOpt->ToFloat64(&symsNeedingFloatConversion, pred);
  4671. }
  4672. if (symIVNeedsSpecializing)
  4673. {
  4674. globOpt->tempBv->ClearAll();
  4675. globOpt->tempBv->Set(symIV->m_id);
  4676. globOpt->ToInt32(globOpt->tempBv, pred, false /* lossy */);
  4677. }
  4678. if(symsRequiringCompensationToMergedValueInfoMap.Count() != 0)
  4679. {
  4680. globOpt->InsertValueCompensation(pred, symsRequiringCompensationToMergedValueInfoMap);
  4681. }
  4682. }
  4683. } NEXT_PREDECESSOR_EDGE_EDITING;
  4684. FOREACH_PREDECESSOR_EDGE(edge, this)
  4685. {
  4686. // Peak Memory optimization:
  4687. // These are in an arena, but putting them on the free list greatly reduces
  4688. // the peak memory used by the global optimizer for complex flow graphs.
  4689. BasicBlock *pred = edge->GetPred();
  4690. if (!this->isLoopHeader || this->loop != pred->loop)
  4691. {
  4692. // Skip airlock compensation block as we are not going to walk this block.
  4693. if (pred->isAirLockCompensationBlock)
  4694. {
  4695. pred->DecrementDataUseCount();
  4696. Assert(pred->GetPredList()->HasOne());
  4697. pred = (pred->GetPredList()->Head())->GetPred();
  4698. }
  4699. if (pred->DecrementDataUseCount() == 0 && (!this->loop || this->loop->landingPad != pred))
  4700. {
  4701. if (!(pred->GetSuccList()->HasOne() && this->GetPredList()->HasOne() && this->loop == nullptr))
  4702. {
  4703. pred->globOptData.DeleteBlockData();
  4704. }
  4705. else
  4706. {
  4707. pred->globOptData.NullOutBlockData(globOpt, globOpt->func);
  4708. }
  4709. }
  4710. }
  4711. } NEXT_PREDECESSOR_EDGE;
  4712. globOpt->tempBv->ClearAll();
  4713. Assert(!globOpt->IsLoopPrePass()); // We already early return if we are in prepass
  4714. if (this->isLoopHeader)
  4715. {
  4716. Loop *const loop = this->loop;
  4717. // Save values live on loop entry, such that we can adjust the state of the
  4718. // values on the back-edge to match.
  4719. loop->varSymsOnEntry = JitAnew(globOpt->alloc, BVSparse<JitArenaAllocator>, globOpt->alloc);
  4720. loop->varSymsOnEntry->Copy(this->globOptData.liveVarSyms);
  4721. loop->int32SymsOnEntry = JitAnew(globOpt->alloc, BVSparse<JitArenaAllocator>, globOpt->alloc);
  4722. loop->int32SymsOnEntry->Copy(this->globOptData.liveInt32Syms);
  4723. loop->lossyInt32SymsOnEntry = JitAnew(globOpt->alloc, BVSparse<JitArenaAllocator>, globOpt->alloc);
  4724. loop->lossyInt32SymsOnEntry->Copy(this->globOptData.liveLossyInt32Syms);
  4725. loop->float64SymsOnEntry = JitAnew(globOpt->alloc, BVSparse<JitArenaAllocator>, globOpt->alloc);
  4726. loop->float64SymsOnEntry->Copy(this->globOptData.liveFloat64Syms);
  4727. loop->liveFieldsOnEntry = JitAnew(globOpt->alloc, BVSparse<JitArenaAllocator>, globOpt->alloc);
  4728. loop->liveFieldsOnEntry->Copy(this->globOptData.liveFields);
  4729. if(globOpt->DoBoundCheckHoist() && loop->inductionVariables)
  4730. {
  4731. globOpt->FinalizeInductionVariables(loop, &blockData);
  4732. if(globOpt->DoLoopCountBasedBoundCheckHoist())
  4733. {
  4734. globOpt->DetermineDominatingLoopCountableBlock(loop, this);
  4735. }
  4736. }
  4737. }
  4738. else if (!this->loop)
  4739. {
  4740. this->SetDataUseCount(this->GetSuccList()->Count());
  4741. }
  4742. else if(this == this->loop->dominatingLoopCountableBlock)
  4743. {
  4744. globOpt->DetermineLoopCount(this->loop);
  4745. }
  4746. }
  4747. void GlobOpt::CloneBlockData(BasicBlock *const toBlock, BasicBlock *const fromBlock)
  4748. {
  4749. toBlock->globOptData.CloneBlockData(toBlock, fromBlock);
  4750. }
  4751. void
  4752. GlobOpt::CloneValues(BasicBlock *const toBlock, GlobOptBlockData *toData, GlobOptBlockData *fromData)
  4753. {
  4754. ValueSet *const valuesToKillOnCalls = JitAnew(this->alloc, ValueSet, this->alloc);
  4755. toData->valuesToKillOnCalls = valuesToKillOnCalls;
  4756. // Values are shared between symbols with the same ValueNumber.
  4757. // Use a dictionary to share the clone values.
  4758. ValueSetByValueNumber *const valuesCreatedForClone = this->valuesCreatedForClone;
  4759. Assert(valuesCreatedForClone);
  4760. Assert(valuesCreatedForClone->Count() == 0);
  4761. DebugOnly(ValueSetByValueNumber originalValues(tempAlloc, 64));
  4762. const uint tableSize = toData->symToValueMap->tableSize;
  4763. SListBase<GlobHashBucket> *const table = toData->symToValueMap->table;
  4764. for (uint i = 0; i < tableSize; i++)
  4765. {
  4766. FOREACH_SLISTBASE_ENTRY(GlobHashBucket, bucket, &table[i])
  4767. {
  4768. Value *value = bucket.element;
  4769. ValueNumber valueNum = value->GetValueNumber();
  4770. #if DBG
  4771. // Ensure that the set of values in fromData contains only one value per value number. Byte-code constant values
  4772. // are reused in multiple blocks without cloning, so exclude those value numbers.
  4773. {
  4774. Value *const previouslyClonedOriginalValue = originalValues.Lookup(valueNum);
  4775. if (previouslyClonedOriginalValue)
  4776. {
  4777. if (!byteCodeConstantValueNumbersBv->Test(valueNum))
  4778. {
  4779. Assert(value == previouslyClonedOriginalValue);
  4780. }
  4781. }
  4782. else
  4783. {
  4784. originalValues.Add(value);
  4785. }
  4786. }
  4787. #endif
  4788. Value *newValue = valuesCreatedForClone->Lookup(valueNum);
  4789. if (!newValue)
  4790. {
  4791. newValue = CopyValue(value, valueNum);
  4792. TrackMergedValueForKills(newValue, toData, nullptr);
  4793. valuesCreatedForClone->Add(newValue);
  4794. }
  4795. bucket.element = newValue;
  4796. } NEXT_SLISTBASE_ENTRY;
  4797. }
  4798. valuesCreatedForClone->Clear();
  4799. ProcessValueKills(toBlock, toData);
  4800. }
  4801. PRECandidates * GlobOpt::FindBackEdgePRECandidates(BasicBlock *block, JitArenaAllocator *alloc)
  4802. {
  4803. // Iterate over the value table looking for propertySyms which are candidates to
  4804. // pre-load in the landing pad for field PRE
  4805. GlobHashTable *valueTable = block->globOptData.symToValueMap;
  4806. Loop *loop = block->loop;
  4807. PRECandidates *candidates = JitAnew(this->tempAlloc, PRECandidates);
  4808. for (uint i = 0; i < valueTable->tableSize; i++)
  4809. {
  4810. FOREACH_SLISTBASE_ENTRY(GlobHashBucket, bucket, &valueTable->table[i])
  4811. {
  4812. Sym *sym = bucket.value;
  4813. if (!sym->IsPropertySym())
  4814. {
  4815. continue;
  4816. }
  4817. PropertySym *propertySym = sym->AsPropertySym();
  4818. // Field should be live on the back-edge
  4819. if (!block->globOptData.liveFields->Test(propertySym->m_id))
  4820. {
  4821. continue;
  4822. }
  4823. // Field should be live in the landing pad as well
  4824. if (!loop->landingPad->globOptData.liveFields->Test(propertySym->m_id))
  4825. {
  4826. continue;
  4827. }
  4828. Value *value = bucket.element;
  4829. Sym *symStore = value->GetValueInfo()->GetSymStore();
  4830. if (!symStore || !symStore->IsStackSym())
  4831. {
  4832. continue;
  4833. }
  4834. // Check upwardExposed in case of:
  4835. // s1 = 0;
  4836. // loop:
  4837. // = o.x;
  4838. // foo();
  4839. // o.x = s1;
  4840. // Can't thrash s1 in loop top.
  4841. if (!symStore->AsStackSym()->IsSingleDef() || loop->GetHeadBlock()->upwardExposedUses->Test(symStore->m_id))
  4842. {
  4843. // If symStore isn't singleDef, we need to make sure it still has the same value.
  4844. // This usually fails if we are not aggressive at transferring values in the prepass.
  4845. Value **pSymStoreFromValue = valueTable->Get(symStore->m_id);
  4846. // Consider: We should be fine if symStore isn't live in landing pad...
  4847. if (!pSymStoreFromValue || (*pSymStoreFromValue)->GetValueNumber() != value->GetValueNumber())
  4848. {
  4849. continue;
  4850. }
  4851. }
  4852. BasicBlock *landingPad = loop->landingPad;
  4853. Value *landingPadValue = landingPad->globOptData.FindValue(propertySym);
  4854. if (!landingPadValue)
  4855. {
  4856. // Value should be added as initial value or already be there.
  4857. continue;
  4858. }
  4859. IR::Instr * ldInstr = this->prePassInstrMap->Lookup(propertySym->m_id, nullptr);
  4860. if (!ldInstr)
  4861. {
  4862. continue;
  4863. }
  4864. if (!candidates->candidatesList)
  4865. {
  4866. candidates->candidatesList = JitAnew(alloc, PRECandidatesList, alloc);
  4867. candidates->candidatesToProcess = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  4868. candidates->candidatesBv = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  4869. }
  4870. candidates->candidatesList->Prepend(&bucket);
  4871. candidates->candidatesToProcess->Set(propertySym->m_id);
  4872. candidates->candidatesBv->Set(propertySym->m_id);
  4873. } NEXT_SLISTBASE_ENTRY;
  4874. }
  4875. return candidates;
  4876. }
  4877. void GlobOpt::InsertCloneStrs(BasicBlock *toBlock, GlobOptBlockData *toData, GlobOptBlockData *fromData)
  4878. {
  4879. if (toBlock->isLoopHeader // isLoopBackEdge
  4880. && toBlock->cloneStrCandidates
  4881. && !IsLoopPrePass())
  4882. {
  4883. Loop *loop = toBlock->loop;
  4884. BasicBlock *landingPad = loop->landingPad;
  4885. const SymTable *const symTable = func->m_symTable;
  4886. Assert(tempBv->IsEmpty());
  4887. tempBv->And(toBlock->cloneStrCandidates, fromData->isTempSrc);
  4888. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  4889. {
  4890. StackSym *const sym = (StackSym *)symTable->Find(id);
  4891. Assert(sym);
  4892. if (!landingPad->globOptData.liveVarSyms->Test(id)
  4893. || !fromData->liveVarSyms->Test(id))
  4894. {
  4895. continue;
  4896. }
  4897. Value * landingPadValue = landingPad->globOptData.FindValue(sym);
  4898. if (landingPadValue == nullptr)
  4899. {
  4900. continue;
  4901. }
  4902. Value * loopValue = fromData->FindValue(sym);
  4903. if (loopValue == nullptr)
  4904. {
  4905. continue;
  4906. }
  4907. ValueInfo *landingPadValueInfo = landingPadValue->GetValueInfo();
  4908. ValueInfo *loopValueInfo = loopValue->GetValueInfo();
  4909. if (landingPadValueInfo->IsLikelyString()
  4910. && loopValueInfo->IsLikelyString())
  4911. {
  4912. IR::Instr *cloneStr = IR::Instr::New(Js::OpCode::CloneStr, this->func);
  4913. IR::RegOpnd *opnd = IR::RegOpnd::New(sym, IRType::TyVar, this->func);
  4914. cloneStr->SetDst(opnd);
  4915. cloneStr->SetSrc1(opnd);
  4916. if (loop->bailOutInfo->bailOutInstr)
  4917. {
  4918. loop->bailOutInfo->bailOutInstr->InsertBefore(cloneStr);
  4919. }
  4920. else
  4921. {
  4922. landingPad->InsertAfter(cloneStr);
  4923. }
  4924. toData->isTempSrc->Set(id);
  4925. }
  4926. }
  4927. NEXT_BITSET_IN_SPARSEBV;
  4928. tempBv->ClearAll();
  4929. }
  4930. }