FunctionBody.h 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869
  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. #pragma once
  6. #include "AuxPtrs.h"
  7. #include "CompactCounters.h"
  8. // Where should I include this file?
  9. #include "FunctionExecutionStateMachine.h"
  10. struct CodeGenWorkItem;
  11. class SourceContextInfo;
  12. struct DeferredFunctionStub;
  13. #ifdef DYNAMIC_PROFILE_MUTATOR
  14. class DynamicProfileMutator;
  15. class DynamicProfileMutatorImpl;
  16. #endif
  17. #define MAX_FUNCTION_BODY_DEBUG_STRING_SIZE 42 //11*3+8+1
  18. typedef BVSparse<ArenaAllocator> ActiveFunctionSet;
  19. #if ENABLE_NATIVE_CODEGEN
  20. class JitTransferData;
  21. class NativeEntryPointData;
  22. class InProcNativeEntryPointData;
  23. #if ENABLE_OOP_NATIVE_CODEGEN
  24. class OOPNativeEntryPointData;
  25. #endif
  26. #endif
  27. namespace Js
  28. {
  29. #pragma region Class Forward Declarations
  30. class ByteCodeBufferReader;
  31. class ByteCodeBufferBuilder;
  32. class ByteCodeCache;
  33. class ScopeInfo;
  34. class SmallSpanSequence;
  35. struct StatementLocation;
  36. class SmallSpanSequenceIter;
  37. struct StatementData;
  38. struct PropertyIdOnRegSlotsContainer;
  39. struct InlineCache;
  40. class PolymorphicInlineCache;
  41. struct IsInstInlineCache;
  42. class ScopeObjectChain;
  43. class EntryPointInfo;
  44. class FunctionProxy;
  45. class ParseableFunctionInfo;
  46. class FunctionBody;
  47. class DebuggerScopeProperty;
  48. class DebuggerScope;
  49. class FunctionEntryPointInfo;
  50. #ifdef ASMJS_PLAT
  51. class AsmJsFunctionInfo;
  52. class AmsJsModuleInfo;
  53. #endif
  54. class ArrayBuffer;
  55. class SharedArrayBuffer;
  56. class FunctionCodeGenRuntimeData;
  57. class JavascriptNumber;
  58. #pragma endregion
  59. // Definition of scopes such as With, Catch and Block which will be used further in the debugger for additional look-ups.
  60. enum DiagExtraScopesType
  61. {
  62. DiagUnknownScope, // Unknown scope set when deserializing bytecode and the scope is not yet known.
  63. DiagWithScope, // With scope.
  64. DiagCatchScopeDirect, // Catch scope in regslot
  65. DiagCatchScopeInSlot, // Catch scope in slot array
  66. DiagCatchScopeInObject, // Catch scope in scope object
  67. DiagBlockScopeDirect, // Block scope in regslot
  68. DiagBlockScopeInSlot, // Block scope in slot array
  69. DiagBlockScopeInObject, // Block scope in activation object
  70. DiagBlockScopeRangeEnd, // Used to end a block scope range.
  71. DiagParamScope, // The scope represents symbols at formals
  72. DiagParamScopeInObject, // The scope represents symbols at formals and formal scope in activation object
  73. };
  74. struct EnumeratorCache
  75. {
  76. Type * type;
  77. void * data;
  78. };
  79. #pragma region Inline Cache Info class declarations
  80. class PolymorphicCacheUtilizationArray
  81. {
  82. private:
  83. Field(byte *) utilArray;
  84. public:
  85. PolymorphicCacheUtilizationArray()
  86. : utilArray(nullptr)
  87. {
  88. }
  89. void EnsureUtilArray(Recycler * const recycler, Js::FunctionBody * functionBody);
  90. byte* GetByteArray() { return utilArray; }
  91. void SetUtil(Js::FunctionBody* functionBody, uint index, byte util);
  92. byte GetUtil(Js::FunctionBody* functionBody, uint index);
  93. };
  94. class PolymorphicInlineCacheInfo sealed
  95. {
  96. private:
  97. Field(InlineCachePointerArray<PolymorphicInlineCache>) polymorphicInlineCaches;
  98. Field(PolymorphicCacheUtilizationArray) polymorphicCacheUtilizationArray;
  99. Field(FunctionBody *) functionBody;
  100. public:
  101. PolymorphicInlineCacheInfo(FunctionBody * functionBody)
  102. : functionBody(functionBody)
  103. {
  104. }
  105. InlineCachePointerArray<PolymorphicInlineCache> * GetPolymorphicInlineCaches() { return &polymorphicInlineCaches; }
  106. PolymorphicCacheUtilizationArray * GetUtilArray() { return &polymorphicCacheUtilizationArray; }
  107. byte * GetUtilByteArray() { return polymorphicCacheUtilizationArray.GetByteArray(); }
  108. FunctionBody * GetFunctionBody() const { return functionBody; }
  109. };
  110. class EntryPointPolymorphicInlineCacheInfo sealed
  111. {
  112. private:
  113. Field(PolymorphicInlineCacheInfo) selfInfo;
  114. typedef SListCounted<PolymorphicInlineCacheInfo*, Recycler> PolymorphicInlineCacheInfoListType;
  115. Field(PolymorphicInlineCacheInfoListType) inlineeInfo;
  116. static void SetPolymorphicInlineCache(PolymorphicInlineCacheInfo * polymorphicInlineCacheInfo, FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, byte polyCacheUtil);
  117. public:
  118. EntryPointPolymorphicInlineCacheInfo(FunctionBody * functionBody);
  119. PolymorphicInlineCacheInfo * GetSelfInfo() { return &selfInfo; }
  120. PolymorphicInlineCacheInfo * EnsureInlineeInfo(Recycler * recycler, FunctionBody * inlineeFunctionBody);
  121. PolymorphicInlineCacheInfo * GetInlineeInfo(FunctionBody * inlineeFunctionBody);
  122. SListCounted<PolymorphicInlineCacheInfo*, Recycler> * GetInlineeInfo() { return &this->inlineeInfo; }
  123. void SetPolymorphicInlineCache(FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, bool isInlinee, byte polyCacheUtil);
  124. template <class Fn>
  125. void MapInlinees(Fn fn)
  126. {
  127. SListCounted<PolymorphicInlineCacheInfo*, Recycler>::Iterator iter(&inlineeInfo);
  128. while (iter.Next())
  129. {
  130. fn(iter.Data());
  131. }
  132. }
  133. };
  134. #pragma endregion
  135. #ifdef FIELD_ACCESS_STATS
  136. struct FieldAccessStats
  137. {
  138. Field(uint) totalInlineCacheCount;
  139. Field(uint) noInfoInlineCacheCount;
  140. Field(uint) monoInlineCacheCount;
  141. Field(uint) emptyMonoInlineCacheCount;
  142. Field(uint) polyInlineCacheCount;
  143. Field(uint) nullPolyInlineCacheCount;
  144. Field(uint) emptyPolyInlineCacheCount;
  145. Field(uint) ignoredPolyInlineCacheCount;
  146. Field(uint) highUtilPolyInlineCacheCount;
  147. Field(uint) lowUtilPolyInlineCacheCount;
  148. Field(uint) equivPolyInlineCacheCount;
  149. Field(uint) nonEquivPolyInlineCacheCount;
  150. Field(uint) disabledPolyInlineCacheCount;
  151. Field(uint) clonedMonoInlineCacheCount;
  152. Field(uint) clonedPolyInlineCacheCount;
  153. FieldAccessStats() :
  154. totalInlineCacheCount(0), noInfoInlineCacheCount(0), monoInlineCacheCount(0), emptyMonoInlineCacheCount(0),
  155. polyInlineCacheCount(0), nullPolyInlineCacheCount(0), emptyPolyInlineCacheCount(0), ignoredPolyInlineCacheCount(0),
  156. highUtilPolyInlineCacheCount(0), lowUtilPolyInlineCacheCount(0),
  157. equivPolyInlineCacheCount(0), nonEquivPolyInlineCacheCount(0), disabledPolyInlineCacheCount(0),
  158. clonedMonoInlineCacheCount(0), clonedPolyInlineCacheCount(0) {}
  159. void Add(FieldAccessStats* other);
  160. };
  161. typedef FieldAccessStats* FieldAccessStatsPtr;
  162. #else
  163. typedef void* FieldAccessStatsPtr;
  164. #endif
  165. #pragma region Entry point class declarations
  166. class ProxyEntryPointInfo: public ExpirableObject
  167. {
  168. public:
  169. // These are public because we don't manage them nor their consistency;
  170. // the user of this class does.
  171. FieldNoBarrier(Js::JavascriptMethod) jsMethod;
  172. ProxyEntryPointInfo(Js::JavascriptMethod jsMethod, ThreadContext* context = nullptr):
  173. ExpirableObject(context),
  174. jsMethod(jsMethod)
  175. {
  176. }
  177. static DWORD GetAddressOffset() { return offsetof(ProxyEntryPointInfo, jsMethod); }
  178. virtual void Expire()
  179. {
  180. AssertMsg(false, "Expire called on object that doesn't support expiration");
  181. }
  182. virtual void EnterExpirableCollectMode()
  183. {
  184. AssertMsg(false, "EnterExpirableCollectMode called on object that doesn't support expiration");
  185. }
  186. virtual bool IsFunctionEntryPointInfo() const { return false; }
  187. };
  188. // Not thread safe.
  189. // Note that instances of this class are read from and written to from the
  190. // main and JIT threads.
  191. class EntryPointInfo : public ProxyEntryPointInfo
  192. {
  193. private:
  194. enum State : BYTE
  195. {
  196. NotScheduled, // code gen has not been scheduled
  197. CodeGenPending, // code gen job has been scheduled
  198. CodeGenQueued, // code gen has been queued and all the code gen data has been gathered.
  199. CodeGenRecorded, // backend completed, but job still pending
  200. CodeGenDone, // code gen job successfully completed
  201. JITCapReached, // workitem created but JIT cap reached
  202. PendingCleanup, // workitem needs to be cleaned up but couldn't for some reason- it'll be cleaned up at the next opportunity
  203. CleanedUp // the entry point has been cleaned up
  204. };
  205. // The following fields are packed into a 32-bit/64-bit, and the tag to avoid fals positive.
  206. Field(const bool) tag : 1;
  207. Field(bool) isLoopBody : 1;
  208. Field(bool) hasJittedStackClosure : 1;
  209. Field(bool) isAsmJsFunction : 1; // true if entrypoint is for asmjs function
  210. Field(bool) nativeEntryPointProcessed : 1;
  211. Field(bool) mIsTemplatizedJitMode : 1; // true only if in TJ mode, used only for debugging
  212. Field(State) state; // Single state member so users can query state w/o a lock
  213. #if ENABLE_NATIVE_CODEGEN
  214. Field(NativeEntryPointData *) nativeEntryPointData;
  215. #endif // ENABLE_NATIVE_CODEGEN
  216. protected:
  217. Field(CodeGenWorkItem *) workItem;
  218. Field(JavascriptLibrary*) library;
  219. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  220. #if ENABLE_DEBUG_STACK_BACK_TRACE
  221. FieldNoBarrier(StackBackTrace*) cleanupStack; // NoCheckHeapAllocator
  222. #endif
  223. public:
  224. enum CleanupReason
  225. {
  226. NotCleanedUp,
  227. CodeGenFailedOOM,
  228. CodeGenFailedStackOverflow,
  229. CodeGenFailedAborted,
  230. CodeGenFailedExceedJITLimit,
  231. CodeGenFailedUnknown,
  232. NativeCodeInstallFailure,
  233. CleanUpForFinalize
  234. };
  235. private:
  236. Field(CleanupReason) cleanupReason;
  237. #endif // ENABLE_ENTRYPOINT_CLEANUP_TRACE
  238. #ifdef FIELD_ACCESS_STATS
  239. private:
  240. Field(FieldAccessStatsPtr) fieldAccessStats;
  241. #endif
  242. #if DEBUG
  243. private:
  244. Field(const unsigned char*) serializedRpcData = nullptr;
  245. Field(size_t) serializedRpcDataSize = 0;
  246. public:
  247. void SetSerializedRpcData(const unsigned char* data, size_t size)
  248. {
  249. if (this->serializedRpcData != nullptr)
  250. {
  251. // We may have multiple codegens happen for same entrypoint
  252. const unsigned char* rpcData = this->serializedRpcData;
  253. HeapDeleteArray(this->serializedRpcDataSize, rpcData);
  254. }
  255. serializedRpcData = data;
  256. serializedRpcDataSize = size;
  257. }
  258. #endif
  259. public:
  260. virtual void Finalize(bool isShutdown) override;
  261. #if ENABLE_NATIVE_CODEGEN
  262. NativeEntryPointData * EnsureNativeEntryPointData();
  263. bool HasNativeEntryPointData() const;
  264. NativeEntryPointData * GetNativeEntryPointData() const;
  265. InProcNativeEntryPointData * GetInProcNativeEntryPointData();
  266. #if ENABLE_OOP_NATIVE_CODEGEN
  267. OOPNativeEntryPointData * GetOOPNativeEntryPointData();
  268. #endif
  269. #endif
  270. protected:
  271. EntryPointInfo(Js::JavascriptMethod method, JavascriptLibrary* library, ThreadContext* context = nullptr, bool isLoopBody = false) :
  272. ProxyEntryPointInfo(method, context), tag(1), nativeEntryPointProcessed(false), mIsTemplatizedJitMode(false),
  273. #if ENABLE_NATIVE_CODEGEN
  274. nativeEntryPointData(nullptr), workItem(nullptr), state(NotScheduled),
  275. isLoopBody(isLoopBody), hasJittedStackClosure(false),
  276. #endif
  277. library(library), isAsmJsFunction(false)
  278. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  279. #if ENABLE_DEBUG_STACK_BACK_TRACE
  280. , cleanupStack(nullptr)
  281. #endif
  282. , cleanupReason(NotCleanedUp)
  283. #endif
  284. #ifdef FIELD_ACCESS_STATS
  285. , fieldAccessStats(nullptr)
  286. #endif
  287. {}
  288. virtual void ReleasePendingWorkItem() {};
  289. virtual void OnCleanup(bool isShutdown) = 0;
  290. #ifdef PERF_COUNTERS
  291. virtual void OnRecorded() = 0;
  292. #endif
  293. private:
  294. State GetState() const
  295. {
  296. Assert(this->state >= NotScheduled && this->state <= CleanedUp);
  297. return this->state;
  298. }
  299. public:
  300. ScriptContext* GetScriptContext();
  301. virtual FunctionBody *GetFunctionBody() const = 0;
  302. #if ENABLE_NATIVE_CODEGEN
  303. uint GetFrameHeight();
  304. JitTransferData* GetJitTransferData();
  305. #ifdef FIELD_ACCESS_STATS
  306. FieldAccessStats* GetFieldAccessStats() { return this->fieldAccessStats; }
  307. FieldAccessStats* EnsureFieldAccessStats(Recycler* recycler);
  308. #endif
  309. void PinTypeRefs(ScriptContext* scriptContext);
  310. void InstallGuards(ScriptContext* scriptContext);
  311. #endif
  312. void Cleanup(bool isShutdown, bool captureCleanupStack);
  313. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  314. #if ENABLE_DEBUG_STACK_BACK_TRACE
  315. void CaptureCleanupStackTrace();
  316. #endif
  317. #endif
  318. bool IsNotScheduled() const
  319. {
  320. return this->GetState() == NotScheduled;
  321. }
  322. bool IsCodeGenPending() const
  323. {
  324. return this->GetState() == CodeGenPending;
  325. }
  326. bool IsCodeGenRecorded() const
  327. {
  328. return this->GetState() == CodeGenRecorded;
  329. }
  330. bool IsNativeCode() const
  331. {
  332. #if ENABLE_NATIVE_CODEGEN
  333. return this->GetState() == CodeGenRecorded ||
  334. this->GetState() == CodeGenDone;
  335. #else
  336. return false;
  337. #endif
  338. }
  339. bool IsCodeGenDone() const
  340. {
  341. #if ENABLE_NATIVE_CODEGEN
  342. return this->GetState() == CodeGenDone;
  343. #else
  344. return false;
  345. #endif
  346. }
  347. bool IsCodeGenQueued() const
  348. {
  349. #if ENABLE_NATIVE_CODEGEN
  350. return this->GetState() == CodeGenQueued;
  351. #else
  352. return false;
  353. #endif
  354. }
  355. bool IsJITCapReached() const
  356. {
  357. #if ENABLE_NATIVE_CODEGEN
  358. return this->GetState() == JITCapReached;
  359. #else
  360. return false;
  361. #endif
  362. }
  363. bool IsCleanedUp() const
  364. {
  365. return this->GetState() == CleanedUp;
  366. }
  367. bool IsPendingCleanup() const
  368. {
  369. return this->GetState() == PendingCleanup;
  370. }
  371. void SetPendingCleanup()
  372. {
  373. this->state = PendingCleanup;
  374. }
  375. #if ENABLE_ENTRYPOINT_CLEANUP_TRACE
  376. void SetCleanupReason(CleanupReason reason)
  377. {
  378. this->cleanupReason = reason;
  379. }
  380. #endif
  381. bool IsLoopBody() const
  382. {
  383. return this->isLoopBody;
  384. }
  385. #if ENABLE_NATIVE_CODEGEN
  386. bool HasJittedStackClosure() const
  387. {
  388. return this->hasJittedStackClosure;
  389. }
  390. void SetHasJittedStackClosure()
  391. {
  392. this->hasJittedStackClosure = true;
  393. }
  394. #endif
  395. void Reset(bool resetStateToNotScheduled);
  396. #if ENABLE_NATIVE_CODEGEN
  397. void SetCodeGenPending(CodeGenWorkItem * workItem)
  398. {
  399. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  400. Assert(workItem != nullptr);
  401. this->workItem = workItem;
  402. this->state = CodeGenPending;
  403. }
  404. void SetCodeGenPending()
  405. {
  406. Assert(this->GetState() == CodeGenQueued);
  407. this->state = CodeGenPending;
  408. }
  409. void SetCodeGenQueued()
  410. {
  411. Assert(this->GetState() == CodeGenPending);
  412. this->state = CodeGenQueued;
  413. }
  414. void RevertToNotScheduled()
  415. {
  416. Assert(this->GetState() == CodeGenPending);
  417. Assert(this->workItem != nullptr);
  418. this->workItem = nullptr;
  419. this->state = NotScheduled;
  420. }
  421. void SetCodeGenPendingWithStackAllocatedWorkItem()
  422. {
  423. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  424. this->workItem = nullptr;
  425. this->state = CodeGenPending;
  426. }
  427. void SetCodeGenRecorded(Js::JavascriptMethod thunkAddress, Js::JavascriptMethod nativeAddress, ptrdiff_t codeSize, void * validationCookie);
  428. void SetCodeGenDone();
  429. void SetJITCapReached()
  430. {
  431. Assert(this->GetState() == CodeGenQueued);
  432. this->state = JITCapReached;
  433. this->workItem = nullptr;
  434. }
  435. SmallSpanSequence* GetNativeThrowSpanSequence() const;
  436. void SetNativeThrowSpanSequence(SmallSpanSequence* seq);
  437. bool IsInNativeAddressRange(DWORD_PTR codeAddress) {
  438. return (IsNativeCode() &&
  439. codeAddress >= GetNativeAddress() &&
  440. codeAddress < GetNativeAddress() + GetCodeSize());
  441. }
  442. DWORD_PTR GetNativeAddress() const;
  443. Js::JavascriptMethod GetThunkAddress() const;
  444. Js::JavascriptMethod GetNativeEntrypoint() const;
  445. ptrdiff_t GetCodeSize() const;
  446. #endif
  447. CodeGenWorkItem * GetWorkItem() const
  448. {
  449. State state = this->GetState();
  450. Assert(state != NotScheduled || this->workItem == nullptr);
  451. Assert(state == CleanedUp && this->workItem == nullptr ||
  452. state != CleanedUp);
  453. if (state == PendingCleanup)
  454. {
  455. return nullptr;
  456. }
  457. return this->workItem;
  458. }
  459. #ifdef ASMJS_PLAT
  460. // set code size, used by TJ to set the code size
  461. void SetTJCodeSize(ptrdiff_t size);
  462. void SetTJNativeAddress(Js::JavascriptMethod address, void * validationCookie);
  463. void SetIsAsmJSFunction(bool value)
  464. {
  465. this->isAsmJsFunction = value;
  466. }
  467. void SetTJCodeGenDone()
  468. {
  469. Assert(isAsmJsFunction);
  470. this->state = CodeGenDone;
  471. this->workItem = nullptr;
  472. }
  473. void SetIsTJMode(bool value);
  474. bool GetIsTJMode() const;
  475. #endif
  476. bool GetIsAsmJSFunction()const
  477. {
  478. return this->isAsmJsFunction;
  479. }
  480. #if ENABLE_NATIVE_CODEGEN
  481. bool IsNativeEntryPointProcessed() { return this->nativeEntryPointProcessed; }
  482. void SetNativeEntryPointProcessed() { this->nativeEntryPointProcessed = true; }
  483. void EnsureIsReadyToCall();
  484. void ProcessJitTransferData();
  485. void ResetOnLazyBailoutFailure();
  486. void OnNativeCodeInstallFailure();
  487. virtual void ResetOnNativeCodeInstallFailure() = 0;
  488. void FreeJitTransferData();
  489. bool ClearEquivalentTypeCaches();
  490. virtual void Invalidate(bool prolongEntryPoint) { Assert(false); }
  491. InlineeFrameRecord* FindInlineeFrame(void* returnAddress);
  492. bool HasInlinees();
  493. void DoLazyBailout(BYTE** addressOfReturnAddress, Js::FunctionBody* functionBody, const PropertyRecord* propertyRecord);
  494. void CleanupNativeCode(ScriptContext * scriptContext);
  495. #if DBG_DUMP
  496. public:
  497. #elif defined(VTUNE_PROFILING)
  498. private:
  499. #endif
  500. #if DBG_DUMP || defined(VTUNE_PROFILING)
  501. public:
  502. void RecordNativeMap(uint32 offset, uint32 statementIndex);
  503. int GetNativeOffsetMapCount() const;
  504. #endif
  505. #if DBG_DUMP && ENABLE_NATIVE_CODEGEN
  506. void DumpNativeOffsetMaps();
  507. void DumpNativeThrowSpanSequence();
  508. #endif
  509. #ifdef VTUNE_PROFILING
  510. public:
  511. uint PopulateLineInfo(void* pLineInfo, FunctionBody* body);
  512. #endif
  513. #endif // ENABLE_NATIVE_CODEGEN
  514. };
  515. class FunctionEntryPointInfo : public EntryPointInfo
  516. {
  517. public:
  518. Field(FunctionProxy *) functionProxy;
  519. Field(FunctionEntryPointInfo*) nextEntryPoint;
  520. // The offset on the native stack, from which the locals are located (Populated at RegAlloc phase). Used for debug purpose.
  521. Field(int32) localVarSlotsOffset;
  522. // The offset which stores that any of the locals are changed from the debugger.
  523. Field(int32) localVarChangedOffset;
  524. Field(uint) entryPointIndex;
  525. Field(uint32) callsCount;
  526. Field(uint32) lastCallsCount;
  527. private:
  528. Field(ExecutionMode) jitMode;
  529. public:
  530. FunctionEntryPointInfo(FunctionProxy * functionInfo, Js::JavascriptMethod method, ThreadContext* context);
  531. virtual bool IsFunctionEntryPointInfo() const override { return true; }
  532. bool ExecutedSinceCallCountCollection() const;
  533. void CollectCallCounts();
  534. virtual FunctionBody *GetFunctionBody() const override;
  535. #if ENABLE_NATIVE_CODEGEN
  536. ExecutionMode GetJitMode() const;
  537. void SetJitMode(const ExecutionMode jitMode);
  538. virtual void Invalidate(bool prolongEntryPoint) override;
  539. virtual void Expire() override;
  540. virtual void EnterExpirableCollectMode() override;
  541. virtual void ResetOnNativeCodeInstallFailure() override;
  542. static const uint8 GetDecrCallCountPerBailout()
  543. {
  544. return (uint8)CONFIG_FLAG(CallsToBailoutsRatioForRejit) + 1;
  545. }
  546. #endif
  547. virtual void OnCleanup(bool isShutdown) override;
  548. virtual void ReleasePendingWorkItem() override;
  549. #ifdef PERF_COUNTERS
  550. virtual void OnRecorded() override;
  551. #endif
  552. };
  553. class LoopEntryPointInfo : public EntryPointInfo
  554. {
  555. public:
  556. Field(LoopHeader*) loopHeader;
  557. Field(uint) jittedLoopIterationsSinceLastBailout; // number of times the loop iterated in the jitted code before bailing out
  558. Field(uint) totalJittedLoopIterations; // total number of times the loop has iterated in the jitted code for this entry point for a particular invocation of the loop
  559. LoopEntryPointInfo(LoopHeader* loopHeader, Js::JavascriptLibrary* library) :
  560. EntryPointInfo(nullptr, library, /*threadContext*/ nullptr, /*isLoopBody*/ true),
  561. loopHeader(loopHeader),
  562. jittedLoopIterationsSinceLastBailout(0),
  563. totalJittedLoopIterations(0)
  564. #ifdef BGJIT_STATS
  565. ,used(false)
  566. #endif
  567. { }
  568. virtual FunctionBody *GetFunctionBody() const override;
  569. virtual void OnCleanup(bool isShutdown) override;
  570. #if ENABLE_NATIVE_CODEGEN
  571. virtual void ResetOnNativeCodeInstallFailure() override;
  572. static const uint8 GetDecrLoopCountPerBailout()
  573. {
  574. return (uint8)CONFIG_FLAG(LoopIterationsToBailoutsRatioForRejit) + 1;
  575. }
  576. #endif
  577. #ifdef PERF_COUNTERS
  578. virtual void OnRecorded() override;
  579. #endif
  580. #ifdef BGJIT_STATS
  581. bool IsUsed() const
  582. {
  583. return this->used;
  584. }
  585. void MarkAsUsed()
  586. {
  587. this->used = true;
  588. }
  589. private:
  590. Field(bool) used;
  591. #endif
  592. };
  593. typedef RecyclerWeakReference<FunctionEntryPointInfo> FunctionEntryPointWeakRef;
  594. typedef SynchronizableList<FunctionEntryPointWeakRef*, JsUtil::List<FunctionEntryPointWeakRef*>> FunctionEntryPointList;
  595. typedef SynchronizableList<LoopEntryPointInfo*, JsUtil::List<LoopEntryPointInfo*>> LoopEntryPointList;
  596. #pragma endregion
  597. struct LoopHeader
  598. {
  599. private:
  600. Field(LoopEntryPointList*) entryPoints;
  601. public:
  602. Field(uint) startOffset;
  603. Field(uint) endOffset;
  604. Field(uint) interpretCount;
  605. Field(uint) profiledLoopCounter;
  606. #if ENABLE_NATIVE_CODEGEN
  607. Field(uint) rejitCount;
  608. #endif
  609. Field(bool) isNested;
  610. Field(bool) isInTry;
  611. Field(bool) isInTryFinally;
  612. Field(FunctionBody *) functionBody;
  613. #if DBG_DUMP
  614. Field(uint) nativeCount;
  615. #endif
  616. static const uint NoLoop = (uint)-1;
  617. static const uint GetOffsetOfProfiledLoopCounter() { return offsetof(LoopHeader, profiledLoopCounter); }
  618. static const uint GetOffsetOfInterpretCount() { return offsetof(LoopHeader, interpretCount); }
  619. bool Contains(Js::LoopHeader * loopHeader) const
  620. {
  621. return (this->startOffset <= loopHeader->startOffset && loopHeader->endOffset <= this->endOffset);
  622. }
  623. bool Contains(uint offset) const
  624. {
  625. return this->startOffset <= offset && offset < this->endOffset;
  626. }
  627. Js::JavascriptMethod GetCurrentEntryPoint() const
  628. {
  629. LoopEntryPointInfo * entryPoint = GetCurrentEntryPointInfo();
  630. if (entryPoint != nullptr)
  631. {
  632. return this->entryPoints->Item(this->GetCurrentEntryPointIndex())->jsMethod;
  633. }
  634. return nullptr;
  635. }
  636. LoopEntryPointInfo * GetCurrentEntryPointInfo() const
  637. {
  638. Assert(this->entryPoints->Count() > 0);
  639. return this->entryPoints->Item(this->GetCurrentEntryPointIndex());
  640. }
  641. uint GetByteCodeCount()
  642. {
  643. return (endOffset - startOffset);
  644. }
  645. int GetCurrentEntryPointIndex() const
  646. {
  647. return this->entryPoints->Count() - 1;
  648. }
  649. LoopEntryPointInfo * GetEntryPointInfo(int index) const
  650. {
  651. return this->entryPoints->Item(index);
  652. }
  653. template <class Fn>
  654. void MapEntryPoints(Fn fn) const
  655. {
  656. if (this->entryPoints) // ETW rundown may call this before entryPoints initialization
  657. {
  658. this->entryPoints->Map([&](int index, LoopEntryPointInfo * entryPoint)
  659. {
  660. if (entryPoint != nullptr)
  661. {
  662. fn(index, entryPoint);
  663. }
  664. });
  665. }
  666. }
  667. template <class Fn>
  668. bool MapEntryPointsUntil(Fn fn) const
  669. {
  670. if (this->entryPoints) // ETW rundown may call this before entryPoints initialization
  671. {
  672. return this->entryPoints->MapUntil([&](int index, LoopEntryPointInfo * entryPoint)
  673. {
  674. if (entryPoint != nullptr)
  675. {
  676. return fn(index, entryPoint);
  677. }
  678. return false;
  679. });
  680. }
  681. return false;
  682. }
  683. template <class DebugSite, class Fn>
  684. HRESULT MapEntryPoints(DebugSite site, Fn fn) const // external debugging version
  685. {
  686. return Map(site, PointerValue(this->entryPoints), [&](int index, LoopEntryPointInfo * entryPoint)
  687. {
  688. if (entryPoint != nullptr)
  689. {
  690. fn(index, entryPoint);
  691. }
  692. });
  693. }
  694. void Init(FunctionBody * functionBody);
  695. #if ENABLE_NATIVE_CODEGEN
  696. int CreateEntryPoint();
  697. void ReleaseEntryPoints();
  698. void IncRejitCount() { ++rejitCount; }
  699. uint GetRejitCount() { return rejitCount; }
  700. #endif
  701. void ResetInterpreterCount()
  702. {
  703. this->interpretCount = 0;
  704. }
  705. void ResetProfiledLoopCounter()
  706. {
  707. this->profiledLoopCounter = 0;
  708. }
  709. };
  710. // ----------------------------------------------------------------------------
  711. // SWB-TODO: Below explicitly uses write barrier. Move top code to new header file.
  712. //
  713. class FunctionProxy;
  714. typedef Field(FunctionInfo*)* FunctionInfoArray;
  715. typedef Field(FunctionInfo*)* FunctionInfoPtrPtr;
  716. //
  717. // FunctionProxy represents a user defined function
  718. // This could be either from a source file or the byte code cache
  719. // The function need not have been compiled yet- it could be parsed or compiled
  720. // at a later time
  721. //
  722. class FunctionProxy : public FinalizableObject
  723. {
  724. public:
  725. typedef RecyclerWeakReference<ScriptFunctionType> FunctionTypeWeakRef;
  726. typedef JsUtil::List<FunctionTypeWeakRef*, Recycler, false, WeakRefFreeListedRemovePolicy> FunctionTypeWeakRefList;
  727. protected:
  728. FunctionProxy(ScriptContext* scriptContext, Utf8SourceInfo* utf8SourceInfo, uint functionNumber);
  729. DEFINE_VTABLE_CTOR_NOBASE(FunctionProxy);
  730. enum class AuxPointerType : uint8 {
  731. DeferredStubs = 0,
  732. CachedSourceString = 1,
  733. AsmJsFunctionInfo = 2,
  734. AsmJsModuleInfo = 3,
  735. StatementMaps = 4,
  736. StackNestedFuncParent = 5,
  737. SimpleJitEntryPointInfo = 6,
  738. FunctionObjectTypeList = 7, // Script function types not including the deferred prototype type
  739. CodeGenGetSetRuntimeData = 8,
  740. PropertyIdOnRegSlotsContainer = 9, // This is used for showing locals for the current frame.
  741. LoopHeaderArray = 10,
  742. CodeGenRuntimeData = 11,
  743. PolymorphicInlineCachesHead = 12, // DList of all polymorphic inline caches that aren't finalized yet
  744. PropertyIdsForScopeSlotArray = 13, // For SourceInfo
  745. #if ENABLE_PROFILE_INFO
  746. PolymorphicCallSiteInfoHead = 14,
  747. #endif
  748. AuxBlock = 15, // Optional auxiliary information
  749. AuxContextBlock = 16, // Optional auxiliary context specific information
  750. ReferencedPropertyIdMap = 17,
  751. LiteralRegexes = 18,
  752. ObjLiteralTypes = 19,
  753. ScopeInfo = 20,
  754. FormalsPropIdArray = 21,
  755. ForInCacheArray = 22,
  756. SlotIdInCachedScopeToNestedIndexArray = 23,
  757. CodeGenCallbackRuntimeData = 24,
  758. #if ENABLE_PROFILE_INFO
  759. CallbackArgOutInfoList = 25,
  760. #endif
  761. Max,
  762. Invalid = 0xff
  763. };
  764. template<AuxPointerType T>
  765. struct AuxPointerTypeTable {
  766. typedef void* type;
  767. };
  768. template<>
  769. struct AuxPointerTypeTable<AuxPointerType::Max> {};
  770. template<>
  771. struct AuxPointerTypeTable<AuxPointerType::Invalid> {};
  772. #define AuxPointerTypeEntry(apt, T) template<> struct AuxPointerTypeTable<apt> { typedef T type; }
  773. AuxPointerTypeEntry(AuxPointerType::DeferredStubs, DeferredFunctionStub*);
  774. AuxPointerTypeEntry(AuxPointerType::CachedSourceString, RecyclerWeakReference<JavascriptString>*);
  775. AuxPointerTypeEntry(AuxPointerType::AsmJsFunctionInfo, AsmJsFunctionInfo*);
  776. AuxPointerTypeEntry(AuxPointerType::AsmJsModuleInfo, AsmJsModuleInfo*);
  777. //AuxPointerTypeEntry(AuxPointerType::StatementMaps, StatementMapList*); // the type for this isn't declared yet
  778. AuxPointerTypeEntry(AuxPointerType::StackNestedFuncParent, RecyclerWeakReference<FunctionInfo>*);
  779. AuxPointerTypeEntry(AuxPointerType::SimpleJitEntryPointInfo, FunctionEntryPointInfo*);
  780. AuxPointerTypeEntry(AuxPointerType::FunctionObjectTypeList, FunctionTypeWeakRefList*);
  781. AuxPointerTypeEntry(AuxPointerType::CodeGenGetSetRuntimeData, Field(Js::FunctionCodeGenRuntimeData*)*);
  782. AuxPointerTypeEntry(AuxPointerType::PropertyIdOnRegSlotsContainer, Js::PropertyIdOnRegSlotsContainer*);
  783. AuxPointerTypeEntry(AuxPointerType::LoopHeaderArray, Js::LoopHeader*);
  784. AuxPointerTypeEntry(AuxPointerType::CodeGenRuntimeData, Field(FunctionCodeGenRuntimeData*)*);
  785. AuxPointerTypeEntry(AuxPointerType::PolymorphicInlineCachesHead, FunctionBodyPolymorphicInlineCache*);
  786. AuxPointerTypeEntry(AuxPointerType::PropertyIdsForScopeSlotArray, Js::PropertyId*);
  787. #if ENABLE_PROFILE_INFO
  788. AuxPointerTypeEntry(AuxPointerType::PolymorphicCallSiteInfoHead , PolymorphicCallSiteInfo*);
  789. #endif
  790. AuxPointerTypeEntry(AuxPointerType::AuxBlock, ByteBlock*);
  791. AuxPointerTypeEntry(AuxPointerType::AuxContextBlock, ByteBlock*);
  792. AuxPointerTypeEntry(AuxPointerType::ReferencedPropertyIdMap, PropertyId*);
  793. AuxPointerTypeEntry(AuxPointerType::LiteralRegexes, Field(UnifiedRegex::RegexPattern*)*);
  794. AuxPointerTypeEntry(AuxPointerType::ObjLiteralTypes, Field(DynamicType*)*);
  795. AuxPointerTypeEntry(AuxPointerType::ScopeInfo, ScopeInfo*);
  796. AuxPointerTypeEntry(AuxPointerType::FormalsPropIdArray, PropertyIdArray*);
  797. AuxPointerTypeEntry(AuxPointerType::ForInCacheArray, EnumeratorCache*);
  798. AuxPointerTypeEntry(AuxPointerType::SlotIdInCachedScopeToNestedIndexArray, Js::AuxArray<uint32>*);
  799. AuxPointerTypeEntry(AuxPointerType::CodeGenCallbackRuntimeData, Field(FunctionCodeGenRuntimeData*)*);
  800. #if ENABLE_PROFILE_INFO
  801. AuxPointerTypeEntry(AuxPointerType::CallbackArgOutInfoList, CallbackInfoList*);
  802. #endif
  803. #undef AuxPointerTypeEntry
  804. typedef AuxPtrs<FunctionProxy, AuxPointerType> AuxPtrsT;
  805. friend AuxPtrsT;
  806. FieldWithBarrier(AuxPtrsT*) auxPtrs;
  807. template<AuxPointerType T, typename MappedType = typename AuxPointerTypeTable<T>::type>
  808. inline MappedType GetAuxPtr() const
  809. {
  810. return static_cast<MappedType>(GetAuxPtr(T));
  811. }
  812. template<AuxPointerType T, typename MappedType = typename AuxPointerTypeTable<T>::type>
  813. inline MappedType GetAuxPtrWithLock() const
  814. {
  815. return static_cast<MappedType>(GetAuxPtrWithLock(T));
  816. }
  817. template<AuxPointerType T, typename MappedType = typename AuxPointerTypeTable<T>::type>
  818. void SetAuxPtr(MappedType ptr)
  819. {
  820. SetAuxPtr(T, ptr);
  821. }
  822. void* GetAuxPtr(AuxPointerType e) const;
  823. void* GetAuxPtrWithLock(AuxPointerType e) const;
  824. void SetAuxPtr(AuxPointerType e, void* ptr);
  825. FieldWithBarrier(FunctionInfo *) functionInfo;
  826. public:
  827. enum SetDisplayNameFlags
  828. {
  829. SetDisplayNameFlagsNone = 0,
  830. SetDisplayNameFlagsDontCopy = 1,
  831. SetDisplayNameFlagsRecyclerAllocated = 2
  832. };
  833. virtual void Dispose(bool isShutdown) override
  834. {
  835. }
  836. virtual void Mark(Recycler *recycler) override { AssertMsg(false, "Mark called on object that isn't TrackableObject"); }
  837. static const uint GetOffsetOfFunctionInfo() { return offsetof(FunctionProxy, functionInfo); }
  838. FunctionInfo * GetFunctionInfo() const
  839. {
  840. return this->functionInfo;
  841. }
  842. void SetFunctionInfo(FunctionInfo * functionInfo)
  843. {
  844. this->functionInfo = functionInfo;
  845. }
  846. LocalFunctionId GetLocalFunctionId() const;
  847. void SetLocalFunctionId(LocalFunctionId functionId);
  848. ParseableFunctionInfo* GetParseableFunctionInfo() const;
  849. void SetParseableFunctionInfo(ParseableFunctionInfo* func);
  850. DeferDeserializeFunctionInfo* GetDeferDeserializeFunctionInfo() const;
  851. FunctionBody * GetFunctionBody() const;
  852. void VerifyOriginalEntryPoint() const;
  853. JavascriptMethod GetOriginalEntryPoint() const;
  854. JavascriptMethod GetOriginalEntryPoint_Unchecked() const;
  855. void SetOriginalEntryPoint(const JavascriptMethod originalEntryPoint);
  856. bool IsAsync() const;
  857. bool IsDeferred() const;
  858. bool IsLambda() const;
  859. bool IsConstructor() const;
  860. bool IsGenerator() const;
  861. bool IsClassConstructor() const;
  862. bool IsBaseClassConstructor() const;
  863. bool IsClassMethod() const;
  864. bool IsModule() const;
  865. bool IsWasmFunction() const;
  866. bool HasSuperReference() const;
  867. bool IsCoroutine() const;
  868. bool GetCapturesThis() const;
  869. void SetCapturesThis();
  870. bool GetEnclosedByGlobalFunc() const;
  871. void SetEnclosedByGlobalFunc();
  872. bool CanBeDeferred() const;
  873. BOOL IsDeferredDeserializeFunction() const;
  874. BOOL IsDeferredParseFunction() const;
  875. FunctionInfo::Attributes GetAttributes() const;
  876. void SetAttributes(FunctionInfo::Attributes attributes);
  877. Recycler* GetRecycler() const;
  878. uint32 GetSourceContextId() const;
  879. char16* GetDebugNumberSet(wchar(&bufferToWriteTo)[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]) const;
  880. bool GetIsTopLevel() { return m_isTopLevel; }
  881. void SetIsTopLevel(bool set) { m_isTopLevel = set; }
  882. bool GetIsAnonymousFunction() const { return this->GetDisplayName() == Js::Constants::AnonymousFunction; }
  883. void Copy(FunctionProxy* other);
  884. ParseableFunctionInfo* EnsureDeserialized();
  885. ScriptContext* GetScriptContext() const;
  886. Utf8SourceInfo* GetUtf8SourceInfo() const { return this->m_utf8SourceInfo; }
  887. void SetUtf8SourceInfo(Utf8SourceInfo* utf8SourceInfo) { m_utf8SourceInfo = utf8SourceInfo; }
  888. bool IsInDebugMode() const { return this->m_utf8SourceInfo->IsInDebugMode(); }
  889. DWORD_PTR GetSecondaryHostSourceContext() const;
  890. DWORD_PTR GetHostSourceContext() const;
  891. SourceContextInfo * GetSourceContextInfo() const;
  892. SRCINFO const * GetHostSrcInfo() const;
  893. uint GetFunctionNumber() const { return m_functionNumber; }
  894. virtual void Finalize(bool isShutdown) override;
  895. void UpdateFunctionBodyImpl(FunctionBody* body);
  896. bool IsFunctionBody() const;
  897. uint GetCompileCount() const;
  898. void SetCompileCount(uint count);
  899. ProxyEntryPointInfo* GetDefaultEntryPointInfo() const;
  900. ScriptFunctionType * GetDeferredPrototypeType() const;
  901. ScriptFunctionType * EnsureDeferredPrototypeType();
  902. ScriptFunctionType * GetUndeferredFunctionType() const;
  903. void SetUndeferredFunctionType(ScriptFunctionType * type);
  904. JavascriptMethod GetDirectEntryPoint(ProxyEntryPointInfo* entryPoint) const;
  905. // Function object type list methods
  906. FunctionTypeWeakRefList* EnsureFunctionObjectTypeList();
  907. FunctionTypeWeakRefList* GetFunctionObjectTypeList() const;
  908. void SetFunctionObjectTypeList(FunctionTypeWeakRefList* list);
  909. void RegisterFunctionObjectType(ScriptFunctionType* functionType);
  910. template <typename Fn>
  911. void MapFunctionObjectTypes(Fn func)
  912. {
  913. FunctionTypeWeakRefList* functionObjectTypeList = this->GetFunctionObjectTypeList();
  914. if (functionObjectTypeList != nullptr)
  915. {
  916. functionObjectTypeList->Map([&](int, FunctionTypeWeakRef* typeWeakRef)
  917. {
  918. if (typeWeakRef)
  919. {
  920. ScriptFunctionType* type = typeWeakRef->Get();
  921. if (type)
  922. {
  923. func(type);
  924. }
  925. }
  926. });
  927. }
  928. if (this->deferredPrototypeType)
  929. {
  930. func(this->deferredPrototypeType);
  931. }
  932. if (this->undeferredFunctionType)
  933. {
  934. func(this->undeferredFunctionType);
  935. }
  936. }
  937. static uint GetOffsetOfDeferredPrototypeType() { return static_cast<uint>(offsetof(Js::FunctionProxy, deferredPrototypeType)); }
  938. static Js::ScriptFunctionType * EnsureFunctionProxyDeferredPrototypeType(FunctionProxy * proxy)
  939. {
  940. return proxy->EnsureDeferredPrototypeType();
  941. }
  942. void SetIsPublicLibraryCode() { m_isPublicLibraryCode = true; }
  943. bool IsPublicLibraryCode() const { return m_isPublicLibraryCode; }
  944. void SetIsJsBuiltInCode() { m_isJsBuiltInCode = true; }
  945. bool IsJsBuiltInCode() const { return m_isJsBuiltInCode; }
  946. #if DBG
  947. bool HasValidEntryPoint() const;
  948. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  949. bool HasValidProfileEntryPoint() const;
  950. #endif
  951. bool HasValidNonProfileEntryPoint() const;
  952. #endif
  953. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) = 0;
  954. virtual const char16* GetDisplayName() const = 0;
  955. virtual uint GetDisplayNameLength() const = 0;
  956. virtual uint GetShortDisplayNameOffset() const = 0;
  957. static const char16* WrapWithBrackets(const char16* name, charcount_t sz, ScriptContext* scriptContext);
  958. // Used only in the library function stringify (toString, DiagGetValueString).
  959. // If we need more often to give the short name, we should create a member variable which points to the short name
  960. // this is also now being used for function.name.
  961. const char16* GetShortDisplayName(charcount_t * shortNameLength);
  962. bool GetDisplayNameIsRecyclerAllocated() const { return m_displayNameIsRecyclerAllocated; }
  963. bool IsJitLoopBodyPhaseEnabled() const
  964. {
  965. // Consider: Allow JitLoopBody in generator functions for loops that do not yield.
  966. return !PHASE_OFF(JITLoopBodyPhase, this) && !PHASE_OFF(FullJitPhase, this) && !this->IsCoroutine();
  967. }
  968. bool IsJitLoopBodyPhaseForced() const
  969. {
  970. return
  971. IsJitLoopBodyPhaseEnabled() &&
  972. (
  973. PHASE_FORCE(JITLoopBodyPhase, this)
  974. #ifdef ENABLE_PREJIT
  975. || Configuration::Global.flags.Prejit
  976. #endif
  977. );
  978. }
  979. ULONG GetHostStartLine() const;
  980. ULONG GetHostStartColumn() const;
  981. protected:
  982. // Static method(s)
  983. static bool SetDisplayName(const char16* srcName, FieldWithBarrier(const char16*)* destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  984. static bool SetDisplayName(const char16* srcName, const char16** destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  985. static bool IsConstantFunctionName(const char16* srcName);
  986. protected:
  987. FieldNoBarrier(ScriptContext*) m_scriptContext; // Memory context for this function body
  988. FieldWithBarrier(Utf8SourceInfo*) m_utf8SourceInfo;
  989. FieldWithBarrier(ScriptFunctionType*) deferredPrototypeType;
  990. FieldWithBarrier(ScriptFunctionType*) undeferredFunctionType;
  991. FieldWithBarrier(ProxyEntryPointInfo*) m_defaultEntryPointInfo; // The default entry point info for the function proxy
  992. FieldWithBarrier(uint) m_functionNumber; // Per thread global function number
  993. FieldWithBarrier(bool) m_tag11 : 1;
  994. FieldWithBarrier(bool) m_isTopLevel : 1; // Indicates that this function is top-level function, currently being used in script profiler and debugger
  995. FieldWithBarrier(bool) m_isPublicLibraryCode: 1; // Indicates this function is public boundary library code that should be visible in JS stack
  996. FieldWithBarrier(bool) m_isJsBuiltInCode: 1; // Indicates this function comes from the JS Built In implementation
  997. FieldWithBarrier(bool) m_canBeDeferred : 1;
  998. FieldWithBarrier(bool) m_displayNameIsRecyclerAllocated : 1;
  999. void CleanupFunctionProxyCounters()
  1000. {
  1001. PERF_COUNTER_DEC(Code, TotalFunction);
  1002. }
  1003. ULONG ComputeAbsoluteLineNumber(ULONG relativeLineNumber) const;
  1004. ULONG ComputeAbsoluteColumnNumber(ULONG relativeLineNumber, ULONG relativeColumnNumber) const;
  1005. ULONG GetLineNumberInHostBuffer(ULONG relativeLineNumber) const;
  1006. private:
  1007. ScriptFunctionType * AllocDeferredPrototypeType();
  1008. };
  1009. inline Js::LocalFunctionId FunctionProxy::GetLocalFunctionId() const
  1010. {
  1011. Assert(GetFunctionInfo());
  1012. return GetFunctionInfo()->GetLocalFunctionId();
  1013. }
  1014. inline void FunctionProxy::SetLocalFunctionId(LocalFunctionId functionId)
  1015. {
  1016. Assert(GetFunctionInfo());
  1017. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1018. return GetFunctionInfo()->SetLocalFunctionId(functionId);
  1019. }
  1020. inline void FunctionProxy::VerifyOriginalEntryPoint() const
  1021. {
  1022. Assert(GetFunctionInfo());
  1023. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1024. return GetFunctionInfo()->VerifyOriginalEntryPoint();
  1025. }
  1026. inline JavascriptMethod FunctionProxy::GetOriginalEntryPoint() const
  1027. {
  1028. Assert(GetFunctionInfo());
  1029. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1030. return GetFunctionInfo()->GetOriginalEntryPoint();
  1031. }
  1032. inline JavascriptMethod FunctionProxy::GetOriginalEntryPoint_Unchecked() const
  1033. {
  1034. Assert(GetFunctionInfo());
  1035. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1036. return GetFunctionInfo()->GetOriginalEntryPoint_Unchecked();
  1037. }
  1038. inline void FunctionProxy::SetOriginalEntryPoint(const JavascriptMethod originalEntryPoint)
  1039. {
  1040. Assert(GetFunctionInfo());
  1041. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1042. GetFunctionInfo()->SetOriginalEntryPoint(originalEntryPoint);
  1043. }
  1044. inline bool FunctionProxy::IsAsync() const
  1045. {
  1046. Assert(GetFunctionInfo());
  1047. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1048. return GetFunctionInfo()->IsAsync();
  1049. }
  1050. inline bool FunctionProxy::IsDeferred() const
  1051. {
  1052. Assert(GetFunctionInfo());
  1053. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1054. return GetFunctionInfo()->IsDeferred();
  1055. }
  1056. inline bool FunctionProxy::IsConstructor() const
  1057. {
  1058. Assert(GetFunctionInfo());
  1059. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1060. return GetFunctionInfo()->IsConstructor();
  1061. }
  1062. inline bool FunctionProxy::IsGenerator() const
  1063. {
  1064. Assert(GetFunctionInfo());
  1065. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1066. return GetFunctionInfo()->IsGenerator();
  1067. }
  1068. inline bool FunctionProxy::HasSuperReference() const
  1069. {
  1070. Assert(GetFunctionInfo());
  1071. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1072. return GetFunctionInfo()->HasSuperReference();
  1073. }
  1074. inline bool FunctionProxy::IsCoroutine() const
  1075. {
  1076. Assert(GetFunctionInfo());
  1077. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1078. return GetFunctionInfo()->IsCoroutine();
  1079. }
  1080. inline bool FunctionProxy::GetCapturesThis() const
  1081. {
  1082. Assert(GetFunctionInfo());
  1083. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1084. return GetFunctionInfo()->GetCapturesThis();
  1085. }
  1086. inline void FunctionProxy::SetCapturesThis()
  1087. {
  1088. Assert(GetFunctionInfo());
  1089. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1090. GetFunctionInfo()->SetCapturesThis();
  1091. }
  1092. inline bool FunctionProxy::GetEnclosedByGlobalFunc() const
  1093. {
  1094. Assert(GetFunctionInfo());
  1095. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1096. return GetFunctionInfo()->GetEnclosedByGlobalFunc();
  1097. }
  1098. inline void FunctionProxy::SetEnclosedByGlobalFunc()
  1099. {
  1100. Assert(GetFunctionInfo());
  1101. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1102. GetFunctionInfo()->SetEnclosedByGlobalFunc();
  1103. }
  1104. inline BOOL FunctionProxy::IsDeferredDeserializeFunction() const
  1105. {
  1106. Assert(GetFunctionInfo());
  1107. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1108. return GetFunctionInfo()->IsDeferredDeserializeFunction();
  1109. }
  1110. inline BOOL FunctionProxy::IsDeferredParseFunction() const
  1111. {
  1112. Assert(GetFunctionInfo());
  1113. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1114. return GetFunctionInfo()->IsDeferredParseFunction();
  1115. }
  1116. inline FunctionInfo::Attributes FunctionProxy::GetAttributes() const
  1117. {
  1118. Assert(GetFunctionInfo());
  1119. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1120. return GetFunctionInfo()->GetAttributes();
  1121. }
  1122. inline void FunctionProxy::SetAttributes(FunctionInfo::Attributes attributes)
  1123. {
  1124. Assert(GetFunctionInfo());
  1125. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1126. GetFunctionInfo()->SetAttributes(attributes);
  1127. }
  1128. inline void FunctionProxy::SetParseableFunctionInfo(ParseableFunctionInfo* func)
  1129. {
  1130. Assert(GetFunctionInfo());
  1131. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1132. GetFunctionInfo()->SetParseableFunctionInfo(func);
  1133. }
  1134. inline bool FunctionProxy::IsLambda() const
  1135. {
  1136. Assert(GetFunctionInfo());
  1137. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1138. return GetFunctionInfo()->IsLambda();
  1139. }
  1140. inline bool FunctionProxy::CanBeDeferred() const
  1141. {
  1142. Assert(GetFunctionInfo());
  1143. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1144. return GetFunctionInfo()->CanBeDeferred();
  1145. }
  1146. inline bool FunctionProxy::IsClassConstructor() const
  1147. {
  1148. Assert(GetFunctionInfo());
  1149. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1150. return GetFunctionInfo()->IsClassConstructor();
  1151. }
  1152. inline bool FunctionProxy::IsBaseClassConstructor() const
  1153. {
  1154. Assert(GetFunctionInfo());
  1155. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1156. return GetFunctionInfo()->GetBaseConstructorKind();
  1157. }
  1158. inline bool FunctionProxy::IsClassMethod() const
  1159. {
  1160. Assert(GetFunctionInfo());
  1161. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1162. return GetFunctionInfo()->IsClassMethod();
  1163. }
  1164. inline bool FunctionProxy::IsModule() const
  1165. {
  1166. Assert(GetFunctionInfo());
  1167. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1168. return GetFunctionInfo()->IsModule();
  1169. }
  1170. inline uint FunctionProxy::GetCompileCount() const
  1171. {
  1172. Assert(GetFunctionInfo());
  1173. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1174. return GetFunctionInfo()->GetCompileCount();
  1175. }
  1176. inline void FunctionProxy::SetCompileCount(uint count)
  1177. {
  1178. Assert(GetFunctionInfo());
  1179. Assert(GetFunctionInfo()->GetFunctionProxy() == this);
  1180. GetFunctionInfo()->SetCompileCount(count);
  1181. }
  1182. inline ParseableFunctionInfo* FunctionProxy::GetParseableFunctionInfo() const
  1183. {
  1184. Assert(!IsDeferredDeserializeFunction());
  1185. return (ParseableFunctionInfo*)this;
  1186. }
  1187. inline DeferDeserializeFunctionInfo* FunctionProxy::GetDeferDeserializeFunctionInfo() const
  1188. {
  1189. Assert(IsDeferredDeserializeFunction());
  1190. return (DeferDeserializeFunctionInfo*)this;
  1191. }
  1192. inline FunctionBody * FunctionProxy::GetFunctionBody() const
  1193. {
  1194. AssertOrFailFast(IsFunctionBody());
  1195. return (FunctionBody*)this;
  1196. }
  1197. // Represents a function from the byte code cache which will
  1198. // be deserialized upon use
  1199. class DeferDeserializeFunctionInfo: public FunctionProxy
  1200. {
  1201. friend struct ByteCodeSerializer;
  1202. private:
  1203. DeferDeserializeFunctionInfo(int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes);
  1204. public:
  1205. static DeferDeserializeFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* utf8SourceInfo, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, FunctionInfo::Attributes attributes);
  1206. virtual void Finalize(bool isShutdown) override;
  1207. FunctionBody* Deserialize();
  1208. virtual const char16* GetDisplayName() const override;
  1209. void SetDisplayName(const char16* displayName);
  1210. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1211. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1212. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1213. LPCWSTR GetSourceInfo(int& lineNumber, int& columnNumber) const;
  1214. private:
  1215. Field(const byte*) m_functionBytes;
  1216. Field(ByteCodeCache*) m_cache;
  1217. Field(const char16 *) m_displayName; // Optional name
  1218. Field(uint) m_displayNameLength;
  1219. Field(uint) m_displayShortNameOffset;
  1220. Field(NativeModule *) m_nativeModule;
  1221. };
  1222. class ParseableFunctionInfo: public FunctionProxy
  1223. {
  1224. friend class ByteCodeBufferReader;
  1225. friend class ByteCodeBufferBuilder;
  1226. public:
  1227. enum FunctionBodyFlags : byte
  1228. {
  1229. Flags_None = 0x00,
  1230. Flags_StackNestedFunc = 0x01,
  1231. Flags_HasOrParentHasArguments = 0x02,
  1232. Flags_HasTry = 0x04,
  1233. Flags_HasThis = 0x08,
  1234. Flags_NonUserCode = 0x10,
  1235. Flags_HasOnlyThisStatements = 0x20,
  1236. Flags_HasNoExplicitReturnValue = 0x40, // Returns undefined, i.e. has no return statements or return with no expression
  1237. Flags_HasRestParameter = 0x80
  1238. };
  1239. protected:
  1240. ParseableFunctionInfo(JavascriptMethod method, int nestedFunctionCount, LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const char16* displayName, uint m_displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, FunctionBodyFlags flags);
  1241. ParseableFunctionInfo(ParseableFunctionInfo * proxy);
  1242. public:
  1243. struct NestedArray
  1244. {
  1245. NestedArray(uint32 count): nestedCount(count) {}
  1246. Field(uint32) nestedCount;
  1247. Field(FunctionInfo*) functionInfoArray[];
  1248. };
  1249. template<typename Fn>
  1250. void ForEachNestedFunc(Fn fn)
  1251. {
  1252. NestedArray* nestedArray = GetNestedArray();
  1253. if (nestedArray != nullptr)
  1254. {
  1255. for (uint i = 0; i < nestedArray->nestedCount; i++)
  1256. {
  1257. if (!fn(nestedArray->functionInfoArray[i]->GetFunctionProxy(), i))
  1258. {
  1259. break;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. NestedArray* GetNestedArray() const { return nestedArray; }
  1265. uint GetNestedCount() const { return nestedArray == nullptr ? 0 : nestedArray->nestedCount; }
  1266. public:
  1267. static ParseableFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, Utf8SourceInfo* utf8SourceInfo, const char16* displayName, uint m_displayNameLength, uint displayShortNameOffset, FunctionInfo::Attributes attributes, FunctionBodyFlags flags);
  1268. static ParseableFunctionInfo* NewDeferredFunctionFromFunctionBody(FunctionBody *functionBody);
  1269. DEFINE_VTABLE_CTOR_NO_REGISTER(ParseableFunctionInfo, FunctionProxy);
  1270. FunctionBody* Parse(ScriptFunction ** functionRef = nullptr, bool isByteCodeDeserialization = false);
  1271. #ifdef ASMJS_PLAT
  1272. FunctionBody* ParseAsmJs(Parser * p, __out CompileScriptException * se, __out ParseNodeProg ** ptree);
  1273. #endif
  1274. FunctionBodyFlags GetFlags() const { return flags; }
  1275. static bool GetHasThis(FunctionBodyFlags flags) { return (flags & Flags_HasThis) != 0; }
  1276. bool GetHasThis() const { return GetHasThis(flags); }
  1277. void SetHasThis(bool has) { SetFlags(has, Flags_HasThis); }
  1278. static bool GetHasTry(FunctionBodyFlags flags) { return (flags & Flags_HasTry) != 0; }
  1279. bool GetHasTry() const { return GetHasTry(flags); }
  1280. void SetHasTry(bool has) { SetFlags(has, Flags_HasTry); }
  1281. static bool GetHasOrParentHasArguments(FunctionBodyFlags flags) { return (flags & Flags_HasOrParentHasArguments) != 0; }
  1282. bool GetHasOrParentHasArguments() const { return GetHasOrParentHasArguments(flags); }
  1283. void SetHasOrParentHasArguments(bool has) { SetFlags(has, Flags_HasOrParentHasArguments); }
  1284. static bool DoStackNestedFunc(FunctionBodyFlags flags) { return (flags & Flags_StackNestedFunc) != 0; }
  1285. bool DoStackNestedFunc() const { return DoStackNestedFunc(flags); }
  1286. void SetStackNestedFunc(bool does) { SetFlags(does, Flags_StackNestedFunc); }
  1287. bool IsNonUserCode() const { return (flags & Flags_NonUserCode) != 0; }
  1288. void SetIsNonUserCode(bool set);
  1289. bool GetHasNoExplicitReturnValue() { return (flags & Flags_HasNoExplicitReturnValue) != 0; }
  1290. void SetHasNoExplicitReturnValue(bool has) { SetFlags(has, Flags_HasNoExplicitReturnValue); }
  1291. bool GetHasOnlyThisStmts() const { return (flags & Flags_HasOnlyThisStatements) != 0; }
  1292. void SetHasOnlyThisStmts(bool has) { SetFlags(has, Flags_HasOnlyThisStatements); }
  1293. static bool GetHasRestParameter(FunctionBodyFlags flags) { return (flags & Flags_HasRestParameter) != 0; }
  1294. bool GetHasRestParameter() const { return GetHasRestParameter(flags); }
  1295. void SetHasRestParameter() { SetFlags(true, Flags_HasRestParameter); }
  1296. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1297. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1298. bool GetIsDeclaration() const { return m_isDeclaration; }
  1299. void SetIsDeclaration(const bool is) { m_isDeclaration = is; }
  1300. bool GetIsAccessor() const { return m_isAccessor; }
  1301. void SetIsAccessor(const bool is) { m_isAccessor = is; }
  1302. bool GetIsGlobalFunc() const { return m_isGlobalFunc; }
  1303. void SetIsStaticNameFunction(const bool is) { m_isStaticNameFunction = is; }
  1304. bool GetIsStaticNameFunction() const { return m_isStaticNameFunction; }
  1305. void SetIsNamedFunctionExpression(const bool is) { m_isNamedFunctionExpression = is; }
  1306. bool GetIsNamedFunctionExpression() const { return m_isNamedFunctionExpression; }
  1307. void SetIsNameIdentifierRef (const bool is) { m_isNameIdentifierRef = is; }
  1308. bool GetIsNameIdentifierRef () const { return m_isNameIdentifierRef ; }
  1309. // Fake global ->
  1310. // 1) new Function code's global code
  1311. // 2) global code generated from the reparsing deferred parse function
  1312. bool IsFakeGlobalFunc(uint32 flags) const;
  1313. void SetIsGlobalFunc(bool is) { m_isGlobalFunc = is; }
  1314. bool GetIsStrictMode() const { return m_isStrictMode; }
  1315. void SetIsStrictMode() { m_isStrictMode = true; }
  1316. bool GetIsAsmjsMode() const { return m_isAsmjsMode; }
  1317. void SetIsAsmjsMode(bool value)
  1318. {
  1319. m_isAsmjsMode = value;
  1320. #if DBG
  1321. if (value)
  1322. {
  1323. m_wasEverAsmjsMode = true;
  1324. }
  1325. #endif
  1326. }
  1327. #if DBG
  1328. bool WasEverAsmJsMode() const { return m_wasEverAsmjsMode; }
  1329. #endif
  1330. void SetIsWasmFunction(bool val)
  1331. {
  1332. m_isWasmFunction = val;
  1333. }
  1334. bool IsWasmFunction() const
  1335. {
  1336. return m_isWasmFunction;
  1337. }
  1338. bool GetHasImplicitArgIns() { return m_hasImplicitArgIns; }
  1339. void SetHasImplicitArgIns(bool has) { m_hasImplicitArgIns = has; }
  1340. uint32 GetGrfscr() const;
  1341. void SetGrfscr(uint32 grfscr);
  1342. ///----------------------------------------------------------------------------
  1343. ///
  1344. /// ParseableFunctionInfo::GetInParamsCount
  1345. ///
  1346. /// GetInParamsCount() returns the number of "in parameters" that have
  1347. /// currently been declared for this function:
  1348. /// - If this is "RegSlot_VariableCount", the function takes a variable number
  1349. /// of parameters.
  1350. ///
  1351. /// Consider: Change to store type information about parameters- names, type,
  1352. /// direction, etc.
  1353. ///
  1354. ///----------------------------------------------------------------------------
  1355. ArgSlot GetInParamsCount() const { return m_inParamCount; }
  1356. void SetInParamsCount(ArgSlot newInParamCount);
  1357. ArgSlot GetReportedInParamsCount() const;
  1358. void SetReportedInParamsCount(ArgSlot newReportedInParamCount);
  1359. void ResetInParams();
  1360. ScopeInfo* GetScopeInfo() const { return this->GetAuxPtr<AuxPointerType::ScopeInfo>(); }
  1361. void SetScopeInfo(ScopeInfo* scopeInfo) { this->SetAuxPtr<AuxPointerType::ScopeInfo>(scopeInfo); }
  1362. PropertyId GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName);
  1363. void SetScopeSlotArraySizes(uint scopeSlotCount, uint scopeSlotCountForParamScope)
  1364. {
  1365. this->scopeSlotArraySize = scopeSlotCount;
  1366. this->paramScopeSlotArraySize = scopeSlotCountForParamScope;
  1367. }
  1368. PropertyId * GetPropertyIdsForScopeSlotArray() const { return this->GetAuxPtr<AuxPointerType::PropertyIdsForScopeSlotArray>(); }
  1369. void SetPropertyIdsForScopeSlotArray(Js::PropertyId * propertyIdsForScopeSlotArray, uint scopeSlotCount, uint scopeSlotCountForParamScope = 0)
  1370. {
  1371. SetScopeSlotArraySizes(scopeSlotCount, scopeSlotCountForParamScope);
  1372. this->SetAuxPtr<AuxPointerType::PropertyIdsForScopeSlotArray>(propertyIdsForScopeSlotArray);
  1373. }
  1374. void SetInitialDefaultEntryPoint();
  1375. void SetDeferredParsingEntryPoint();
  1376. void SetEntryPoint(ProxyEntryPointInfo* entryPoint, Js::JavascriptMethod jsMethod) {
  1377. entryPoint->jsMethod = jsMethod;
  1378. }
  1379. bool IsDynamicScript() const;
  1380. uint LengthInBytes() const { return m_cbLength; }
  1381. uint StartOffset() const;
  1382. ULONG GetLineNumber() const;
  1383. ULONG GetColumnNumber() const;
  1384. template <class T>
  1385. LPCWSTR GetSourceName(const T& sourceContextInfo) const;
  1386. template <class T>
  1387. static LPCWSTR GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction);
  1388. LPCWSTR GetSourceName() const;
  1389. ULONG GetRelativeLineNumber() const { return m_lineNumber; }
  1390. ULONG GetRelativeColumnNumber() const { return m_columnNumber; }
  1391. uint GetSourceIndex() const;
  1392. LPCUTF8 GetSource(const char16* reason = nullptr) const;
  1393. charcount_t LengthInChars() const { return m_cchLength; }
  1394. charcount_t StartInDocument() const;
  1395. bool IsEval() const { return m_isEval; }
  1396. bool IsDynamicFunction() const;
  1397. bool GetDontInline() { return m_dontInline; }
  1398. void SetDontInline(bool is) { m_dontInline = is; }
  1399. LPCUTF8 GetStartOfDocument(const char16* reason = nullptr) const;
  1400. bool IsReparsed() const { return m_reparsed; }
  1401. void SetReparsed(bool set) { m_reparsed = set; }
  1402. bool IsMethod() const { return m_isMethod; }
  1403. void SetIsMethod(bool set) { m_isMethod = set; }
  1404. #ifdef NTBUILD
  1405. bool GetExternalDisplaySourceName(BSTR* sourceName);
  1406. #endif
  1407. void CleanupToReparse();
  1408. void CleanupToReparseHelper();
  1409. bool EndsAfter(size_t offset) const;
  1410. void SetDoBackendArgumentsOptimization(bool set)
  1411. {
  1412. m_doBackendArgumentsOptimization = set;
  1413. }
  1414. bool GetDoBackendArgumentsOptimization()
  1415. {
  1416. return m_doBackendArgumentsOptimization;
  1417. }
  1418. void SetDoScopeObjectCreation(bool set)
  1419. {
  1420. m_doScopeObjectCreation = set;
  1421. }
  1422. bool GetDoScopeObjectCreation()
  1423. {
  1424. return m_doScopeObjectCreation;
  1425. }
  1426. void SetUsesArgumentsObject(bool set)
  1427. {
  1428. if (!m_usesArgumentsObject)
  1429. {
  1430. m_usesArgumentsObject = set;
  1431. }
  1432. }
  1433. bool GetUsesArgumentsObject()
  1434. {
  1435. return m_usesArgumentsObject;
  1436. }
  1437. bool IsFunctionParsed()
  1438. {
  1439. return !IsDeferredParseFunction() || m_hasBeenParsed;
  1440. }
  1441. void SetFunctionParsed(bool hasBeenParsed)
  1442. {
  1443. m_hasBeenParsed = hasBeenParsed;
  1444. }
  1445. void SetSourceInfo(uint sourceIndex, ParseNodeFnc * node, bool isEval, bool isDynamicFunction);
  1446. void SetSourceInfo(uint sourceIndex);
  1447. void Copy(ParseableFunctionInfo * other);
  1448. void Copy(FunctionBody* other);
  1449. void CopyNestedArray(ParseableFunctionInfo * other);
  1450. const char16* GetExternalDisplayName() const;
  1451. JavascriptString* GetExternalDisplayNameObject(ScriptContext* scriptContext) const;
  1452. //
  1453. // Algorithm to retrieve a function body's external display name. Template supports both
  1454. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1455. //
  1456. template <class T>
  1457. static const char16* GetExternalDisplayName(const T* funcBody)
  1458. {
  1459. Assert(funcBody != nullptr);
  1460. Assert(funcBody->GetDisplayName() != nullptr);
  1461. return funcBody->GetDisplayName();
  1462. }
  1463. virtual const char16* GetDisplayName() const override;
  1464. void SetDisplayName(const char16* displayName);
  1465. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1466. virtual void Finalize(bool isShutdown) override;
  1467. JavascriptString * GetCachedSourceString();
  1468. void SetCachedSourceString(JavascriptString * sourceString);
  1469. FunctionInfoArray GetNestedFuncArray();
  1470. FunctionInfo* GetNestedFunc(uint index);
  1471. FunctionInfoPtrPtr GetNestedFuncReference(uint index);
  1472. FunctionProxy* GetNestedFunctionProxy(uint index);
  1473. ParseableFunctionInfo* GetNestedFunctionForExecution(uint index);
  1474. void SetNestedFunc(FunctionInfo* nestedFunc, uint index, uint32 flags);
  1475. void BuildDeferredStubs(ParseNodeFnc* pnodeFnc);
  1476. DeferredFunctionStub *GetDeferredStubs() const { return this->GetAuxPtr<AuxPointerType::DeferredStubs>(); }
  1477. void SetDeferredStubs(DeferredFunctionStub *stub) { this->SetAuxPtr<AuxPointerType::DeferredStubs>(stub); }
  1478. void RegisterFuncToDiag(ScriptContext * scriptContext, char16 const * pszTitle);
  1479. bool IsES6ModuleCode() const;
  1480. private:
  1481. RecyclerWeakReference<JavascriptString> * GetCachedSourceStringWeakRef();
  1482. void SetCachedSourceStringWeakRef(RecyclerWeakReference<JavascriptString> * weakRef);
  1483. protected:
  1484. static HRESULT MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se);
  1485. void SetFlags(bool does, FunctionBodyFlags newFlags)
  1486. {
  1487. if (does)
  1488. {
  1489. flags = (FunctionBodyFlags)(flags | newFlags);
  1490. }
  1491. else
  1492. {
  1493. flags = (FunctionBodyFlags)(flags & ~newFlags);
  1494. }
  1495. }
  1496. FieldWithBarrier(bool) m_tag21 : 1;
  1497. FieldWithBarrier(bool) m_hasBeenParsed : 1; // Has function body been parsed- true for actual function bodies, false for deferparse
  1498. FieldWithBarrier(bool) m_isDeclaration : 1;
  1499. FieldWithBarrier(bool) m_isAccessor : 1; // Function is a property getter or setter
  1500. FieldWithBarrier(bool) m_isStaticNameFunction : 1;
  1501. FieldWithBarrier(bool) m_isNamedFunctionExpression : 1;
  1502. FieldWithBarrier(bool) m_isNameIdentifierRef : 1;
  1503. FieldWithBarrier(bool) m_isClassMember : 1;
  1504. // 8 bits from last tag
  1505. FieldWithBarrier(bool) m_isStrictMode : 1;
  1506. FieldWithBarrier(bool) m_isAsmjsMode : 1;
  1507. FieldWithBarrier(bool) m_isAsmJsFunction : 1;
  1508. FieldWithBarrier(bool) m_isWasmFunction : 1;
  1509. FieldWithBarrier(bool) m_isGlobalFunc : 1;
  1510. FieldWithBarrier(bool) m_doBackendArgumentsOptimization : 1;
  1511. FieldWithBarrier(bool) m_doScopeObjectCreation : 1;
  1512. FieldWithBarrier(bool) m_usesArgumentsObject : 1;
  1513. // 16 bits from last tag
  1514. FieldWithBarrier(bool) m_isEval : 1; // Source code is in 'eval'
  1515. FieldWithBarrier(bool) m_isDynamicFunction : 1; // Source code is in 'Function'
  1516. FieldWithBarrier(bool) m_hasImplicitArgIns : 1;
  1517. FieldWithBarrier(bool) m_dontInline : 1; // Used by the JIT's inliner
  1518. FieldWithBarrier(bool) m_reparsed : 1; // Indicates if the function has been reparsed for debug attach/detach scenario.
  1519. FieldWithBarrier(bool) m_isMethod : 1; // Function is an object literal method
  1520. #if DBG
  1521. FieldWithBarrier(bool) m_wasEverAsmjsMode : 1; // has m_isAsmjsMode ever been true
  1522. #endif
  1523. // This field is not required for deferred parsing but because our thunks can't handle offsets > 128 bytes
  1524. // yet, leaving this here for now. We can look at optimizing the function info and function proxy structures some
  1525. // more and also fix our thunks to handle 8 bit offsets
  1526. FieldWithBarrier(bool) m_utf8SourceHasBeenSet; // start of UTF8-encoded source
  1527. FieldWithBarrier(uint) m_sourceIndex; // index into the scriptContext's list of saved sources
  1528. #if DYNAMIC_INTERPRETER_THUNK
  1529. FieldNoBarrier(void*) m_dynamicInterpreterThunk; // Unique 'thunk' for every interpreted function - used for ETW symbol decoding.
  1530. #endif
  1531. FieldWithBarrier(uint) m_cbStartOffset; // pUtf8Source is this many bytes from the start of the scriptContext's source buffer.
  1532. // This is generally the same as m_cchStartOffset unless the buffer has a BOM
  1533. #define DEFINE_PARSEABLE_FUNCTION_INFO_FIELDS 1
  1534. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1535. #define CURRENT_ACCESS_MODIFIER protected:
  1536. #include "SerializableFunctionFields.h"
  1537. FieldWithBarrier(ULONG) m_lineNumber;
  1538. FieldWithBarrier(ULONG) m_columnNumber;
  1539. FieldWithBarrier(const char16*) m_displayName; // Optional name
  1540. FieldWithBarrier(uint) m_displayNameLength;
  1541. FieldWithBarrier(NestedArray*) nestedArray;
  1542. public:
  1543. #if DBG
  1544. FieldWithBarrier(Js::LocalFunctionId) deferredParseNextFunctionId;
  1545. #endif
  1546. #if DBG
  1547. FieldWithBarrier(UINT) scopeObjectSize; // If the scope is an activation object - its size
  1548. #endif
  1549. };
  1550. //
  1551. // Algorithm to retrieve a function body's source name (url). Template supports both
  1552. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1553. //
  1554. template <class T>
  1555. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo) const
  1556. {
  1557. return GetSourceName<T>(sourceContextInfo, this->m_isEval, this->m_isDynamicFunction);
  1558. }
  1559. template <class T>
  1560. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction)
  1561. {
  1562. if (sourceContextInfo->IsDynamic())
  1563. {
  1564. if (m_isEval)
  1565. {
  1566. return Constants::EvalCode;
  1567. }
  1568. else if (m_isDynamicFunction)
  1569. {
  1570. return Constants::FunctionCode;
  1571. }
  1572. else
  1573. {
  1574. return Constants::UnknownScriptCode;
  1575. }
  1576. }
  1577. else
  1578. {
  1579. return sourceContextInfo->url;
  1580. }
  1581. }
  1582. class FunctionBody : public ParseableFunctionInfo
  1583. {
  1584. DEFINE_VTABLE_CTOR_NO_REGISTER(FunctionBody, ParseableFunctionInfo);
  1585. friend class ByteCodeBufferBuilder;
  1586. friend class ByteCodeBufferReader;
  1587. #ifdef DYNAMIC_PROFILE_MUTATOR
  1588. friend class ::DynamicProfileMutator;
  1589. friend class ::DynamicProfileMutatorImpl;
  1590. #endif
  1591. friend class RemoteFunctionBody;
  1592. public:
  1593. // same as MachDouble, used in the Func.h
  1594. static const uint DIAGLOCALSLOTSIZE = 8;
  1595. enum class CounterFields : uint8
  1596. {
  1597. VarCount = 0,
  1598. ConstantCount = 1,
  1599. OutParamMaxDepth = 2,
  1600. ByteCodeCount = 3,
  1601. ByteCodeWithoutLDACount = 4,
  1602. ByteCodeInLoopCount = 5,
  1603. LoopCount = 6,
  1604. ForInLoopDepth = 7,
  1605. ProfiledForInLoopCount = 8,
  1606. InlineCacheCount = 9,
  1607. RootObjectLoadInlineCacheStart = 10,
  1608. RootObjectLoadMethodInlineCacheStart = 11,
  1609. RootObjectStoreInlineCacheStart = 12,
  1610. IsInstInlineCacheCount = 13,
  1611. ReferencedPropertyIdCount = 14,
  1612. ObjLiteralCount = 15,
  1613. LiteralRegexCount = 16,
  1614. InnerScopeCount = 17,
  1615. // Following counters uses ((uint32)-1) as default value
  1616. LocalClosureRegister = 18,
  1617. ParamClosureRegister = 19,
  1618. LocalFrameDisplayRegister = 20,
  1619. EnvRegister = 21,
  1620. ThisRegisterForEventHandler = 22,
  1621. FirstInnerScopeRegister = 23,
  1622. FuncExprScopeRegister = 24,
  1623. FirstTmpRegister = 25,
  1624. Max
  1625. };
  1626. private:
  1627. typedef CompactCounters<FunctionBody> CounterT;
  1628. FieldWithBarrier(CounterT) counters;
  1629. friend CounterT;
  1630. public:
  1631. uint32 GetCountField(FunctionBody::CounterFields fieldEnum) const;
  1632. uint32 SetCountField(FunctionBody::CounterFields fieldEnum, uint32 val);
  1633. uint32 IncreaseCountField(FunctionBody::CounterFields fieldEnum);
  1634. #if DBG
  1635. void LockDownCounters() { counters.isLockedDown = true; };
  1636. void UnlockCounters() { counters.isLockedDown = false; };
  1637. void SetIsClosing() { counters.isClosing = true; };
  1638. #endif
  1639. struct StatementMap
  1640. {
  1641. StatementMap() : isSubexpression(false) {}
  1642. static StatementMap * New(Recycler* recycler)
  1643. {
  1644. return RecyclerNew(recycler, StatementMap);
  1645. }
  1646. FieldWithBarrier(regex::Interval) sourceSpan;
  1647. FieldWithBarrier(regex::Interval) byteCodeSpan;
  1648. FieldWithBarrier(bool) isSubexpression;
  1649. };
  1650. // The type of StatementAdjustmentRecord.
  1651. // A bitmask that can be OR'ed of multiple values of the enum.
  1652. enum StatementAdjustmentType : ushort
  1653. {
  1654. SAT_None = 0,
  1655. // Specifies an adjustment for next statement when going from current to next.
  1656. // Used for transitioning from current stmt to next during normal control-flow,
  1657. // such as offset of Br after if-block when there is else block present,
  1658. // when throw happens inside if and we ignore exceptions (next statement in the list
  1659. // would be 'else' but we need to pass flow control to Br target rather than entering 'else').
  1660. SAT_FromCurrentToNext = 0x01,
  1661. // Specifies an adjustment for beginning of next statement.
  1662. // If there is adjustment record, the statement following it starts at specified offset and not at offset specified in statementMap.
  1663. // Used for set next statement from arbitrary location.
  1664. SAT_NextStatementStart = 0x02,
  1665. SAT_All = SAT_FromCurrentToNext | SAT_NextStatementStart
  1666. };
  1667. class StatementAdjustmentRecord
  1668. {
  1669. uint m_byteCodeOffset;
  1670. StatementAdjustmentType m_adjustmentType;
  1671. public:
  1672. StatementAdjustmentRecord();
  1673. StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset);
  1674. StatementAdjustmentRecord(const StatementAdjustmentRecord& other);
  1675. uint GetByteCodeOffset();
  1676. StatementAdjustmentType GetAdjustmentType();
  1677. };
  1678. // Offset and entry/exit of a block that must be processed in new interpreter frame rather than current.
  1679. // Used for try and catch blocks.
  1680. class CrossFrameEntryExitRecord
  1681. {
  1682. uint m_byteCodeOffset;
  1683. // true means enter, false means exit.
  1684. bool m_isEnterBlock;
  1685. public:
  1686. CrossFrameEntryExitRecord();
  1687. CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  1688. CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other);
  1689. uint GetByteCodeOffset() const;
  1690. bool GetIsEnterBlock();
  1691. };
  1692. typedef JsUtil::List<Js::FunctionBody::StatementMap*, ArenaAllocator> ArenaStatementMapList;
  1693. typedef JsUtil::List<Js::FunctionBody::StatementMap*> StatementMapList;
  1694. // Note: isLeaf = true template param below means that recycler should not be used to dispose the items.
  1695. typedef JsUtil::List<StatementAdjustmentRecord, Recycler, /* isLeaf = */ true> StatementAdjustmentRecordList;
  1696. typedef JsUtil::List<CrossFrameEntryExitRecord, Recycler, /* isLeaf = */ true> CrossFrameEntryExitRecordList;
  1697. // Contains recorded at bytecode generation time information about statements and try-catch blocks.
  1698. // Used by debugger.
  1699. struct AuxStatementData
  1700. {
  1701. // Contains statement adjustment data:
  1702. // For given bytecode, following statement needs an adjustment, see StatementAdjustmentType for details.
  1703. Field(StatementAdjustmentRecordList*) m_statementAdjustmentRecords;
  1704. // Contain data about entry/exit of blocks that cause processing in different interpreter stack frame, such as try or catch.
  1705. Field(CrossFrameEntryExitRecordList*) m_crossFrameBlockEntryExisRecords;
  1706. AuxStatementData();
  1707. };
  1708. class SourceInfo
  1709. {
  1710. friend class RemoteFunctionBody;
  1711. friend class ByteCodeBufferReader;
  1712. friend class ByteCodeBufferBuilder;
  1713. public:
  1714. FieldNoBarrier(SmallSpanSequence*) pSpanSequence;
  1715. FieldWithBarrier(RegSlot) frameDisplayRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1716. FieldWithBarrier(RegSlot) objectRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1717. FieldWithBarrier(ScopeObjectChain*) pScopeObjectChain;
  1718. FieldWithBarrier(ByteBlock*) m_probeBackingBlock; // NULL if no Probes, otherwise a copy of the unmodified the byte-codeblock //Delay
  1719. FieldWithBarrier(int32) m_probeCount; // The number of installed probes (such as breakpoints).
  1720. // List of bytecode offset for the Branch bytecode.
  1721. FieldWithBarrier(AuxStatementData*) m_auxStatementData;
  1722. SourceInfo():
  1723. frameDisplayRegister(0),
  1724. objectRegister(0),
  1725. pScopeObjectChain(nullptr),
  1726. m_probeBackingBlock(nullptr),
  1727. m_probeCount(0),
  1728. m_auxStatementData(nullptr),
  1729. pSpanSequence(nullptr)
  1730. {
  1731. }
  1732. };
  1733. private:
  1734. FieldWithBarrier(ByteBlock*) byteCodeBlock; // Function byte-code for script functions
  1735. FieldWithBarrier(FunctionEntryPointList*) entryPoints;
  1736. FieldWithBarrier(Field(Var)*) m_constTable;
  1737. FieldWithBarrier(void**) inlineCaches;
  1738. FieldWithBarrier(InlineCachePointerArray<PolymorphicInlineCache>) polymorphicInlineCaches; // Contains the latest polymorphic inline caches
  1739. FieldWithBarrier(PropertyId*) cacheIdToPropertyIdMap;
  1740. #if DBG
  1741. #define InlineCacheTypeNone 0x00
  1742. #define InlineCacheTypeInlineCache 0x01
  1743. #define InlineCacheTypeIsInst 0x02
  1744. FieldWithBarrier(byte*) m_inlineCacheTypes;
  1745. #endif
  1746. public:
  1747. PropertyId * GetCacheIdToPropertyIdMap()
  1748. {
  1749. return cacheIdToPropertyIdMap;
  1750. }
  1751. static DWORD GetAsmJsTotalLoopCountOffset() { return offsetof(FunctionBody, m_asmJsTotalLoopCount); }
  1752. #if DBG
  1753. FieldWithBarrier(int) m_DEBUG_executionCount; // Count of outstanding on InterpreterStackFrame
  1754. FieldWithBarrier(bool) m_nativeEntryPointIsInterpreterThunk; // NativeEntry entry point is in fact InterpreterThunk.
  1755. // Set by bgjit in OutOfMemory scenario during codegen.
  1756. #endif
  1757. //#if ENABLE_DEBUG_CONFIG_OPTIONS //TODO: need this?
  1758. FieldWithBarrier(uint) regAllocStoreCount;
  1759. FieldWithBarrier(uint) regAllocLoadCount;
  1760. FieldWithBarrier(uint) callCountStats;
  1761. //#endif
  1762. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1763. //
  1764. // If you add compile-time attributes to this set, be sure to add them to the attributes that are
  1765. // copied in FunctionBody::Clone
  1766. //
  1767. FieldWithBarrier(SourceInfo) m_sourceInfo; // position of the source
  1768. // Data needed by profiler:
  1769. FieldWithBarrier(uint) m_uScriptId; // Delay //Script Block it belongs to. This is function no. of the global function created by engine for each block
  1770. #if DBG
  1771. FieldWithBarrier(int) m_iProfileSession; // Script profile session the meta data of this function is reported to.
  1772. #endif // DEBUG
  1773. // R0 is reserved for the return value, R1 for the root object
  1774. static const RegSlot ReturnValueRegSlot = 0;
  1775. static const RegSlot RootObjectRegSlot = 1;
  1776. static const RegSlot FirstRegSlot = 1;
  1777. // This value be set on the stack (on a particular offset), when the frame value got changed.
  1778. static const int LocalsChangeDirtyValue = 1;
  1779. #define DEFINE_FUNCTION_BODY_FIELDS 1
  1780. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1781. #define CURRENT_ACCESS_MODIFIER public:
  1782. #include "SerializableFunctionFields.h"
  1783. private:
  1784. FieldWithBarrier(uint) inactiveCount;
  1785. // aligned with 8
  1786. FieldWithBarrier(bool) m_tag32 : 1;
  1787. FieldWithBarrier(bool) m_nativeEntryPointUsed : 1; // Code might have been generated but not yet used.
  1788. FieldWithBarrier(bool) hasDoneLoopBodyCodeGen : 1; // Code generated for loop body, but not necessary available to execute yet.
  1789. FieldWithBarrier(bool) m_isFuncRegistered : 1;
  1790. FieldWithBarrier(bool) m_isFuncRegisteredToDiag : 1; // Mentions the function's context is registered with diagprobe.
  1791. FieldWithBarrier(bool) funcEscapes : 1;
  1792. FieldWithBarrier(bool) m_hasBailoutInstrInJittedCode : 1; // Indicates whether function has bailout instructions. Valid only if hasDoneCodeGen is true
  1793. FieldWithBarrier(bool) m_pendingLoopHeaderRelease : 1; // Indicates whether loop headers need to be released
  1794. // 8 bits from last tag
  1795. FieldWithBarrier(bool) hasExecutionDynamicProfileInfo : 1;
  1796. FieldWithBarrier(bool) cleanedUp: 1;
  1797. FieldWithBarrier(bool) sourceInfoCleanedUp: 1;
  1798. FieldWithBarrier(bool) dontRethunkAfterBailout : 1;
  1799. FieldWithBarrier(bool) disableInlineApply : 1;
  1800. FieldWithBarrier(bool) disableInlineSpread : 1;
  1801. FieldWithBarrier(bool) hasHotLoop: 1;
  1802. FieldWithBarrier(bool) wasCalledFromLoop : 1;
  1803. // 16 bits from last tag
  1804. FieldWithBarrier(bool) hasNestedLoop : 1;
  1805. FieldWithBarrier(bool) recentlyBailedOutOfJittedLoopBody : 1;
  1806. FieldWithBarrier(bool) m_firstFunctionObject: 1;
  1807. FieldWithBarrier(bool) m_inlineCachesOnFunctionObject: 1;
  1808. // Used for the debug re-parse. Saves state of function on the first parse, and restores it on a reparse. The state below is either dependent on
  1809. // the state of the script context, or on other factors like whether it was defer parsed or not.
  1810. FieldWithBarrier(bool) m_hasSetIsObject : 1;
  1811. // Used for the debug purpose, this info will be stored (in the non-debug mode), when a function has all locals marked as non-local-referenced.
  1812. // So when we got to no-refresh debug mode, and try to re-use the same function body we can then enforce all locals to be non-local-referenced.
  1813. FieldWithBarrier(bool) m_hasAllNonLocalReferenced : 1;
  1814. FieldWithBarrier(bool) m_hasFunExprNameReference : 1;
  1815. FieldWithBarrier(bool) m_ChildCallsEval : 1;
  1816. // 24 bits from last tag
  1817. FieldWithBarrier(bool) m_CallsEval : 1;
  1818. FieldWithBarrier(bool) m_hasReferenceableBuiltInArguments : 1;
  1819. FieldWithBarrier(bool) m_isParamAndBodyScopeMerged : 1;
  1820. // Used in the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple times for each child function.
  1821. FieldWithBarrier(bool) m_hasDoneAllNonLocalReferenced : 1;
  1822. // Used by the script profiler, once the function compiled is sent this will be set to true.
  1823. FieldWithBarrier(bool) m_hasFunctionCompiledSent : 1;
  1824. FieldWithBarrier(bool) m_isFromNativeCodeModule : 1;
  1825. FieldWithBarrier(bool) m_isPartialDeserializedFunction : 1;
  1826. FieldWithBarrier(bool) m_isAsmJsScheduledForFullJIT : 1;
  1827. // 32 bits from last tag
  1828. FieldWithBarrier(bool) m_tag33 : 1;
  1829. FieldWithBarrier(bool) m_hasLocalClosureRegister : 1;
  1830. FieldWithBarrier(bool) m_hasParamClosureRegister : 1;
  1831. FieldWithBarrier(bool) m_hasLocalFrameDisplayRegister : 1;
  1832. FieldWithBarrier(bool) m_hasEnvRegister : 1;
  1833. FieldWithBarrier(bool) m_hasThisRegisterForEventHandler : 1;
  1834. FieldWithBarrier(bool) m_hasFirstInnerScopeRegister : 1;
  1835. FieldWithBarrier(bool) m_hasFuncExprScopeRegister : 1;
  1836. // 8 bits from last tag
  1837. FieldWithBarrier(bool) m_hasFirstTmpRegister : 1;
  1838. FieldWithBarrier(bool) m_hasActiveReference : 1;
  1839. FieldWithBarrier(bool) m_isJsBuiltInForceInline : 1;
  1840. #if DBG
  1841. FieldWithBarrier(bool) m_isSerialized : 1;
  1842. #endif
  1843. #ifdef PERF_COUNTERS
  1844. FieldWithBarrier(bool) m_isDeserializedFunction : 1;
  1845. #endif
  1846. #if DBG
  1847. // Indicates that nested functions can be allocated on the stack (but may not be)
  1848. FieldWithBarrier(bool) m_canDoStackNestedFunc : 1;
  1849. #endif
  1850. #ifdef IR_VIEWER
  1851. // whether IR Dump is enabled for this function (used by parseIR)
  1852. FieldWithBarrier(bool) m_isIRDumpEnabled : 1;
  1853. FieldWithBarrier(Js::DynamicObject*) m_irDumpBaseObject;
  1854. #endif /* IR_VIEWER */
  1855. FieldWithBarrier(uint8) bailOnMisingProfileCount;
  1856. FieldWithBarrier(uint8) bailOnMisingProfileRejitCount;
  1857. FieldWithBarrier(byte) inlineDepth; // Used by inlining to avoid recursively inlining functions excessively
  1858. FieldWithBarrier(FunctionExecutionStateMachine) executionState;
  1859. // Indicates how many times the function has been entered (so increases by one on each recursive call, decreases by one when we're done)
  1860. FieldWithBarrier(uint) m_depth;
  1861. FieldWithBarrier(uint32) loopInterpreterLimit;
  1862. FieldWithBarrier(uint32) debuggerScopeIndex;
  1863. FieldWithBarrier(uint32) savedPolymorphicCacheState;
  1864. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1865. //
  1866. // If you add compile-time attributes to the above set, be sure to add them to the attributes that are
  1867. // copied in FunctionBody::Clone
  1868. //
  1869. FieldNoBarrier(Js::ByteCodeCache*) byteCodeCache; // Not GC allocated so naked pointer
  1870. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1871. static bool shareInlineCaches;
  1872. #endif
  1873. FieldWithBarrier(FunctionEntryPointInfo*) defaultFunctionEntryPointInfo;
  1874. #if ENABLE_PROFILE_INFO
  1875. FieldWithBarrier(DynamicProfileInfo*) dynamicProfileInfo;
  1876. #endif
  1877. // select dynamic profile info saved off when we codegen and later
  1878. // used for rejit decisions (see bailout.cpp)
  1879. FieldWithBarrier(BYTE) savedInlinerVersion;
  1880. #if ENABLE_NATIVE_CODEGEN
  1881. FieldWithBarrier(ImplicitCallFlags) savedImplicitCallsFlags;
  1882. #endif
  1883. FunctionBody(ScriptContext* scriptContext, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount, Utf8SourceInfo* sourceInfo,
  1884. uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  1885. #ifdef PERF_COUNTERS
  1886. , bool isDeserializedFunction = false
  1887. #endif
  1888. );
  1889. FunctionBody(ParseableFunctionInfo * parseableFunctionInfo);
  1890. void SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, JavascriptMethod directEntryPoint);
  1891. #if DYNAMIC_INTERPRETER_THUNK
  1892. void GenerateDynamicInterpreterThunk();
  1893. #endif
  1894. Js::JavascriptMethod GetEntryPoint(ProxyEntryPointInfo* entryPoint) const { return entryPoint->jsMethod; }
  1895. void CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo);
  1896. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1897. void DumpRegStats(FunctionBody *funcBody);
  1898. #endif
  1899. public:
  1900. FunctionBody(ByteCodeCache* cache, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext):
  1901. ParseableFunctionInfo((JavascriptMethod) nullptr, 0, (LocalFunctionId) 0, sourceInfo, scriptContext, 0, nullptr, 0, 0, FunctionInfo::Attributes::None, Flags_None)
  1902. {
  1903. // Dummy constructor- does nothing
  1904. // Must be stack allocated
  1905. // Used during deferred bytecode serialization
  1906. }
  1907. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1908. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes
  1909. , FunctionBodyFlags flags
  1910. #ifdef PERF_COUNTERS
  1911. , bool isDeserializedFunction
  1912. #endif
  1913. );
  1914. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1915. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes
  1916. , FunctionBodyFlags flags
  1917. #ifdef PERF_COUNTERS
  1918. , bool isDeserializedFunction
  1919. #endif
  1920. );
  1921. static FunctionBody * NewFromParseableFunctionInfo(ParseableFunctionInfo * info);
  1922. FunctionEntryPointInfo * GetEntryPointInfo(int index) const;
  1923. FunctionEntryPointInfo * TryGetEntryPointInfo(int index) const;
  1924. bool DoRedeferFunction(uint inactiveThreshold) const;
  1925. void RedeferFunction();
  1926. void RedeferFunctionObjectTypes();
  1927. bool IsActiveFunction(ActiveFunctionSet * pActiveFuncs) const;
  1928. bool TestAndUpdateActiveFunctions(ActiveFunctionSet * pActiveFuncs) const;
  1929. void UpdateActiveFunctionSet(ActiveFunctionSet * pActiveFuncs, FunctionCodeGenRuntimeData *callSiteData) const;
  1930. void UpdateActiveFunctionsForOneDataSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *parentData, Field(FunctionCodeGenRuntimeData*)* dataSet, uint count) const;
  1931. uint GetInactiveCount() const { return inactiveCount; }
  1932. void SetInactiveCount(uint count) { inactiveCount = count; }
  1933. void IncrInactiveCount(uint increment);
  1934. bool InterpretedSinceCallCountCollection() const;
  1935. void CollectInterpretedCounts();
  1936. void ResetRedeferralAttributes() { this->m_hasActiveReference = false; }
  1937. Js::RootObjectBase * LoadRootObject() const;
  1938. Js::RootObjectBase * GetRootObject() const;
  1939. ByteBlock* GetAuxiliaryData() const { return this->GetAuxPtr<AuxPointerType::AuxBlock>(); }
  1940. ByteBlock* GetAuxiliaryDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::AuxBlock>(); }
  1941. void SetAuxiliaryData(ByteBlock* auxBlock) { this->SetAuxPtr<AuxPointerType::AuxBlock>(auxBlock); }
  1942. ByteBlock* GetAuxiliaryContextData()const { return this->GetAuxPtr<AuxPointerType::AuxContextBlock>(); }
  1943. ByteBlock* GetAuxiliaryContextDataWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AuxContextBlock>(); }
  1944. void SetAuxiliaryContextData(ByteBlock* auxContextBlock) { this->SetAuxPtr<AuxPointerType::AuxContextBlock>(auxContextBlock); }
  1945. void SetFormalsPropIdArray(PropertyIdArray * propIdArray);
  1946. PropertyIdArray* GetFormalsPropIdArray(bool checkForNull = true);
  1947. Var GetFormalsPropIdArrayOrNullObj();
  1948. ByteBlock* GetByteCode() const;
  1949. ByteBlock* GetOriginalByteCode(); // Returns original bytecode without probes (such as BPs).
  1950. Js::ByteCodeCache * GetByteCodeCache() const { return this->byteCodeCache; }
  1951. void SetByteCodeCache(Js::ByteCodeCache *byteCodeCache)
  1952. {
  1953. if (byteCodeCache != nullptr)
  1954. {
  1955. this->byteCodeCache = byteCodeCache;
  1956. }
  1957. }
  1958. #if DBG
  1959. void SetIsSerialized(bool serialized) { m_isSerialized = serialized; }
  1960. bool GetIsSerialized()const { return m_isSerialized; }
  1961. #endif
  1962. uint GetByteCodeCount() const { return GetCountField(CounterFields::ByteCodeCount); }
  1963. void SetByteCodeCount(uint count) { SetCountField(CounterFields::ByteCodeCount, count); }
  1964. uint GetByteCodeWithoutLDACount() const { return GetCountField(CounterFields::ByteCodeWithoutLDACount); }
  1965. void SetByteCodeWithoutLDACount(uint count) { SetCountField(CounterFields::ByteCodeWithoutLDACount, count); }
  1966. uint GetByteCodeInLoopCount() const { return GetCountField(CounterFields::ByteCodeInLoopCount); }
  1967. void SetByteCodeInLoopCount(uint count) { SetCountField(CounterFields::ByteCodeInLoopCount, count); }
  1968. uint16 GetEnvDepth() const { return m_envDepth; }
  1969. void SetEnvDepth(uint16 depth) { m_envDepth = depth; }
  1970. void SetEnvRegister(RegSlot reg);
  1971. void MapAndSetEnvRegister(RegSlot reg);
  1972. RegSlot GetEnvRegister() const;
  1973. void SetThisRegisterForEventHandler(RegSlot reg);
  1974. void MapAndSetThisRegisterForEventHandler(RegSlot reg);
  1975. RegSlot GetThisRegisterForEventHandler() const;
  1976. void SetLocalClosureRegister(RegSlot reg);
  1977. void MapAndSetLocalClosureRegister(RegSlot reg);
  1978. RegSlot GetLocalClosureRegister() const;
  1979. void SetParamClosureRegister(RegSlot reg);
  1980. void MapAndSetParamClosureRegister(RegSlot reg);
  1981. RegSlot GetParamClosureRegister() const;
  1982. void SetLocalFrameDisplayRegister(RegSlot reg);
  1983. void MapAndSetLocalFrameDisplayRegister(RegSlot reg);
  1984. RegSlot GetLocalFrameDisplayRegister() const;
  1985. void SetFirstInnerScopeRegister(RegSlot reg);
  1986. void MapAndSetFirstInnerScopeRegister(RegSlot reg);
  1987. RegSlot GetFirstInnerScopeRegister() const;
  1988. void SetFuncExprScopeRegister(RegSlot reg);
  1989. void MapAndSetFuncExprScopeRegister(RegSlot reg);
  1990. RegSlot GetFuncExprScopeRegister() const;
  1991. bool HasScopeObject() const { return hasScopeObject; }
  1992. void SetHasScopeObject(bool has) { hasScopeObject = has; }
  1993. uint GetInnerScopeCount() const { return GetCountField(CounterFields::InnerScopeCount); }
  1994. void SetInnerScopeCount(uint count) { SetCountField(CounterFields::InnerScopeCount, count); }
  1995. bool HasCachedScopePropIds() const { return hasCachedScopePropIds; }
  1996. void SetHasCachedScopePropIds(bool has) { hasCachedScopePropIds = has; }
  1997. uint32 GetInterpretedCount() const;
  1998. uint32 IncreaseInterpretedCount();
  1999. uint32 GetLoopInterpreterLimit() const { return loopInterpreterLimit; }
  2000. uint32 SetLoopInterpreterLimit(uint32 val) { return loopInterpreterLimit = val; }
  2001. // Gets the next index for tracking debugger scopes (increments the internal counter as well).
  2002. uint32 GetNextDebuggerScopeIndex() { return debuggerScopeIndex++; }
  2003. void SetDebuggerScopeIndex(uint32 index) { debuggerScopeIndex = index; }
  2004. size_t GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars);
  2005. void SetJsBuiltInForceInline() { m_isJsBuiltInForceInline = true; }
  2006. bool IsJsBuiltInForceInline() const { return m_isJsBuiltInForceInline; }
  2007. void AllocateLoopHeaders();
  2008. void ReleaseLoopHeaders();
  2009. Js::LoopHeader * GetLoopHeader(uint index) const;
  2010. Js::LoopHeader * GetLoopHeaderWithLock(uint index) const;
  2011. Js::LoopHeader * GetLoopHeaderArrayPtr() const
  2012. {
  2013. Assert(this->GetLoopHeaderArray() != nullptr);
  2014. return this->GetLoopHeaderArray();
  2015. }
  2016. #ifdef ASMJS_PLAT
  2017. void SetIsAsmJsFullJitScheduled(bool val){ m_isAsmJsScheduledForFullJIT = val; }
  2018. bool GetIsAsmJsFullJitScheduled(){ return m_isAsmJsScheduledForFullJIT; }
  2019. uint32 GetAsmJSTotalLoopCount() const
  2020. {
  2021. return m_asmJsTotalLoopCount;
  2022. }
  2023. void SetIsAsmJsFunction(bool isAsmJsFunction)
  2024. {
  2025. m_isAsmJsFunction = isAsmJsFunction;
  2026. }
  2027. #endif
  2028. const bool GetIsAsmJsFunction() const
  2029. {
  2030. return m_isAsmJsFunction;
  2031. }
  2032. #ifdef ASMJS_PLAT
  2033. bool IsHotAsmJsLoop()
  2034. {
  2035. // Negative MinTemplatizedJitLoopRunCount treats all loops as hot asm loop
  2036. if (CONFIG_FLAG(MinTemplatizedJitLoopRunCount) < 0 || m_asmJsTotalLoopCount > static_cast<uint>(CONFIG_FLAG(MinTemplatizedJitLoopRunCount)))
  2037. {
  2038. return true;
  2039. }
  2040. return false;
  2041. }
  2042. #endif
  2043. private:
  2044. void ResetLoops();
  2045. public:
  2046. static bool Is(void* ptr);
  2047. uint GetScriptId() const { return m_uScriptId; }
  2048. void* GetAddressOfScriptId() const
  2049. {
  2050. return (void*)&m_uScriptId;
  2051. }
  2052. static uint *GetJittedLoopIterationsSinceLastBailoutAddress(EntryPointInfo* info)
  2053. {
  2054. LoopEntryPointInfo* entryPoint = (LoopEntryPointInfo*)info;
  2055. return &entryPoint->jittedLoopIterationsSinceLastBailout;
  2056. }
  2057. FunctionEntryPointInfo* GetDefaultFunctionEntryPointInfo() const;
  2058. void SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint);
  2059. FunctionEntryPointInfo *GetSimpleJitEntryPointInfo() const;
  2060. void SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo);
  2061. void SetAsmJsExecutionMode();
  2062. void SetDefaultInterpreterExecutionMode();
  2063. ExecutionMode GetExecutionMode() const;
  2064. ExecutionMode GetInterpreterExecutionMode(const bool isPostBailout);
  2065. private:
  2066. bool IsInterpreterExecutionMode() const;
  2067. public:
  2068. bool TryTransitionToNextExecutionMode();
  2069. void TryTransitionToNextInterpreterExecutionMode();
  2070. void SetIsSpeculativeJitCandidate();
  2071. bool TryTransitionToJitExecutionMode();
  2072. void TransitionToSimpleJitExecutionMode();
  2073. void TransitionToFullJitExecutionMode();
  2074. void ReinitializeExecutionModeAndLimits();
  2075. private:
  2076. uint16 GetSimpleJitExecutedIterations() const;
  2077. public:
  2078. void ResetSimpleJitLimitAndCallCount();
  2079. private:
  2080. void SetSimpleJitCallCount(const uint16 simpleJitLimit) const;
  2081. void ResetSimpleJitCallCount();
  2082. public:
  2083. uint16 GetProfiledIterations() const;
  2084. public:
  2085. void OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo);
  2086. public:
  2087. void TraceExecutionMode(const char *const eventDescription = nullptr) const;
  2088. void TraceInterpreterExecutionMode() const;
  2089. private:
  2090. void DoTraceExecutionMode(const char *const eventDescription) const;
  2091. public:
  2092. bool DoSimpleJit() const;
  2093. bool DoSimpleJitWithLock() const;
  2094. bool DoSimpleJitDynamicProfile() const;
  2095. bool DoInterpreterProfile() const;
  2096. bool DoInterpreterProfileWithLock() const;
  2097. bool DoInterpreterAutoProfile() const;
  2098. public:
  2099. bool WasCalledFromLoop() const;
  2100. void SetWasCalledFromLoop();
  2101. public:
  2102. bool RecentlyBailedOutOfJittedLoopBody() const;
  2103. void SetRecentlyBailedOutOfJittedLoopBody(const bool value);
  2104. private:
  2105. static uint16 GetMinProfileIterations();
  2106. public:
  2107. static uint16 GetMinFunctionProfileIterations();
  2108. private:
  2109. static uint GetMinLoopProfileIterations(const uint loopInterpreterLimit);
  2110. public:
  2111. uint GetLoopProfileThreshold(const uint loopInterpreterLimit) const;
  2112. private:
  2113. static uint GetReducedLoopInterpretCount();
  2114. public:
  2115. uint GetLoopInterpretCount(LoopHeader* loopHeader) const;
  2116. private:
  2117. static bool DoObjectHeaderInlining();
  2118. static bool DoObjectHeaderInliningForConstructors();
  2119. public:
  2120. static bool DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity);
  2121. private:
  2122. static bool DoObjectHeaderInliningForObjectLiterals();
  2123. public:
  2124. static bool DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity);
  2125. static bool DoObjectHeaderInliningForObjectLiteral(const PropertyIdArray *const propIds);
  2126. static bool DoObjectHeaderInliningForEmptyObjects();
  2127. public:
  2128. #if DBG
  2129. int GetProfileSession() { return m_iProfileSession; }
  2130. #ifdef ENABLE_SCRIPT_DEBUGGING
  2131. Js::DebuggerMode GetDebuggerMode();
  2132. #endif
  2133. #endif
  2134. virtual void Finalize(bool isShutdown) override;
  2135. virtual void OnMark() override;
  2136. void Cleanup(bool isScriptContextClosing);
  2137. void CleanupSourceInfo(bool isScriptContextClosing);
  2138. template<bool IsScriptContextShutdown>
  2139. void CleanUpInlineCaches();
  2140. void CleanupRecyclerData(bool isRecyclerShutdown, bool doEntryPointCleanupCaptureStack);
  2141. #ifdef PERF_COUNTERS
  2142. void CleanupPerfCounter();
  2143. #endif
  2144. bool HasRejit() const
  2145. {
  2146. if(this->entryPoints)
  2147. {
  2148. return this->entryPoints->Count() > 1;
  2149. }
  2150. return false;
  2151. }
  2152. #pragma region SourceInfo Methods
  2153. void CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo);
  2154. void FinishSourceInfo();
  2155. RegSlot GetFrameDisplayRegister() const;
  2156. void SetFrameDisplayRegister(RegSlot frameDisplayRegister);
  2157. RegSlot GetObjectRegister() const;
  2158. void SetObjectRegister(RegSlot objectRegister);
  2159. bool HasObjectRegister() const { return GetObjectRegister() != 0; }
  2160. ScopeObjectChain *GetScopeObjectChain() const;
  2161. void SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain);
  2162. // fetch the Catch scope object which encloses the passed bytecode offset, returns NULL otherwise
  2163. Js::DebuggerScope * GetDiagCatchScopeObjectAt(int byteCodeOffset);
  2164. ByteBlock *GetProbeBackingBlock();
  2165. void SetProbeBackingBlock(ByteBlock* probeBackingBlock);
  2166. bool HasLineBreak() const;
  2167. bool HasLineBreak(charcount_t start, charcount_t end) const;
  2168. bool HasGeneratedFromByteCodeCache() const { return this->byteCodeCache != nullptr; }
  2169. void TrackLoad(int ichMin);
  2170. SmallSpanSequence* GetStatementMapSpanSequence() const { return m_sourceInfo.pSpanSequence; }
  2171. void RecordStatementMap(StatementMap* statementMap);
  2172. void RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data);
  2173. void RecordLoad(int ichMin, int bytecodeAfterLoad);
  2174. DebuggerScope* RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index = nullptr);
  2175. void RecordEndScopeObject(DebuggerScope* currentScope, int end);
  2176. DebuggerScope* AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  2177. bool TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope);
  2178. StatementMapList * GetStatementMaps() const { return static_cast<StatementMapList *>(this->GetAuxPtrWithLock<AuxPointerType::StatementMaps>()); }
  2179. void SetStatementMaps(StatementMapList *pStatementMaps) { this->SetAuxPtr<AuxPointerType::StatementMaps>(pStatementMaps); }
  2180. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenGetSetRuntimeData>(); }
  2181. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenGetSetRuntimeData>(); }
  2182. void SetCodeGenGetSetRuntimeData(FunctionCodeGenRuntimeData** codeGenGetSetRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenGetSetRuntimeData>(codeGenGetSetRuntimeData); }
  2183. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenRuntimeData>(); }
  2184. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenRuntimeData>(); }
  2185. void SetCodeGenRuntimeData(FunctionCodeGenRuntimeData** codeGenRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenRuntimeData>(codeGenRuntimeData); }
  2186. Field(FunctionCodeGenRuntimeData*)* GetCodeGenCallbackRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenCallbackRuntimeData>(); }
  2187. Field(FunctionCodeGenRuntimeData*)* GetCodeGenCallbackRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenCallbackRuntimeData>(); }
  2188. void SetCodeGenCallbackRuntimeData(FunctionCodeGenRuntimeData** codeGenArgumentRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenCallbackRuntimeData>(codeGenArgumentRuntimeData); }
  2189. template <typename TStatementMapList>
  2190. static StatementMap * GetNextNonSubexpressionStatementMap(TStatementMapList *statementMapList, int & startingAtIndex);
  2191. static StatementMap * GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex);
  2192. void RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType);
  2193. void RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  2194. // Find out an offset falls within the range. returns TRUE if found.
  2195. BOOL GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record);
  2196. bool GetLineCharOffset(int byteCodeOffset, ULONG* line, LONG* charOffset, bool canAllocateLineCache = true);
  2197. bool GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache = true);
  2198. // Given bytecode position, returns the start position of the statement and length of the statement.
  2199. bool GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength);
  2200. // skip any utf-8/utf-16 byte-order-mark. Returns the number of chars skipped.
  2201. static charcount_t SkipByteOrderMark(__in_bcount_z(4) LPCUTF8& documentStart)
  2202. {
  2203. charcount_t retValue = 0;
  2204. Assert(documentStart != nullptr);
  2205. if (documentStart[0] == 0xEF &&
  2206. documentStart[1] == 0xBB &&
  2207. documentStart[2] == 0xBF)
  2208. {
  2209. // UTF-8 - EF BB BF
  2210. // 3 bytes skipped - reports one char skipped
  2211. documentStart += 3;
  2212. retValue = 1;
  2213. }
  2214. else if ((documentStart[0] == 0xFF && documentStart[1] == 0xFE) ||
  2215. (documentStart[0] == 0xFE && documentStart[1] == 0xFF))
  2216. {
  2217. // UTF-16 LE - FF FE
  2218. // UTF-16 BE - FE FF
  2219. // 2 bytes skipped - reports one char skipped
  2220. documentStart += 2;
  2221. retValue = 1;
  2222. }
  2223. return retValue;
  2224. }
  2225. StatementMap* GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2226. int GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2227. StatementMap* GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2228. StatementMap* GetMatchingStatementMapFromSource(int byteCodeOffset, int* pMapIndex = nullptr);
  2229. void RecordFrameDisplayRegister(RegSlot slot);
  2230. void RecordObjectRegister(RegSlot slot);
  2231. CrossFrameEntryExitRecordList* GetCrossFrameEntryExitRecords();
  2232. #ifdef VTUNE_PROFILING
  2233. uint GetStartOffset(uint statementIndex) const;
  2234. ULONG GetSourceLineNumber(uint statementIndex);
  2235. #endif
  2236. #pragma endregion
  2237. // Field accessors
  2238. bool GetHasBailoutInstrInJittedCode() const { return this->m_hasBailoutInstrInJittedCode; }
  2239. void SetHasBailoutInstrInJittedCode(bool hasBailout) { this->m_hasBailoutInstrInJittedCode = hasBailout; }
  2240. bool GetCanDefer() const { return this->functionInfo->CanBeDeferred() && this->m_depth == 0 && !this->m_hasActiveReference; }
  2241. bool GetCanReleaseLoopHeaders() const { return (this->m_depth == 0); }
  2242. void SetPendingLoopHeaderRelease(bool pendingLoopHeaderRelease) { this->m_pendingLoopHeaderRelease = pendingLoopHeaderRelease; }
  2243. bool GetIsFromNativeCodeModule() const { return m_isFromNativeCodeModule; }
  2244. void SetIsFromNativeCodeModule(bool isFromNativeCodeModule) { m_isFromNativeCodeModule = isFromNativeCodeModule; }
  2245. uint GetLoopNumber(LoopHeader const * loopHeader) const;
  2246. uint GetLoopNumberWithLock(LoopHeader const * loopHeader) const;
  2247. bool GetHasAllocatedLoopHeaders() { return this->GetLoopHeaderArray() != nullptr; }
  2248. Js::LoopHeader* GetLoopHeaderArray() const { return this->GetAuxPtr<AuxPointerType::LoopHeaderArray>(); }
  2249. Js::LoopHeader* GetLoopHeaderArrayWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::LoopHeaderArray>(); }
  2250. void SetLoopHeaderArray(Js::LoopHeader* loopHeaderArray) { this->SetAuxPtr<AuxPointerType::LoopHeaderArray>(loopHeaderArray); }
  2251. #if ENABLE_NATIVE_CODEGEN
  2252. Js::JavascriptMethod GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex);
  2253. void SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint, uint loopNum);
  2254. #endif
  2255. void RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPoint, JavascriptMethod oldOriginalEntryPoint, FunctionEntryPointInfo* newEntryPoint);
  2256. FunctionEntryPointInfo* CreateNewDefaultEntryPoint();
  2257. void AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPoint);
  2258. // Kind of entry point for original entry point
  2259. #if DBG
  2260. BOOL IsInterpreterThunk() const;
  2261. BOOL IsDynamicInterpreterThunk() const;
  2262. #endif
  2263. BOOL IsNativeOriginalEntryPoint() const;
  2264. bool IsSimpleJitOriginalEntryPoint() const;
  2265. #if DYNAMIC_INTERPRETER_THUNK
  2266. static BYTE GetOffsetOfDynamicInterpreterThunk() { return static_cast<BYTE>(offsetof(FunctionBody, m_dynamicInterpreterThunk)); }
  2267. void* GetDynamicInterpreterEntryPoint() const
  2268. {
  2269. return m_dynamicInterpreterThunk;
  2270. }
  2271. bool HasInterpreterThunkGenerated() const
  2272. {
  2273. return m_dynamicInterpreterThunk != nullptr;
  2274. }
  2275. DWORD GetDynamicInterpreterThunkSize() const;
  2276. #endif
  2277. bool GetHasHotLoop() const { return hasHotLoop; };
  2278. void SetHasHotLoop();
  2279. bool GetHasNestedLoop() const { return hasNestedLoop; };
  2280. void SetHasNestedLoop(bool nest) { hasNestedLoop = nest; };
  2281. bool IsInlineApplyDisabled();
  2282. void InitDisableInlineApply();
  2283. void SetDisableInlineApply(bool set);
  2284. bool IsInlineSpreadDisabled() const { return disableInlineSpread; }
  2285. void InitDisableInlineSpread() { disableInlineSpread = this->GetLocalFunctionId() != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this); }
  2286. void SetDisableInlineSpread(bool set) { disableInlineSpread = set; }
  2287. bool CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy);
  2288. #if DBG
  2289. bool HasValidSourceInfo();
  2290. #endif
  2291. #if DYNAMIC_INTERPRETER_THUNK
  2292. JavascriptMethod EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo);
  2293. #endif
  2294. #if ENABLE_NATIVE_CODEGEN
  2295. void SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint);
  2296. typedef void (*SetNativeEntryPointFuncType)(FunctionEntryPointInfo* entryPointInfo, Js::FunctionBody * functionBody, Js::JavascriptMethod entryPoint);
  2297. static void DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2298. static void ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2299. bool GetNativeEntryPointUsed() const { return m_nativeEntryPointUsed; }
  2300. void SetNativeEntryPointUsed(bool nativeEntryPointUsed) { this->m_nativeEntryPointUsed = nativeEntryPointUsed; }
  2301. bool GetHasDoneLoopBodyCodeGen() const { return hasDoneLoopBodyCodeGen; }
  2302. void SetHasDoneLoopBodyCodeGen(bool hasDoneLoopBodyCodeGen) { this->hasDoneLoopBodyCodeGen = hasDoneLoopBodyCodeGen; }
  2303. #endif
  2304. bool GetIsFuncRegistered() { return m_isFuncRegistered; }
  2305. void SetIsFuncRegistered(bool isRegistered) { m_isFuncRegistered = isRegistered; }
  2306. bool GetHasLoops() const { return this->GetLoopCount() != 0; }
  2307. uint IncrLoopCount() { return this->IncreaseCountField(CounterFields::LoopCount); }
  2308. uint GetLoopCount() const { return this->GetCountField(CounterFields::LoopCount); }
  2309. uint SetLoopCount(uint count) { return this->SetCountField(CounterFields::LoopCount, count); }
  2310. uint GetForInLoopDepth() const { return this->GetCountField(CounterFields::ForInLoopDepth); }
  2311. uint SetForInLoopDepth(uint count) { return this->SetCountField(CounterFields::ForInLoopDepth, count); }
  2312. bool AllocProfiledForInLoopCount(ProfileId* profileId)
  2313. {
  2314. ProfileId profiledForInLoopCount = this->GetProfiledForInLoopCount();
  2315. if (profiledForInLoopCount != Constants::NoProfileId)
  2316. {
  2317. *profileId = profiledForInLoopCount;
  2318. this->IncreaseCountField(CounterFields::ProfiledForInLoopCount);
  2319. return true;
  2320. }
  2321. return false;
  2322. }
  2323. ProfileId GetProfiledForInLoopCount() const { return (ProfileId)this->GetCountField(CounterFields::ProfiledForInLoopCount); }
  2324. void SetProfiledForInLoopCount(ProfileId count) { this->SetCountField(CounterFields::ProfiledForInLoopCount, count); }
  2325. bool AllocProfiledDivOrRem(ProfileId* profileId) { if (this->profiledDivOrRemCount != Constants::NoProfileId) { *profileId = this->profiledDivOrRemCount++; return true; } return false; }
  2326. ProfileId GetProfiledDivOrRemCount() { return this->profiledDivOrRemCount; }
  2327. bool AllocProfiledSwitch(ProfileId* profileId) { if (this->profiledSwitchCount != Constants::NoProfileId) { *profileId = this->profiledSwitchCount++; return true; } return false; }
  2328. ProfileId GetProfiledSwitchCount() { return this->profiledSwitchCount; }
  2329. bool AllocProfiledCallSiteId(ProfileId* profileId) { if (this->profiledCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledCallSiteCount++; return true; } return false; }
  2330. ProfileId GetProfiledCallSiteCount() const { return this->profiledCallSiteCount; }
  2331. void SetProfiledCallSiteCount(ProfileId callSiteId) { this->profiledCallSiteCount = callSiteId; }
  2332. bool AllocProfiledArrayCallSiteId(ProfileId* profileId) { if (this->profiledArrayCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledArrayCallSiteCount++; return true; } return false; }
  2333. ProfileId GetProfiledArrayCallSiteCount() const { return this->profiledArrayCallSiteCount; }
  2334. bool AllocProfiledReturnTypeId(ProfileId* profileId) { if (this->profiledReturnTypeCount != Constants::NoProfileId) { *profileId = this->profiledReturnTypeCount++; return true; } return false; }
  2335. ProfileId GetProfiledReturnTypeCount() const { return this->profiledReturnTypeCount; }
  2336. bool AllocProfiledSlotId(ProfileId* profileId) { if (this->profiledSlotCount != Constants::NoProfileId) { *profileId = this->profiledSlotCount++; return true; } return false; }
  2337. ProfileId GetProfiledSlotCount() const { return this->profiledSlotCount; }
  2338. bool AllocProfiledLdLenId(ProfileId* profileId) { if (this->profiledLdLenCount != Constants::NoProfileId) { *profileId = this->profiledLdLenCount++; return true; } return false; }
  2339. ProfileId GetProfiledLdLenCount() const { return this->profiledLdLenCount; }
  2340. bool AllocProfiledLdElemId(ProfileId* profileId) { if (this->profiledLdElemCount != Constants::NoProfileId) { *profileId = this->profiledLdElemCount++; return true; } return false; }
  2341. ProfileId GetProfiledLdElemCount() const { return this->profiledLdElemCount; }
  2342. bool AllocProfiledStElemId(ProfileId* profileId) { if (this->profiledStElemCount != Constants::NoProfileId) { *profileId = this->profiledStElemCount++; return true; } return false; }
  2343. ProfileId GetProfiledStElemCount() const { return this->profiledStElemCount; }
  2344. uint GetProfiledFldCount() const { return this->GetInlineCacheCount(); }
  2345. ArgSlot GetProfiledInParamsCount() const { return this->GetInParamsCount() > 1? this->GetInParamsCount() - 1 : 0; }
  2346. bool IsPartialDeserializedFunction() { return this->m_isPartialDeserializedFunction; }
  2347. #ifdef PERF_COUNTERS
  2348. bool IsDeserializedFunction() { return this->m_isDeserializedFunction; }
  2349. #endif
  2350. #ifdef IR_VIEWER
  2351. bool IsIRDumpEnabled() const { return this->m_isIRDumpEnabled; }
  2352. void SetIRDumpEnabled(bool enabled) { this->m_isIRDumpEnabled = enabled; }
  2353. Js::DynamicObject * GetIRDumpBaseObject();
  2354. #endif /* IR_VIEWER */
  2355. #if ENABLE_NATIVE_CODEGEN
  2356. void SetPolymorphicCallSiteInfoHead(PolymorphicCallSiteInfo *polyCallSiteInfo) { this->SetAuxPtr<AuxPointerType::PolymorphicCallSiteInfoHead>(polyCallSiteInfo); }
  2357. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoHead() { return this->GetAuxPtr<AuxPointerType::PolymorphicCallSiteInfoHead>(); }
  2358. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoWithLock() { return this->GetAuxPtrWithLock<AuxPointerType::PolymorphicCallSiteInfoHead>(); }
  2359. void SetCallbackInfoList(CallbackInfoList * callbackInfoList) { this->SetAuxPtr<AuxPointerType::CallbackArgOutInfoList>(callbackInfoList); }
  2360. CallbackInfoList * GetCallbackInfoList() { return this->GetAuxPtr<AuxPointerType::CallbackArgOutInfoList>(); }
  2361. CallbackInfoList * GetCallbackInfoListWithLock() { return this->GetAuxPtrWithLock<AuxPointerType::CallbackArgOutInfoList>(); }
  2362. #endif
  2363. FunctionBodyPolymorphicInlineCache * GetPolymorphicInlineCachesHead() { return this->GetAuxPtr<AuxPointerType::PolymorphicInlineCachesHead>(); }
  2364. void SetPolymorphicInlineCachesHead(FunctionBodyPolymorphicInlineCache * cache) { this->SetAuxPtr<AuxPointerType::PolymorphicInlineCachesHead>(cache); }
  2365. bool PolyInliningUsingFixedMethodsAllowedByConfigFlags(FunctionBody* topFunctionBody)
  2366. {
  2367. return !PHASE_OFF(Js::InlinePhase, this) && !PHASE_OFF(Js::InlinePhase, topFunctionBody) &&
  2368. !PHASE_OFF(Js::PolymorphicInlinePhase, this) && !PHASE_OFF(Js::PolymorphicInlinePhase, topFunctionBody) &&
  2369. !PHASE_OFF(Js::FixedMethodsPhase, this) && !PHASE_OFF(Js::FixedMethodsPhase, topFunctionBody) &&
  2370. !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, this) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, topFunctionBody);
  2371. }
  2372. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainer() const
  2373. {
  2374. return this->GetAuxPtr<AuxPointerType::PropertyIdOnRegSlotsContainer>();
  2375. }
  2376. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainerWithLock() const
  2377. {
  2378. return this->GetAuxPtrWithLock<AuxPointerType::PropertyIdOnRegSlotsContainer>();
  2379. }
  2380. void SetPropertyIdOnRegSlotsContainer(Js::PropertyIdOnRegSlotsContainer *propertyIdOnRegSlotsContainer)
  2381. {
  2382. this->SetAuxPtr<AuxPointerType::PropertyIdOnRegSlotsContainer>(propertyIdOnRegSlotsContainer);
  2383. }
  2384. private:
  2385. void ResetProfileIds();
  2386. public:
  2387. bool GetHasFinally() const { return m_hasFinally; }
  2388. void SetHasFinally(bool has){ m_hasFinally = has; }
  2389. bool GetFuncEscapes() const { return funcEscapes; }
  2390. void SetFuncEscapes(bool does) { funcEscapes = does; }
  2391. #if DBG
  2392. bool CanDoStackNestedFunc() const { return m_canDoStackNestedFunc; }
  2393. void SetCanDoStackNestedFunc() { m_canDoStackNestedFunc = true; }
  2394. #endif
  2395. RecyclerWeakReference<FunctionInfo> * GetStackNestedFuncParent();
  2396. FunctionInfo * GetStackNestedFuncParentStrongRef();
  2397. FunctionInfo * GetAndClearStackNestedFuncParent();
  2398. void ClearStackNestedFuncParent();
  2399. void SetStackNestedFuncParent(FunctionInfo * parentFunctionInfo);
  2400. uint GetScopeSlotArraySize() const
  2401. {
  2402. return scopeSlotArraySize;
  2403. }
  2404. #if defined(_M_IX86) || defined(_M_X64)
  2405. template <typename T>
  2406. static bool DoStackClosure(T functionBody)
  2407. {
  2408. return functionBody->DoStackNestedFunc()
  2409. && functionBody->GetNestedCount() != 0
  2410. && functionBody->GetScopeSlotArraySize() != 0
  2411. && functionBody->GetEnvDepth() != (uint16)-1;
  2412. }
  2413. #else
  2414. template <typename T>
  2415. static bool DoStackClosure(T functionBody)
  2416. {
  2417. return false;
  2418. }
  2419. #endif
  2420. bool DoStackFrameDisplay() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2421. bool DoStackScopeSlots() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2422. bool GetIsFirstFunctionObject() const { return m_firstFunctionObject; }
  2423. void SetIsNotFirstFunctionObject() { m_firstFunctionObject = false; }
  2424. bool GetInlineCachesOnFunctionObject() { return m_inlineCachesOnFunctionObject; }
  2425. void SetInlineCachesOnFunctionObject(bool has) { m_inlineCachesOnFunctionObject = has; }
  2426. bool NeedScopeObjectForArguments(bool hasNonSimpleParams)
  2427. {
  2428. Assert(HasReferenceableBuiltInArguments());
  2429. // We can avoid creating a scope object with arguments present if:
  2430. bool dontNeedScopeObject =
  2431. // Either we are in strict mode, or have strict mode formal semantics from a non-simple parameter list, and
  2432. (GetIsStrictMode() || hasNonSimpleParams)
  2433. // Neither of the scopes are objects
  2434. && !HasScopeObject();
  2435. return
  2436. // Regardless of the conditions above, we won't need a scope object if there aren't any formals.
  2437. (GetInParamsCount() > 1 || GetHasRestParameter())
  2438. && !dontNeedScopeObject;
  2439. }
  2440. uint GetNumberOfRecursiveCallSites();
  2441. bool CanInlineRecursively(uint depth, bool tryAggressive = true);
  2442. public:
  2443. #if ENABLE_NATIVE_CODEGEN
  2444. bool CanInlineAgain() const
  2445. {
  2446. // Block excessive recursive inlining of the same function
  2447. return inlineDepth < static_cast<byte>(max(1, min(0xff, CONFIG_FLAG(MaxFuncInlineDepth))));
  2448. }
  2449. void OnBeginInlineInto()
  2450. {
  2451. ++inlineDepth;
  2452. }
  2453. void OnEndInlineInto()
  2454. {
  2455. --inlineDepth;
  2456. }
  2457. uint8 IncrementBailOnMisingProfileCount() { return ++bailOnMisingProfileCount; }
  2458. void ResetBailOnMisingProfileCount() { bailOnMisingProfileCount = 0; }
  2459. uint8 IncrementBailOnMisingProfileRejitCount() { return ++bailOnMisingProfileRejitCount; }
  2460. uint32 GetFrameHeight(EntryPointInfo* entryPointInfo) const;
  2461. #endif
  2462. RegSlot GetLocalsCount();
  2463. RegSlot GetConstantCount() const { return this->GetCountField(CounterFields::ConstantCount); }
  2464. void CheckAndSetConstantCount(RegSlot cNewConstants);
  2465. void SetConstantCount(RegSlot cNewConstants);
  2466. RegSlot GetVarCount();
  2467. void SetVarCount(RegSlot cNewVars);
  2468. void CheckAndSetVarCount(RegSlot cNewVars);
  2469. RegSlot MapRegSlot(RegSlot reg)
  2470. {
  2471. if (this->RegIsConst(reg))
  2472. {
  2473. reg = CONSTREG_TO_REGSLOT(reg);
  2474. Assert(reg < this->GetConstantCount());
  2475. }
  2476. else
  2477. {
  2478. reg += this->GetConstantCount();
  2479. }
  2480. return reg;
  2481. }
  2482. bool RegIsConst(RegSlot reg) { return reg > REGSLOT_TO_CONSTREG(this->GetConstantCount()); }
  2483. uint32 GetNonTempLocalVarCount();
  2484. uint32 GetFirstNonTempLocalIndex();
  2485. uint32 GetEndNonTempLocalIndex();
  2486. bool IsNonTempLocalVar(uint32 varIndex);
  2487. bool GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp = false);
  2488. RegSlot GetOutParamMaxDepth();
  2489. void SetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2490. void CheckAndSetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2491. #if _M_X64
  2492. // 1 Var to push current m_outparam, 1 Var for "this"
  2493. // 6 Vars for register optimization in InterpreterStackFrame::OP_CallAsmInternalCommon
  2494. static constexpr RegSlot MinAsmJsOutParams() { return 1 + 1 + 6; }
  2495. #endif
  2496. RegSlot GetYieldRegister();
  2497. RegSlot GetFirstTmpRegister() const;
  2498. void SetFirstTmpRegister(RegSlot reg);
  2499. RegSlot GetFirstTmpReg();
  2500. void SetFirstTmpReg(RegSlot firstTmpReg);
  2501. RegSlot GetTempCount();
  2502. Js::ModuleID GetModuleID() const;
  2503. void CreateConstantTable();
  2504. void RecordNullObject(RegSlot location);
  2505. void RecordUndefinedObject(RegSlot location);
  2506. void RecordTrueObject(RegSlot location);
  2507. void RecordFalseObject(RegSlot location);
  2508. void RecordIntConstant(RegSlot location, unsigned int val);
  2509. void RecordStrConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool forcePropertyString);
  2510. void RecordFloatConstant(RegSlot location, double d);
  2511. void RecordNullDisplayConstant(RegSlot location);
  2512. void RecordStrictNullDisplayConstant(RegSlot location);
  2513. void InitConstantSlots(Var *dstSlots);
  2514. Var GetConstantVar(RegSlot location);
  2515. Field(Js::Var)* GetConstTable() const { return this->m_constTable; }
  2516. void SetConstTable(Field(Js::Var)* constTable) { this->m_constTable = constTable; }
  2517. void MarkScript(ByteBlock * pblkByteCode, ByteBlock * pblkAuxiliaryData, ByteBlock* auxContextBlock,
  2518. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount);
  2519. void BeginExecution();
  2520. void EndExecution();
  2521. SourceInfo * GetSourceInfo() { return &this->m_sourceInfo; }
  2522. #ifdef ENABLE_SCRIPT_DEBUGGING
  2523. bool InstallProbe(int offset);
  2524. bool UninstallProbe(int offset);
  2525. bool ProbeAtOffset(int offset, OpCode* pOriginalOpcode);
  2526. #endif
  2527. static bool ShouldShareInlineCaches() { return CONFIG_FLAG(ShareInlineCaches); }
  2528. uint GetInlineCacheCount() const { return GetCountField(CounterFields::InlineCacheCount); }
  2529. void SetInlineCacheCount(uint count) { SetCountField(CounterFields::InlineCacheCount, count); }
  2530. uint GetRootObjectLoadInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadInlineCacheStart); }
  2531. void SetRootObjectLoadInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadInlineCacheStart, count); }
  2532. uint GetRootObjectLoadMethodInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart); }
  2533. void SetRootObjectLoadMethodInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart, count); }
  2534. uint GetRootObjectStoreInlineCacheStart() const { return GetCountField(CounterFields::RootObjectStoreInlineCacheStart); }
  2535. void SetRootObjectStoreInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectStoreInlineCacheStart, count); }
  2536. uint GetIsInstInlineCacheCount() const { return GetCountField(CounterFields::IsInstInlineCacheCount); }
  2537. void SetIsInstInlineCacheCount(uint count) { SetCountField(CounterFields::IsInstInlineCacheCount, count); }
  2538. uint GetReferencedPropertyIdCount() const { return GetCountField(CounterFields::ReferencedPropertyIdCount); }
  2539. void SetReferencedPropertyIdCount(uint count) { SetCountField(CounterFields::ReferencedPropertyIdCount, count); }
  2540. uint GetObjLiteralCount() const { return GetCountField(CounterFields::ObjLiteralCount); }
  2541. void SetObjLiteralCount(uint count) { SetCountField(CounterFields::ObjLiteralCount, count); }
  2542. uint IncObjLiteralCount() { return IncreaseCountField(CounterFields::ObjLiteralCount); }
  2543. uint GetLiteralRegexCount() const { return GetCountField(CounterFields::LiteralRegexCount); }
  2544. void SetLiteralRegexCount(uint count) { SetCountField(CounterFields::LiteralRegexCount, count); }
  2545. uint IncLiteralRegexCount() { return IncreaseCountField(CounterFields::LiteralRegexCount); }
  2546. void AllocateForInCache();
  2547. EnumeratorCache * GetForInCache(uint index);
  2548. EnumeratorCache * GetForInCacheArray();
  2549. void CleanUpForInCache(bool isShutdown);
  2550. void AllocateInlineCache();
  2551. InlineCache * GetInlineCache(uint index);
  2552. bool CanFunctionObjectHaveInlineCaches();
  2553. void** GetInlineCaches();
  2554. #if DBG
  2555. byte* GetInlineCacheTypes();
  2556. #endif
  2557. IsInstInlineCache * GetIsInstInlineCache(uint index);
  2558. PolymorphicInlineCache * GetPolymorphicInlineCache(uint index);
  2559. PolymorphicInlineCache * CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache);
  2560. PolymorphicInlineCache * CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId);
  2561. private:
  2562. void ResetInlineCaches();
  2563. PolymorphicInlineCache * CreatePolymorphicInlineCache(uint index, uint16 size);
  2564. FieldWithBarrier(uint32) m_asmJsTotalLoopCount;
  2565. public:
  2566. void CreateCacheIdToPropertyIdMap();
  2567. void CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart, uint rootObjectStoreInlineCacheStart,
  2568. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount);
  2569. void SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId);
  2570. PropertyId GetPropertyIdFromCacheId(uint cacheId)
  2571. {
  2572. Assert(this->cacheIdToPropertyIdMap);
  2573. Assert(cacheId < this->GetInlineCacheCount());
  2574. return this->cacheIdToPropertyIdMap[cacheId];
  2575. }
  2576. #if DBG
  2577. void VerifyCacheIdToPropertyIdMap();
  2578. #endif
  2579. PropertyId* GetReferencedPropertyIdMap() const { return this->GetAuxPtr<AuxPointerType::ReferencedPropertyIdMap>(); }
  2580. PropertyId* GetReferencedPropertyIdMapWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::ReferencedPropertyIdMap>(); }
  2581. void SetReferencedPropertyIdMap(PropertyId* propIdMap) { this->SetAuxPtr<AuxPointerType::ReferencedPropertyIdMap>(propIdMap); }
  2582. void CreateReferencedPropertyIdMap(uint referencedPropertyIdCount);
  2583. void CreateReferencedPropertyIdMap();
  2584. PropertyId GetReferencedPropertyIdWithMapIndex(uint mapIndex);
  2585. PropertyId GetReferencedPropertyIdWithMapIndexWithLock(uint mapIndex);
  2586. void SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId);
  2587. PropertyId GetReferencedPropertyId(uint index);
  2588. PropertyId GetReferencedPropertyIdWithLock(uint index);
  2589. #if DBG
  2590. void VerifyReferencedPropertyIdMap();
  2591. #endif
  2592. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2593. void DumpFullFunctionName();
  2594. void DumpFunctionId(bool pad);
  2595. uint GetTraceFunctionNumber() const;
  2596. #endif
  2597. public:
  2598. uint NewObjectLiteral();
  2599. void AllocateObjectLiteralTypeArray();
  2600. Field(DynamicType*)* GetObjectLiteralTypeRef(uint index);
  2601. Field(DynamicType*)* GetObjectLiteralTypeRefWithLock(uint index);
  2602. uint NewLiteralRegex();
  2603. void AllocateLiteralRegexArray();
  2604. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexes() const { return this->GetAuxPtr<AuxPointerType::LiteralRegexes>(); }
  2605. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexesWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::LiteralRegexes>(); }
  2606. void SetLiteralRegexs(UnifiedRegex::RegexPattern ** literalRegexes) { this->SetAuxPtr<AuxPointerType::LiteralRegexes>(literalRegexes); }
  2607. UnifiedRegex::RegexPattern *GetLiteralRegex(const uint index);
  2608. UnifiedRegex::RegexPattern *GetLiteralRegexWithLock(const uint index);
  2609. #ifdef ASMJS_PLAT
  2610. AsmJsFunctionInfo* GetAsmJsFunctionInfo() const { return this->GetAuxPtr<AuxPointerType::AsmJsFunctionInfo>(); }
  2611. AsmJsFunctionInfo* GetAsmJsFunctionInfoWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AsmJsFunctionInfo>(); }
  2612. AsmJsFunctionInfo* AllocateAsmJsFunctionInfo();
  2613. AsmJsModuleInfo* GetAsmJsModuleInfo()const { return this->GetAuxPtr<AuxPointerType::AsmJsModuleInfo>(); }
  2614. AsmJsModuleInfo* GetAsmJsModuleInfoWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AsmJsModuleInfo>(); }
  2615. void ResetAsmJsInfo()
  2616. {
  2617. this->SetAuxPtr<AuxPointerType::AsmJsFunctionInfo>(nullptr);
  2618. this->SetAuxPtr<AuxPointerType::AsmJsModuleInfo>(nullptr);
  2619. }
  2620. bool IsAsmJSModule() const { return m_isAsmjsMode && !m_isAsmJsFunction; }
  2621. AsmJsModuleInfo* AllocateAsmJsModuleInfo();
  2622. #endif
  2623. void SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern);
  2624. Field(DynamicType*)* GetObjectLiteralTypes() const { return this->GetAuxPtr<AuxPointerType::ObjLiteralTypes>(); }
  2625. Field(DynamicType*)* GetObjectLiteralTypesWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::ObjLiteralTypes>(); }
  2626. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArray() const { return this->GetAuxPtr<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(); }
  2627. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArrayWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(); }
  2628. Js::AuxArray<uint32> * AllocateSlotIdInCachedScopeToNestedIndexArray(uint32 slotCount);
  2629. private:
  2630. void ResetLiteralRegexes();
  2631. void ResetObjectLiteralTypes();
  2632. void SetObjectLiteralTypes(DynamicType** objLiteralTypes) { this->SetAuxPtr<AuxPointerType::ObjLiteralTypes>(objLiteralTypes); };
  2633. void SetSlotIdInCachedScopeToNestedIndexArray(Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray) { this->SetAuxPtr<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(slotIdInCachedScopeToNestedIndexArray); }
  2634. void ResetSlotIdInCachedScopeToNestedIndexArray() { SetSlotIdInCachedScopeToNestedIndexArray(nullptr); }
  2635. public:
  2636. void ResetByteCodeGenState();
  2637. void ResetByteCodeGenVisitState();
  2638. void FindClosestStatements(int32 characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation);
  2639. #if ENABLE_NATIVE_CODEGEN
  2640. template<AuxPointerType T>
  2641. FunctionCodeGenRuntimeData *EnsureCodeGenRuntimeDataCommon(
  2642. Recycler *const recycler,
  2643. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2644. FunctionBody *const inlinee);
  2645. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2646. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, FunctionBody *inlineeFuncBody) const;
  2647. FunctionCodeGenRuntimeData *EnsureInlineeCodeGenRuntimeData(
  2648. Recycler *const recycler,
  2649. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2650. FunctionBody *const inlinee);
  2651. const FunctionCodeGenRuntimeData *GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const;
  2652. FunctionCodeGenRuntimeData *EnsureLdFldInlineeCodeGenRuntimeData(
  2653. Recycler *const recycler,
  2654. const InlineCacheIndex inlineCacheIndex,
  2655. FunctionBody *const inlinee);
  2656. const FunctionCodeGenRuntimeData * GetCallbackInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2657. FunctionCodeGenRuntimeData * EnsureCallbackInlineeCodeGenRuntimeData(
  2658. Recycler *const recycler,
  2659. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2660. FunctionBody *const inlinee);
  2661. void LoadDynamicProfileInfo();
  2662. bool HasExecutionDynamicProfileInfo() const { return hasExecutionDynamicProfileInfo; }
  2663. bool HasDynamicProfileInfo() const { return dynamicProfileInfo != nullptr; }
  2664. bool NeedEnsureDynamicProfileInfo() const;
  2665. DynamicProfileInfo * GetDynamicProfileInfo() const { Assert(HasExecutionDynamicProfileInfo()); return dynamicProfileInfo; }
  2666. DynamicProfileInfo * GetAnyDynamicProfileInfo() const { Assert(HasDynamicProfileInfo()); return dynamicProfileInfo; }
  2667. DynamicProfileInfo * EnsureDynamicProfileInfo();
  2668. DynamicProfileInfo * AllocateDynamicProfile();
  2669. BYTE GetSavedInlinerVersion() const;
  2670. uint32 GetSavedPolymorphicCacheState() const;
  2671. void SetSavedPolymorphicCacheState(uint32 state);
  2672. ImplicitCallFlags GetSavedImplicitCallsFlags() const;
  2673. bool HasNonBuiltInCallee();
  2674. void RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 offset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum);
  2675. void SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint);
  2676. BOOL GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2677. BOOL GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2678. FunctionEntryPointInfo * GetEntryPointFromNativeAddress(DWORD_PTR codeAddress);
  2679. LoopEntryPointInfo * GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const;
  2680. #endif
  2681. void InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount);
  2682. void InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount);
  2683. void SetPropertyIdsOfFormals(PropertyIdArray * formalArgs);
  2684. PropertyIdArray * AllocatePropertyIdArrayForFormals(uint32 size, uint32 count, byte extraSlots);
  2685. bool DontRethunkAfterBailout() const { return dontRethunkAfterBailout; }
  2686. void SetDontRethunkAfterBailout() { dontRethunkAfterBailout = true; }
  2687. void ClearDontRethunkAfterBailout() { dontRethunkAfterBailout = false; }
  2688. void SaveState(ParseNodeFnc * pnodeFnc);
  2689. void RestoreState(ParseNodeFnc * pnodeFnc);
  2690. // Used for the debug purpose, this info will be stored (in the non-debug mode), when a function has all locals marked as non-local-referenced.
  2691. // So when we got to no-refresh debug mode, and try to re-use the same function body we can then enforce all locals to be non-local-referenced.
  2692. bool HasAllNonLocalReferenced() const { return m_hasAllNonLocalReferenced; }
  2693. void SetAllNonLocalReferenced(bool set) { m_hasAllNonLocalReferenced = set; }
  2694. bool HasSetIsObject() const { return m_hasSetIsObject; }
  2695. void SetHasSetIsObject(bool set) { m_hasSetIsObject = set; }
  2696. bool HasFuncExprNameReference() const { return m_hasFunExprNameReference; }
  2697. void SetFuncExprNameReference(bool value) { m_hasFunExprNameReference = value; }
  2698. bool GetChildCallsEval() const { return m_ChildCallsEval; }
  2699. void SetChildCallsEval(bool value) { m_ChildCallsEval = value; }
  2700. bool GetCallsEval() const { return m_CallsEval; }
  2701. void SetCallsEval(bool set) { m_CallsEval = set; }
  2702. bool HasReferenceableBuiltInArguments() const { return m_hasReferenceableBuiltInArguments; }
  2703. void SetHasReferenceableBuiltInArguments(bool value) { m_hasReferenceableBuiltInArguments = value; }
  2704. bool IsParamAndBodyScopeMerged() const { return m_isParamAndBodyScopeMerged; }
  2705. void SetParamAndBodyScopeNotMerged() { m_isParamAndBodyScopeMerged = false; }
  2706. // Used for the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple time for each child function.
  2707. bool HasDoneAllNonLocalReferenced() const { return m_hasDoneAllNonLocalReferenced; }
  2708. void SetHasDoneAllNonLocalReferenced(bool set) { m_hasDoneAllNonLocalReferenced = set; }
  2709. // Once the function compiled is sent m_hasFunctionCompiledSent will be set to 'true'. The below check will be used only to determine during ProfileModeDeferredParse function.
  2710. bool HasFunctionCompiledSent() const { return m_hasFunctionCompiledSent; }
  2711. void SetHasFunctionCompiledSent(bool set) { m_hasFunctionCompiledSent = set; }
  2712. #if DBG_DUMP
  2713. void DumpStatementMaps();
  2714. void Dump();
  2715. void PrintStatementSourceLine(uint statementIndex);
  2716. void PrintStatementSourceLineFromStartOffset(uint cchStartOffset);
  2717. void DumpScopes();
  2718. #endif
  2719. uint GetStatementStartOffset(const uint statementIndex);
  2720. #ifdef IR_VIEWER
  2721. void GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2722. ULONG * line, LONG * col);
  2723. void GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2724. ULONG * line, LONG * col);
  2725. #endif
  2726. #if ENABLE_TTD
  2727. void GetSourceLineFromStartOffset_TTD(const uint startOffset, ULONG* line, LONG* col);
  2728. #endif
  2729. #ifdef ENABLE_SCRIPT_PROFILING
  2730. HRESULT RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent = FALSE);
  2731. HRESULT ReportScriptCompiled();
  2732. HRESULT ReportFunctionCompiled();
  2733. void SetEntryToProfileMode();
  2734. #endif
  2735. #ifdef ENABLE_SCRIPT_DEBUGGING
  2736. void CheckAndRegisterFuncToDiag(ScriptContext *scriptContext);
  2737. void SetEntryToDeferParseForDebugger();
  2738. #endif
  2739. void ClearEntryPoints();
  2740. void ResetEntryPoint();
  2741. void CleanupToReparseHelper();
  2742. void UpdateEntryPointsOnDebugReparse();
  2743. void AddDeferParseAttribute();
  2744. void RemoveDeferParseAttribute();
  2745. #if DBG
  2746. void MustBeInDebugMode();
  2747. #endif
  2748. static bool IsDummyGlobalRetStatement(const regex::Interval *sourceSpan)
  2749. {
  2750. Assert(sourceSpan != nullptr);
  2751. return sourceSpan->begin == 0 && sourceSpan->end == 0;
  2752. }
  2753. static void GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer);
  2754. template<class Fn>
  2755. void MapLoopHeaders(Fn fn) const
  2756. {
  2757. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2758. if(loopHeaderArray)
  2759. {
  2760. uint loopCount = this->GetLoopCount();
  2761. for(uint i = 0; i < loopCount; i++)
  2762. {
  2763. fn(i , &loopHeaderArray[i]);
  2764. }
  2765. }
  2766. }
  2767. template<class Fn>
  2768. void MapLoopHeadersWithLock(Fn fn) const
  2769. {
  2770. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArrayWithLock();
  2771. if (loopHeaderArray)
  2772. {
  2773. uint loopCount = this->GetLoopCount();
  2774. for (uint i = 0; i < loopCount; i++)
  2775. {
  2776. fn(i, &loopHeaderArray[i]);
  2777. }
  2778. }
  2779. }
  2780. template<class Fn>
  2781. bool MapLoopHeadersUntil(Fn fn) const
  2782. {
  2783. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2784. if (loopHeaderArray)
  2785. {
  2786. uint loopCount = this->GetLoopCount();
  2787. for (uint i = 0; i < loopCount; i++)
  2788. {
  2789. if (fn(i, &loopHeaderArray[i]))
  2790. {
  2791. return true;
  2792. }
  2793. }
  2794. return false;
  2795. }
  2796. return false;
  2797. }
  2798. template <class Fn>
  2799. void MapEntryPoints(Fn fn) const
  2800. {
  2801. if (this->entryPoints)
  2802. {
  2803. this->entryPoints->Map([&fn] (int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2804. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2805. if (strongRef)
  2806. {
  2807. fn(index, strongRef);
  2808. }
  2809. });
  2810. }
  2811. }
  2812. template <class Fn>
  2813. bool MapEntryPointsUntil(Fn fn) const
  2814. {
  2815. if (this->entryPoints)
  2816. {
  2817. return this->entryPoints->MapUntil([&fn](int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2818. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2819. if (strongRef)
  2820. {
  2821. return fn(index, strongRef);
  2822. }
  2823. return false;
  2824. });
  2825. }
  2826. return false;
  2827. }
  2828. bool DoJITLoopBody() const
  2829. {
  2830. return IsJitLoopBodyPhaseEnabled() && this->GetLoopHeaderArrayWithLock() != nullptr;
  2831. }
  2832. bool ForceJITLoopBody() const
  2833. {
  2834. return IsJitLoopBodyPhaseForced() && !this->GetHasTry();
  2835. }
  2836. bool IsGeneratorAndJitIsDisabled()
  2837. {
  2838. return this->IsCoroutine() && !(CONFIG_ISENABLED(Js::JitES6GeneratorsFlag) && !this->GetHasTry());
  2839. }
  2840. FunctionBodyFlags * GetAddressOfFlags() { return &this->flags; }
  2841. Js::RegSlot GetRestParamRegSlot();
  2842. public:
  2843. void RecordConstant(RegSlot location, Var var);
  2844. private:
  2845. inline void CheckEmpty();
  2846. inline void CheckNotExecuting();
  2847. BOOL GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee);
  2848. #if ENABLE_NATIVE_CODEGEN
  2849. int GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset);
  2850. int GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress);
  2851. #endif
  2852. void EnsureAuxStatementData();
  2853. StatementAdjustmentRecordList* GetStatementAdjustmentRecords();
  2854. };
  2855. class AutoRestoreFunctionInfo {
  2856. public:
  2857. AutoRestoreFunctionInfo(ParseableFunctionInfo *pfi, const JavascriptMethod originalEntryPoint) : pfi(pfi), funcBody(nullptr), originalEntryPoint(originalEntryPoint) {}
  2858. ~AutoRestoreFunctionInfo() {
  2859. if (this->pfi != nullptr && this->pfi->GetFunctionInfo()->GetFunctionProxy() != this->pfi)
  2860. {
  2861. FunctionInfo *functionInfo = this->pfi->GetFunctionInfo();
  2862. FunctionBody *functionBody = functionInfo->GetFunctionProxy()->GetFunctionBody();
  2863. functionBody->RedeferFunctionObjectTypes();
  2864. functionInfo->SetAttributes(
  2865. (FunctionInfo::Attributes)(functionInfo->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  2866. functionInfo->SetFunctionProxy(this->pfi);
  2867. functionInfo->SetOriginalEntryPoint(originalEntryPoint);
  2868. }
  2869. Assert(this->pfi == nullptr || (this->pfi->GetFunctionInfo()->GetFunctionProxy() == this->pfi && !this->pfi->IsFunctionBody()));
  2870. }
  2871. void Clear() { pfi = nullptr; funcBody = nullptr; }
  2872. ParseableFunctionInfo * pfi;
  2873. FunctionBody * funcBody;
  2874. const JavascriptMethod originalEntryPoint;
  2875. };
  2876. // If we throw or fail with the function body in an unfinished state, make sure the function info is still
  2877. // pointing to the old ParseableFunctionInfo and has the right attributes.
  2878. typedef SynchronizableList<FunctionBody*, JsUtil::List<FunctionBody*, ArenaAllocator, false, Js::FreeListedRemovePolicy> > FunctionBodyList;
  2879. struct ScopeSlots
  2880. {
  2881. public:
  2882. static uint const MaxEncodedSlotCount = Constants::UShortMaxValue;
  2883. // The slot index is at the same location as the vtable, so that we can distinguish between scope slot and frame display
  2884. static uint const EncodedSlotCountSlotIndex = 0;
  2885. static uint const ScopeMetadataSlotIndex = 1; // Either a FunctionBody* or DebuggerScope*
  2886. static uint const FirstSlotIndex = 2;
  2887. public:
  2888. ScopeSlots(Field(Var)* slotArray) : slotArray(slotArray)
  2889. {
  2890. }
  2891. bool IsDebuggerScopeSlotArray();
  2892. FunctionInfo* GetFunctionInfo()
  2893. {
  2894. Assert(!IsDebuggerScopeSlotArray());
  2895. return (FunctionInfo*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  2896. }
  2897. DebuggerScope* GetDebuggerScope()
  2898. {
  2899. Assert(IsDebuggerScopeSlotArray());
  2900. return (DebuggerScope*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  2901. }
  2902. Var GetScopeMetadataRaw() const
  2903. {
  2904. return slotArray[ScopeMetadataSlotIndex];
  2905. }
  2906. void SetScopeMetadata(Var scopeMetadataObj)
  2907. {
  2908. slotArray[ScopeMetadataSlotIndex] = scopeMetadataObj;
  2909. }
  2910. size_t GetCount() const
  2911. {
  2912. return ::Math::PointerCastToIntegralTruncate<size_t>(slotArray[EncodedSlotCountSlotIndex]);
  2913. }
  2914. void SetCount(uint count)
  2915. {
  2916. slotArray[EncodedSlotCountSlotIndex] = (Var)min<uint>(count, ScopeSlots::MaxEncodedSlotCount);
  2917. }
  2918. Var Get(uint i) const
  2919. {
  2920. Assert(i < GetCount());
  2921. return slotArray[i + FirstSlotIndex];
  2922. }
  2923. void Set(uint i, Var value)
  2924. {
  2925. Assert(i < GetCount());
  2926. slotArray[i + FirstSlotIndex] = value;
  2927. }
  2928. template<class Fn>
  2929. void Map(Fn fn)
  2930. {
  2931. uint count = GetCount();
  2932. for(uint i = 0; i < count; i++)
  2933. {
  2934. fn(GetSlot[i]);
  2935. }
  2936. }
  2937. // The first pointer sized value in the object for scope slots is the count, while it is a vtable
  2938. // for Activation object or with scope (a recyclable object)
  2939. // VTable values are always > 64K because they are a pointer, hence anything less than that implies
  2940. // a slot array.
  2941. // CONSIDER: Use TaggedInt instead of range of slot count to distinguish slot array with others.
  2942. static bool Is(void* object)
  2943. {
  2944. if (object == nullptr)
  2945. {
  2946. // Null slot in a frame where nothing is captured and the scope object has been eliminated
  2947. // by stack args optimization.
  2948. return false;
  2949. }
  2950. size_t slotCount = *((size_t*)object);
  2951. if(slotCount <= MaxEncodedSlotCount)
  2952. {
  2953. return true;
  2954. }
  2955. return false;
  2956. }
  2957. private:
  2958. Field(Field(Var)*) slotArray;
  2959. };
  2960. enum ScopeType
  2961. {
  2962. ScopeType_ActivationObject,
  2963. ScopeType_SlotArray,
  2964. ScopeType_WithScope
  2965. };
  2966. // A FrameDisplay encodes a FunctionObject's scope chain. It is an array of scopes, where each scope can be either an inline slot array
  2967. // or a RecyclableObject. A FrameDisplay for a given FunctionObject will consist of the FrameDisplay from it's enclosing scope, with any additional
  2968. // scopes prepended. Due to with statements etc. a function may introduce multiple scopes to the FrameDisplay.
  2969. struct FrameDisplay
  2970. {
  2971. FrameDisplay(uint16 len, bool strictMode = false) :
  2972. tag(true),
  2973. length(len),
  2974. strictMode(strictMode)
  2975. #if _M_X64
  2976. , unused(0)
  2977. #endif
  2978. {
  2979. }
  2980. void SetTag(bool tag) { this->tag = tag; }
  2981. void SetItem(uint index, void* item);
  2982. void *GetItem(uint index);
  2983. uint16 GetLength() const { return length; }
  2984. void SetLength(uint16 len) { this->length = len; }
  2985. bool GetStrictMode() const { return strictMode; }
  2986. void SetStrictMode(bool flag) { this->strictMode = flag; }
  2987. Field(void*)* GetDataAddress() { return this->scopes; }
  2988. static uint32 GetOffsetOfStrictMode() { return offsetof(FrameDisplay, strictMode); }
  2989. static uint32 GetOffsetOfLength() { return offsetof(FrameDisplay, length); }
  2990. static uint32 GetOffsetOfScopes() { return offsetof(FrameDisplay, scopes); }
  2991. static ScopeType GetScopeType(void* scope);
  2992. private:
  2993. Field(bool) tag; // Tag it so that the NativeCodeGenerator::IsValidVar would not think this is var
  2994. Field(bool) strictMode;
  2995. Field(uint16) length;
  2996. #if defined(TARGET_64)
  2997. Field(uint32) unused;
  2998. #endif
  2999. Field(void*) scopes[];
  3000. };
  3001. #pragma region Function Body helper classes
  3002. #pragma region Debugging related source classes
  3003. // Contains only the beginning part of the statement. This will mainly used in SmallSpanSequence which will further be compressed
  3004. // and stored in the buffer
  3005. struct StatementData
  3006. {
  3007. StatementData()
  3008. : sourceBegin(0),
  3009. bytecodeBegin(0)
  3010. {
  3011. }
  3012. int sourceBegin;
  3013. int bytecodeBegin;
  3014. };
  3015. struct StatementLocation
  3016. {
  3017. Js::FunctionBody* function;
  3018. regex::Interval statement;
  3019. regex::Interval bytecodeSpan;
  3020. };
  3021. // Small span in the Statement buffer of the SmallSpanSequence
  3022. struct SmallSpan
  3023. {
  3024. ushort sourceBegin;
  3025. ushort bytecodeBegin;
  3026. SmallSpan(uint32 val)
  3027. {
  3028. sourceBegin = (ushort)(val >> 16);
  3029. bytecodeBegin = (ushort)(val & 0x0000FFFF);
  3030. }
  3031. operator unsigned int()
  3032. {
  3033. return (uint32)sourceBegin << 16 | bytecodeBegin;
  3034. }
  3035. };
  3036. // Iterator which contains the state at particular index. These values will used when fetching next item from
  3037. // SmallSpanSequence
  3038. class SmallSpanSequenceIter
  3039. {
  3040. friend class SmallSpanSequence;
  3041. public:
  3042. SmallSpanSequenceIter()
  3043. : accumulatedIndex(-1),
  3044. accumulatedSourceBegin(0),
  3045. accumulatedBytecodeBegin(0),
  3046. indexOfActualOffset(0)
  3047. {
  3048. }
  3049. // Below are used for fast access when the last access happened nearby.
  3050. // so the actual index would be accumulatedIndex / 2 + (remainder for which byte).
  3051. int accumulatedIndex;
  3052. int accumulatedSourceBegin;
  3053. int accumulatedBytecodeBegin;
  3054. int indexOfActualOffset;
  3055. };
  3056. struct ThrowMapEntry
  3057. {
  3058. uint32 nativeBufferOffset;
  3059. uint32 statementIndex;
  3060. };
  3061. // This class compacts the range of the statement to BYTEs instead of ints.
  3062. // Instead of having start and end as int32s we will have them stored in bytes, and they will be
  3063. // treated as start offset and end offset.
  3064. // For simplicity, this class should be heap allocated, since it can be allocated from either the background
  3065. // or main thread.
  3066. class SmallSpanSequence
  3067. {
  3068. private:
  3069. BOOL GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data);
  3070. ushort GetDiff(int current, int prev);
  3071. public:
  3072. // Each item in the list contains two set of begins (one for bytecode and for sourcespan).
  3073. // The allowed valued for source and bytecode span is in between SHORT_MAX - 1 to SHORT_MIN (inclusive).
  3074. // otherwise its a miss
  3075. JsUtil::GrowingUint32HeapArray * pStatementBuffer;
  3076. // Contains list of values which are missed in StatementBuffer.
  3077. JsUtil::GrowingUint32HeapArray * pActualOffsetList;
  3078. // The first value of the sequence
  3079. int baseValue;
  3080. SmallSpanSequence();
  3081. ~SmallSpanSequence()
  3082. {
  3083. Cleanup();
  3084. }
  3085. void Cleanup()
  3086. {
  3087. if (pStatementBuffer != nullptr)
  3088. {
  3089. HeapDelete(pStatementBuffer);
  3090. pStatementBuffer = nullptr;
  3091. }
  3092. if (pActualOffsetList != nullptr)
  3093. {
  3094. HeapDelete(pActualOffsetList);
  3095. pActualOffsetList = nullptr;
  3096. }
  3097. }
  3098. // Trys to match passed bytecode in the statement, and returns the statement which includes that.
  3099. BOOL GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data);
  3100. // Record the statement data in the statement buffer in the compressed manner.
  3101. BOOL RecordARange(SmallSpanSequenceIter &iter, StatementData * data);
  3102. // Reset the accumulator's state and value.
  3103. void Reset(SmallSpanSequenceIter &iter);
  3104. uint32 Count() const { return pStatementBuffer ? pStatementBuffer->Count() : 0; }
  3105. BOOL Item(int index, SmallSpanSequenceIter &iter, StatementData &data);
  3106. // Below function will not change any state, so it will not alter accumulated index and value
  3107. BOOL Seek(int index, StatementData & data);
  3108. };
  3109. #pragma endregion
  3110. // This container represent the property ids for the locals which are placed at direct slot
  3111. // and list of formals args if user has not used the arguments object in the script for the current function
  3112. struct PropertyIdOnRegSlotsContainer
  3113. {
  3114. Field(PropertyId *) propertyIdsForRegSlots;
  3115. Field(uint) length;
  3116. // This keeps the upper bound of register slots for the formals. While emitting locals in the body we skip
  3117. // the properties that are below this limit.
  3118. Field(RegSlot) formalsUpperBound;
  3119. Field(PropertyIdArray *) propertyIdsForFormalArgs;
  3120. PropertyIdOnRegSlotsContainer();
  3121. static PropertyIdOnRegSlotsContainer * New(Recycler * recycler);
  3122. void CreateRegSlotsArray(Recycler * recycler, uint _length);
  3123. void SetFormalArgs(PropertyIdArray * formalArgs);
  3124. // Helper methods
  3125. void Insert(RegSlot reg, PropertyId propId);
  3126. void FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot);
  3127. // Whether reg belongs to non-temp locals
  3128. bool IsRegSlotFormal(RegSlot reg);
  3129. };
  3130. // Flags for the DebuggerScopeProperty object.
  3131. typedef int DebuggerScopePropertyFlags;
  3132. const int DebuggerScopePropertyFlags_None = 0x000000000;
  3133. const int DebuggerScopePropertyFlags_Const = 0x000000001;
  3134. const int DebuggerScopePropertyFlags_CatchObject = 0x000000002;
  3135. const int DebuggerScopePropertyFlags_WithObject = 0x000000004;
  3136. const int DebuggerScopePropertyFlags_ForInOrOfCollection = 0x000000008;
  3137. const int DebuggerScopePropertyFlags_HasDuplicateInBody = 0x000000016;
  3138. // Used to store local property info for with/catch objects, lets, or consts
  3139. // that are needed for the debugger.
  3140. class DebuggerScopeProperty
  3141. {
  3142. public:
  3143. Js::PropertyId propId; // The property ID of the scope variable.
  3144. RegSlot location; // Contains the location of the scope variable (regslot, slotarray, direct).
  3145. int byteCodeInitializationOffset; // The byte code offset used when comparing let/const variables for dead zone exclusion debugger side.
  3146. DebuggerScopePropertyFlags flags; // Flags for the property.
  3147. bool IsConst() const { return (flags & DebuggerScopePropertyFlags_Const) != 0; }
  3148. bool IsCatchObject() const { return (flags & DebuggerScopePropertyFlags_CatchObject) != 0; }
  3149. bool IsWithObject() const { return (flags & DebuggerScopePropertyFlags_WithObject) != 0; }
  3150. bool IsForInOrForOfCollectionScope() const { return (flags & DebuggerScopePropertyFlags_ForInOrOfCollection) != 0; }
  3151. public:
  3152. // Determines if the current property is in a dead zone. Note that the property makes
  3153. // no assumptions about what scope it's in, that is determined by DebuggerScope.
  3154. // byteCodeOffset - The current offset in bytecode that the debugger is at.
  3155. bool IsInDeadZone(int byteCodeOffset) const
  3156. {
  3157. if (IsForInOrForOfCollectionScope())
  3158. {
  3159. // These are let/const loop variables of a for-in or for-of loop
  3160. // in the scope for the collection expression. They are always
  3161. // in TDZ in this scope, never initialized by the bytecode.
  3162. return true;
  3163. }
  3164. if (this->byteCodeInitializationOffset == Constants::InvalidByteCodeOffset && !(IsCatchObject() || IsWithObject()))
  3165. {
  3166. AssertMsg(false, "Debug let/const property never had its initialization point updated. This indicates that a Ld or St operation in ByteCodeGenerator was missed that needs to have DebuggerScope::UpdatePropertyInitializationOffset() added to it.");
  3167. return false;
  3168. }
  3169. return byteCodeOffset < this->byteCodeInitializationOffset;
  3170. }
  3171. };
  3172. // Used to track with, catch, and block scopes for the debugger to determine context.
  3173. class DebuggerScope
  3174. {
  3175. protected:
  3176. DEFINE_VTABLE_CTOR_NOBASE(DebuggerScope);
  3177. public:
  3178. typedef JsUtil::List<DebuggerScopeProperty> DebuggerScopePropertyList;
  3179. DebuggerScope(Recycler* recycler, DiagExtraScopesType scopeType, RegSlot scopeLocation, int rangeBegin)
  3180. : scopeType(scopeType),
  3181. scopeProperties(nullptr),
  3182. parentScope(nullptr),
  3183. siblingScope(nullptr),
  3184. scopeLocation(scopeLocation),
  3185. recycler(recycler)
  3186. {
  3187. this->range.begin = rangeBegin;
  3188. this->range.end = -1;
  3189. }
  3190. virtual ~DebuggerScope() {}
  3191. static bool Is(void* ptr);
  3192. DebuggerScope * GetSiblingScope(RegSlot location, FunctionBody *functionBody);
  3193. void AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags);
  3194. bool GetPropertyIndex(Js::PropertyId propertyId, int& i);
  3195. bool HasProperty(Js::PropertyId propertyId);
  3196. bool IsOffsetInScope(int offset) const;
  3197. bool Contains(Js::PropertyId propertyId, RegSlot location) const;
  3198. bool IsBlockScope() const;
  3199. bool IsBlockObjectScope() const
  3200. {
  3201. return this->scopeType == Js::DiagBlockScopeInObject;
  3202. }
  3203. bool IsCatchScope() const;
  3204. bool IsWithScope() const;
  3205. bool IsSlotScope() const;
  3206. bool IsParamScope() const;
  3207. bool HasProperties() const;
  3208. bool IsAncestorOf(const DebuggerScope* potentialChildScope);
  3209. bool AreAllPropertiesInDeadZone(int byteCodeOffset) const;
  3210. RegSlot GetLocation() const { Assert(IsOwnScope()); return scopeLocation; }
  3211. bool IsOwnScope() const { return scopeLocation != Js::Constants::NoRegister; }
  3212. bool TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const;
  3213. bool TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const;
  3214. bool UpdatePropertyInitializationOffset(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3215. void UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  3216. void UpdatePropertiesInForInOrOfCollectionScope();
  3217. void SetParentScope(DebuggerScope* parentScope) { this->parentScope = parentScope; }
  3218. DebuggerScope* GetParentScope() const { return parentScope; }
  3219. DebuggerScope* FindCommonAncestor(DebuggerScope* debuggerScope);
  3220. int GetEnd() const { return range.end; }
  3221. int GetStart() const { return range.begin; }
  3222. void SetScopeLocation(RegSlot scopeLocation) { this->scopeLocation = scopeLocation; }
  3223. void SetBegin(int begin);
  3224. void SetEnd(int end);
  3225. #if DBG
  3226. void Dump();
  3227. PCWSTR GetDebuggerScopeTypeString(DiagExtraScopesType scopeType);
  3228. #endif
  3229. #if ENABLE_TTD
  3230. Js::PropertyId GetPropertyIdForSlotIndex_TTD(uint32 slotIndex) const;
  3231. #endif
  3232. public:
  3233. // The list of scope properties in this scope object.
  3234. // For with scope: Has 1 property that represents the scoped object.
  3235. // For catch scope: Has 1 property that represents the exception object.
  3236. // For block scope: Has 0-n properties that represent let/const variables in that scope.
  3237. Field(DebuggerScopePropertyList*) scopeProperties;
  3238. Field(DiagExtraScopesType) scopeType; // The type of scope being represented (With, Catch, or Block scope).
  3239. Field(DebuggerScope*) siblingScope; // Valid only when current scope is slot/activationobject and symbols are on direct regslot
  3240. static const int InvalidScopeIndex = -1;
  3241. private:
  3242. int GetScopeDepth() const;
  3243. bool UpdatePropertyInitializationOffsetInternal(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3244. void EnsurePropertyListIsAllocated();
  3245. private:
  3246. FieldNoBarrier(Recycler*) recycler;
  3247. Field(DebuggerScope*) parentScope;
  3248. Field(regex::Interval) range; // The start and end byte code writer offsets used when comparing where the debugger is currently stopped at (breakpoint location).
  3249. Field(RegSlot) scopeLocation;
  3250. };
  3251. class ScopeObjectChain
  3252. {
  3253. public:
  3254. typedef JsUtil::List<DebuggerScope*> ScopeObjectChainList;
  3255. ScopeObjectChain(Recycler* recycler)
  3256. : pScopeChain(nullptr)
  3257. {
  3258. pScopeChain = RecyclerNew(recycler, ScopeObjectChainList, recycler);
  3259. }
  3260. // This function will return DebuggerScopeProperty when the property is found and correctly in the range.
  3261. // If the property is found, but the scope is not in the range, it will return false, but the out param (isPropertyInDebuggerScope) will set to true,
  3262. // and isConst will be updated.
  3263. // If the property is not found at all, it will return false, and isPropertyInDebuggerScope will be false.
  3264. bool TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone);
  3265. // List of all Scope Objects in a function. Scopes are added to this list as when they are created in bytecode gen part.
  3266. Field(ScopeObjectChainList*) pScopeChain;
  3267. };
  3268. #pragma endregion
  3269. } // namespace Js