FlowGraph.cpp 188 KB

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