2
0

FlowGraph.cpp 195 KB

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