FunctionBody.h 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873
  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. uint PrintableStartOffset() const;
  1383. ULONG GetLineNumber() const;
  1384. ULONG GetColumnNumber() const;
  1385. template <class T>
  1386. LPCWSTR GetSourceName(const T& sourceContextInfo) const;
  1387. template <class T>
  1388. static LPCWSTR GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction);
  1389. LPCWSTR GetSourceName() const;
  1390. ULONG GetRelativeLineNumber() const { return m_lineNumber; }
  1391. ULONG GetRelativeColumnNumber() const { return m_columnNumber; }
  1392. uint GetSourceIndex() const;
  1393. LPCUTF8 GetSource(const char16* reason = nullptr) const;
  1394. LPCUTF8 GetToStringSource(const char16* reason = nullptr) const;
  1395. charcount_t LengthInChars() const { return m_cchLength; }
  1396. charcount_t StartInDocument() const;
  1397. bool IsEval() const { return m_isEval; }
  1398. bool IsDynamicFunction() const;
  1399. bool GetDontInline() { return m_dontInline; }
  1400. void SetDontInline(bool is) { m_dontInline = is; }
  1401. LPCUTF8 GetStartOfDocument(const char16* reason = nullptr) const;
  1402. bool IsReparsed() const { return m_reparsed; }
  1403. void SetReparsed(bool set) { m_reparsed = set; }
  1404. bool IsMethod() const { return m_isMethod; }
  1405. void SetIsMethod(bool set) { m_isMethod = set; }
  1406. #ifdef NTBUILD
  1407. bool GetExternalDisplaySourceName(BSTR* sourceName);
  1408. #endif
  1409. void CleanupToReparse();
  1410. void CleanupToReparseHelper();
  1411. bool EndsAfter(size_t offset) const;
  1412. void SetDoBackendArgumentsOptimization(bool set)
  1413. {
  1414. m_doBackendArgumentsOptimization = set;
  1415. }
  1416. bool GetDoBackendArgumentsOptimization()
  1417. {
  1418. return m_doBackendArgumentsOptimization;
  1419. }
  1420. void SetDoScopeObjectCreation(bool set)
  1421. {
  1422. m_doScopeObjectCreation = set;
  1423. }
  1424. bool GetDoScopeObjectCreation()
  1425. {
  1426. return m_doScopeObjectCreation;
  1427. }
  1428. void SetUsesArgumentsObject(bool set)
  1429. {
  1430. if (!m_usesArgumentsObject)
  1431. {
  1432. m_usesArgumentsObject = set;
  1433. }
  1434. }
  1435. bool GetUsesArgumentsObject()
  1436. {
  1437. return m_usesArgumentsObject;
  1438. }
  1439. bool IsFunctionParsed()
  1440. {
  1441. return !IsDeferredParseFunction() || m_hasBeenParsed;
  1442. }
  1443. void SetFunctionParsed(bool hasBeenParsed)
  1444. {
  1445. m_hasBeenParsed = hasBeenParsed;
  1446. }
  1447. void SetSourceInfo(uint sourceIndex, ParseNodeFnc * node, bool isEval, bool isDynamicFunction);
  1448. void SetSourceInfo(uint sourceIndex);
  1449. void Copy(ParseableFunctionInfo * other);
  1450. void Copy(FunctionBody* other);
  1451. void CopyNestedArray(ParseableFunctionInfo * other);
  1452. const char16* GetExternalDisplayName() const;
  1453. JavascriptString* GetExternalDisplayNameObject(ScriptContext* scriptContext) const;
  1454. //
  1455. // Algorithm to retrieve a function body's external display name. Template supports both
  1456. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1457. //
  1458. template <class T>
  1459. static const char16* GetExternalDisplayName(const T* funcBody)
  1460. {
  1461. Assert(funcBody != nullptr);
  1462. Assert(funcBody->GetDisplayName() != nullptr);
  1463. return funcBody->GetDisplayName();
  1464. }
  1465. virtual const char16* GetDisplayName() const override;
  1466. void SetDisplayName(const char16* displayName);
  1467. virtual void SetDisplayName(const char16* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1468. virtual void Finalize(bool isShutdown) override;
  1469. JavascriptString * GetCachedSourceString();
  1470. void SetCachedSourceString(JavascriptString * sourceString);
  1471. FunctionInfoArray GetNestedFuncArray();
  1472. FunctionInfo* GetNestedFunc(uint index);
  1473. FunctionInfoPtrPtr GetNestedFuncReference(uint index);
  1474. FunctionProxy* GetNestedFunctionProxy(uint index);
  1475. ParseableFunctionInfo* GetNestedFunctionForExecution(uint index);
  1476. void SetNestedFunc(FunctionInfo* nestedFunc, uint index, uint32 flags);
  1477. void BuildDeferredStubs(ParseNodeFnc* pnodeFnc);
  1478. DeferredFunctionStub *GetDeferredStubs() const { return this->GetAuxPtr<AuxPointerType::DeferredStubs>(); }
  1479. void SetDeferredStubs(DeferredFunctionStub *stub) { this->SetAuxPtr<AuxPointerType::DeferredStubs>(stub); }
  1480. void RegisterFuncToDiag(ScriptContext * scriptContext, char16 const * pszTitle);
  1481. bool IsES6ModuleCode() const;
  1482. private:
  1483. RecyclerWeakReference<JavascriptString> * GetCachedSourceStringWeakRef();
  1484. void SetCachedSourceStringWeakRef(RecyclerWeakReference<JavascriptString> * weakRef);
  1485. protected:
  1486. static HRESULT MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se);
  1487. void SetFlags(bool does, FunctionBodyFlags newFlags)
  1488. {
  1489. if (does)
  1490. {
  1491. flags = (FunctionBodyFlags)(flags | newFlags);
  1492. }
  1493. else
  1494. {
  1495. flags = (FunctionBodyFlags)(flags & ~newFlags);
  1496. }
  1497. }
  1498. FieldWithBarrier(bool) m_tag21 : 1;
  1499. FieldWithBarrier(bool) m_hasBeenParsed : 1; // Has function body been parsed- true for actual function bodies, false for deferparse
  1500. FieldWithBarrier(bool) m_isDeclaration : 1;
  1501. FieldWithBarrier(bool) m_isAccessor : 1; // Function is a property getter or setter
  1502. FieldWithBarrier(bool) m_isStaticNameFunction : 1;
  1503. FieldWithBarrier(bool) m_isNamedFunctionExpression : 1;
  1504. FieldWithBarrier(bool) m_isNameIdentifierRef : 1;
  1505. FieldWithBarrier(bool) m_isClassMember : 1;
  1506. // 8 bits from last tag
  1507. FieldWithBarrier(bool) m_isStrictMode : 1;
  1508. FieldWithBarrier(bool) m_isAsmjsMode : 1;
  1509. FieldWithBarrier(bool) m_isAsmJsFunction : 1;
  1510. FieldWithBarrier(bool) m_isWasmFunction : 1;
  1511. FieldWithBarrier(bool) m_isGlobalFunc : 1;
  1512. FieldWithBarrier(bool) m_doBackendArgumentsOptimization : 1;
  1513. FieldWithBarrier(bool) m_doScopeObjectCreation : 1;
  1514. FieldWithBarrier(bool) m_usesArgumentsObject : 1;
  1515. // 16 bits from last tag
  1516. FieldWithBarrier(bool) m_isEval : 1; // Source code is in 'eval'
  1517. FieldWithBarrier(bool) m_isDynamicFunction : 1; // Source code is in 'Function'
  1518. FieldWithBarrier(bool) m_hasImplicitArgIns : 1;
  1519. FieldWithBarrier(bool) m_dontInline : 1; // Used by the JIT's inliner
  1520. FieldWithBarrier(bool) m_reparsed : 1; // Indicates if the function has been reparsed for debug attach/detach scenario.
  1521. FieldWithBarrier(bool) m_isMethod : 1; // Function is an object literal method
  1522. #if DBG
  1523. FieldWithBarrier(bool) m_wasEverAsmjsMode : 1; // has m_isAsmjsMode ever been true
  1524. #endif
  1525. // This field is not required for deferred parsing but because our thunks can't handle offsets > 128 bytes
  1526. // yet, leaving this here for now. We can look at optimizing the function info and function proxy structures some
  1527. // more and also fix our thunks to handle 8 bit offsets
  1528. FieldWithBarrier(bool) m_utf8SourceHasBeenSet : 1; // start of UTF8-encoded source
  1529. #define DEFINE_PARSEABLE_FUNCTION_INFO_FIELDS 1
  1530. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1531. #define CURRENT_ACCESS_MODIFIER protected:
  1532. #include "SerializableFunctionFields.h"
  1533. FieldWithBarrier(uint) m_sourceIndex; // index into the scriptContext's list of saved sources
  1534. #if DYNAMIC_INTERPRETER_THUNK
  1535. FieldNoBarrier(void*) m_dynamicInterpreterThunk; // Unique 'thunk' for every interpreted function - used for ETW symbol decoding.
  1536. #endif
  1537. FieldWithBarrier(uint) m_cbStartOffset; // pUtf8Source is this many bytes from the start of the scriptContext's source buffer.
  1538. // This is generally the same as m_cchStartOffset unless the buffer has a BOM or other non-ascii characters
  1539. FieldWithBarrier(uint) m_cbStartPrintOffset; // pUtf8Source is this many bytes from the start of the toString-relevant part of the scriptContext's source buffer.
  1540. FieldWithBarrier(ULONG) m_lineNumber;
  1541. FieldWithBarrier(ULONG) m_columnNumber;
  1542. FieldWithBarrier(const char16*) m_displayName; // Optional name
  1543. FieldWithBarrier(uint) m_displayNameLength;
  1544. FieldWithBarrier(NestedArray*) nestedArray;
  1545. public:
  1546. #if DBG
  1547. FieldWithBarrier(Js::LocalFunctionId) deferredParseNextFunctionId;
  1548. #endif
  1549. #if DBG
  1550. FieldWithBarrier(UINT) scopeObjectSize; // If the scope is an activation object - its size
  1551. #endif
  1552. };
  1553. //
  1554. // Algorithm to retrieve a function body's source name (url). Template supports both
  1555. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1556. //
  1557. template <class T>
  1558. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo) const
  1559. {
  1560. return GetSourceName<T>(sourceContextInfo, this->m_isEval, this->m_isDynamicFunction);
  1561. }
  1562. template <class T>
  1563. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction)
  1564. {
  1565. if (sourceContextInfo->IsDynamic())
  1566. {
  1567. if (m_isEval)
  1568. {
  1569. return Constants::EvalCode;
  1570. }
  1571. else if (m_isDynamicFunction)
  1572. {
  1573. return Constants::FunctionCode;
  1574. }
  1575. else
  1576. {
  1577. return Constants::UnknownScriptCode;
  1578. }
  1579. }
  1580. else
  1581. {
  1582. return sourceContextInfo->url;
  1583. }
  1584. }
  1585. class FunctionBody : public ParseableFunctionInfo
  1586. {
  1587. DEFINE_VTABLE_CTOR_NO_REGISTER(FunctionBody, ParseableFunctionInfo);
  1588. friend class ByteCodeBufferBuilder;
  1589. friend class ByteCodeBufferReader;
  1590. #ifdef DYNAMIC_PROFILE_MUTATOR
  1591. friend class ::DynamicProfileMutator;
  1592. friend class ::DynamicProfileMutatorImpl;
  1593. #endif
  1594. friend class RemoteFunctionBody;
  1595. public:
  1596. // same as MachDouble, used in the Func.h
  1597. static const uint DIAGLOCALSLOTSIZE = 8;
  1598. enum class CounterFields : uint8
  1599. {
  1600. VarCount = 0,
  1601. ConstantCount = 1,
  1602. OutParamMaxDepth = 2,
  1603. ByteCodeCount = 3,
  1604. ByteCodeWithoutLDACount = 4,
  1605. ByteCodeInLoopCount = 5,
  1606. LoopCount = 6,
  1607. ForInLoopDepth = 7,
  1608. ProfiledForInLoopCount = 8,
  1609. InlineCacheCount = 9,
  1610. RootObjectLoadInlineCacheStart = 10,
  1611. RootObjectLoadMethodInlineCacheStart = 11,
  1612. RootObjectStoreInlineCacheStart = 12,
  1613. IsInstInlineCacheCount = 13,
  1614. ReferencedPropertyIdCount = 14,
  1615. ObjLiteralCount = 15,
  1616. LiteralRegexCount = 16,
  1617. InnerScopeCount = 17,
  1618. // Following counters uses ((uint32)-1) as default value
  1619. LocalClosureRegister = 18,
  1620. ParamClosureRegister = 19,
  1621. LocalFrameDisplayRegister = 20,
  1622. EnvRegister = 21,
  1623. ThisRegisterForEventHandler = 22,
  1624. FirstInnerScopeRegister = 23,
  1625. FuncExprScopeRegister = 24,
  1626. FirstTmpRegister = 25,
  1627. Max
  1628. };
  1629. private:
  1630. typedef CompactCounters<FunctionBody> CounterT;
  1631. FieldWithBarrier(CounterT) counters;
  1632. friend CounterT;
  1633. public:
  1634. uint32 GetCountField(FunctionBody::CounterFields fieldEnum) const;
  1635. uint32 SetCountField(FunctionBody::CounterFields fieldEnum, uint32 val);
  1636. uint32 IncreaseCountField(FunctionBody::CounterFields fieldEnum);
  1637. #if DBG
  1638. void LockDownCounters() { counters.isLockedDown = true; };
  1639. void UnlockCounters() { counters.isLockedDown = false; };
  1640. void SetIsClosing() { counters.isClosing = true; };
  1641. #endif
  1642. struct StatementMap
  1643. {
  1644. StatementMap() : isSubexpression(false) {}
  1645. static StatementMap * New(Recycler* recycler)
  1646. {
  1647. return RecyclerNew(recycler, StatementMap);
  1648. }
  1649. FieldWithBarrier(regex::Interval) sourceSpan;
  1650. FieldWithBarrier(regex::Interval) byteCodeSpan;
  1651. FieldWithBarrier(bool) isSubexpression;
  1652. };
  1653. // The type of StatementAdjustmentRecord.
  1654. // A bitmask that can be OR'ed of multiple values of the enum.
  1655. enum StatementAdjustmentType : ushort
  1656. {
  1657. SAT_None = 0,
  1658. // Specifies an adjustment for next statement when going from current to next.
  1659. // Used for transitioning from current stmt to next during normal control-flow,
  1660. // such as offset of Br after if-block when there is else block present,
  1661. // when throw happens inside if and we ignore exceptions (next statement in the list
  1662. // would be 'else' but we need to pass flow control to Br target rather than entering 'else').
  1663. SAT_FromCurrentToNext = 0x01,
  1664. // Specifies an adjustment for beginning of next statement.
  1665. // If there is adjustment record, the statement following it starts at specified offset and not at offset specified in statementMap.
  1666. // Used for set next statement from arbitrary location.
  1667. SAT_NextStatementStart = 0x02,
  1668. SAT_All = SAT_FromCurrentToNext | SAT_NextStatementStart
  1669. };
  1670. class StatementAdjustmentRecord
  1671. {
  1672. uint m_byteCodeOffset;
  1673. StatementAdjustmentType m_adjustmentType;
  1674. public:
  1675. StatementAdjustmentRecord();
  1676. StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset);
  1677. StatementAdjustmentRecord(const StatementAdjustmentRecord& other);
  1678. uint GetByteCodeOffset();
  1679. StatementAdjustmentType GetAdjustmentType();
  1680. };
  1681. // Offset and entry/exit of a block that must be processed in new interpreter frame rather than current.
  1682. // Used for try and catch blocks.
  1683. class CrossFrameEntryExitRecord
  1684. {
  1685. uint m_byteCodeOffset;
  1686. // true means enter, false means exit.
  1687. bool m_isEnterBlock;
  1688. public:
  1689. CrossFrameEntryExitRecord();
  1690. CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  1691. CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other);
  1692. uint GetByteCodeOffset() const;
  1693. bool GetIsEnterBlock();
  1694. };
  1695. typedef JsUtil::List<Js::FunctionBody::StatementMap*, ArenaAllocator> ArenaStatementMapList;
  1696. typedef JsUtil::List<Js::FunctionBody::StatementMap*> StatementMapList;
  1697. // Note: isLeaf = true template param below means that recycler should not be used to dispose the items.
  1698. typedef JsUtil::List<StatementAdjustmentRecord, Recycler, /* isLeaf = */ true> StatementAdjustmentRecordList;
  1699. typedef JsUtil::List<CrossFrameEntryExitRecord, Recycler, /* isLeaf = */ true> CrossFrameEntryExitRecordList;
  1700. // Contains recorded at bytecode generation time information about statements and try-catch blocks.
  1701. // Used by debugger.
  1702. struct AuxStatementData
  1703. {
  1704. // Contains statement adjustment data:
  1705. // For given bytecode, following statement needs an adjustment, see StatementAdjustmentType for details.
  1706. Field(StatementAdjustmentRecordList*) m_statementAdjustmentRecords;
  1707. // Contain data about entry/exit of blocks that cause processing in different interpreter stack frame, such as try or catch.
  1708. Field(CrossFrameEntryExitRecordList*) m_crossFrameBlockEntryExisRecords;
  1709. AuxStatementData();
  1710. };
  1711. class SourceInfo
  1712. {
  1713. friend class RemoteFunctionBody;
  1714. friend class ByteCodeBufferReader;
  1715. friend class ByteCodeBufferBuilder;
  1716. public:
  1717. FieldNoBarrier(SmallSpanSequence*) pSpanSequence;
  1718. FieldWithBarrier(RegSlot) frameDisplayRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1719. FieldWithBarrier(RegSlot) objectRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1720. FieldWithBarrier(ScopeObjectChain*) pScopeObjectChain;
  1721. FieldWithBarrier(ByteBlock*) m_probeBackingBlock; // NULL if no Probes, otherwise a copy of the unmodified the byte-codeblock //Delay
  1722. FieldWithBarrier(int32) m_probeCount; // The number of installed probes (such as breakpoints).
  1723. // List of bytecode offset for the Branch bytecode.
  1724. FieldWithBarrier(AuxStatementData*) m_auxStatementData;
  1725. SourceInfo():
  1726. frameDisplayRegister(0),
  1727. objectRegister(0),
  1728. pScopeObjectChain(nullptr),
  1729. m_probeBackingBlock(nullptr),
  1730. m_probeCount(0),
  1731. m_auxStatementData(nullptr),
  1732. pSpanSequence(nullptr)
  1733. {
  1734. }
  1735. };
  1736. private:
  1737. FieldWithBarrier(ByteBlock*) byteCodeBlock; // Function byte-code for script functions
  1738. FieldWithBarrier(FunctionEntryPointList*) entryPoints;
  1739. FieldWithBarrier(Field(Var)*) m_constTable;
  1740. FieldWithBarrier(void**) inlineCaches;
  1741. FieldWithBarrier(InlineCachePointerArray<PolymorphicInlineCache>) polymorphicInlineCaches; // Contains the latest polymorphic inline caches
  1742. FieldWithBarrier(PropertyId*) cacheIdToPropertyIdMap;
  1743. #if DBG
  1744. #define InlineCacheTypeNone 0x00
  1745. #define InlineCacheTypeInlineCache 0x01
  1746. #define InlineCacheTypeIsInst 0x02
  1747. FieldWithBarrier(byte*) m_inlineCacheTypes;
  1748. #endif
  1749. public:
  1750. PropertyId * GetCacheIdToPropertyIdMap()
  1751. {
  1752. return cacheIdToPropertyIdMap;
  1753. }
  1754. static DWORD GetAsmJsTotalLoopCountOffset() { return offsetof(FunctionBody, m_asmJsTotalLoopCount); }
  1755. #if DBG
  1756. FieldWithBarrier(int) m_DEBUG_executionCount; // Count of outstanding on InterpreterStackFrame
  1757. FieldWithBarrier(bool) m_nativeEntryPointIsInterpreterThunk; // NativeEntry entry point is in fact InterpreterThunk.
  1758. // Set by bgjit in OutOfMemory scenario during codegen.
  1759. #endif
  1760. //#if ENABLE_DEBUG_CONFIG_OPTIONS //TODO: need this?
  1761. FieldWithBarrier(uint) regAllocStoreCount;
  1762. FieldWithBarrier(uint) regAllocLoadCount;
  1763. FieldWithBarrier(uint) callCountStats;
  1764. //#endif
  1765. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1766. //
  1767. // If you add compile-time attributes to this set, be sure to add them to the attributes that are
  1768. // copied in FunctionBody::Clone
  1769. //
  1770. FieldWithBarrier(SourceInfo) m_sourceInfo; // position of the source
  1771. // Data needed by profiler:
  1772. FieldWithBarrier(uint) m_uScriptId; // Delay //Script Block it belongs to. This is function no. of the global function created by engine for each block
  1773. #if DBG
  1774. FieldWithBarrier(int) m_iProfileSession; // Script profile session the meta data of this function is reported to.
  1775. #endif // DEBUG
  1776. // R0 is reserved for the return value, R1 for the root object
  1777. static const RegSlot ReturnValueRegSlot = 0;
  1778. static const RegSlot RootObjectRegSlot = 1;
  1779. static const RegSlot FirstRegSlot = 1;
  1780. // This value be set on the stack (on a particular offset), when the frame value got changed.
  1781. static const int LocalsChangeDirtyValue = 1;
  1782. #define DEFINE_FUNCTION_BODY_FIELDS 1
  1783. #define DECLARE_TAG_FIELD(type, name, serializableType) Field(type) name
  1784. #define CURRENT_ACCESS_MODIFIER public:
  1785. #include "SerializableFunctionFields.h"
  1786. private:
  1787. FieldWithBarrier(uint) inactiveCount;
  1788. // aligned with 8
  1789. FieldWithBarrier(bool) m_tag32 : 1;
  1790. FieldWithBarrier(bool) m_nativeEntryPointUsed : 1; // Code might have been generated but not yet used.
  1791. FieldWithBarrier(bool) hasDoneLoopBodyCodeGen : 1; // Code generated for loop body, but not necessary available to execute yet.
  1792. FieldWithBarrier(bool) m_isFuncRegistered : 1;
  1793. FieldWithBarrier(bool) m_isFuncRegisteredToDiag : 1; // Mentions the function's context is registered with diagprobe.
  1794. FieldWithBarrier(bool) funcEscapes : 1;
  1795. FieldWithBarrier(bool) m_hasBailoutInstrInJittedCode : 1; // Indicates whether function has bailout instructions. Valid only if hasDoneCodeGen is true
  1796. FieldWithBarrier(bool) m_pendingLoopHeaderRelease : 1; // Indicates whether loop headers need to be released
  1797. // 8 bits from last tag
  1798. FieldWithBarrier(bool) hasExecutionDynamicProfileInfo : 1;
  1799. FieldWithBarrier(bool) cleanedUp: 1;
  1800. FieldWithBarrier(bool) sourceInfoCleanedUp: 1;
  1801. FieldWithBarrier(bool) dontRethunkAfterBailout : 1;
  1802. FieldWithBarrier(bool) disableInlineApply : 1;
  1803. FieldWithBarrier(bool) disableInlineSpread : 1;
  1804. FieldWithBarrier(bool) hasHotLoop: 1;
  1805. FieldWithBarrier(bool) wasCalledFromLoop : 1;
  1806. // 16 bits from last tag
  1807. FieldWithBarrier(bool) hasNestedLoop : 1;
  1808. FieldWithBarrier(bool) recentlyBailedOutOfJittedLoopBody : 1;
  1809. FieldWithBarrier(bool) m_firstFunctionObject: 1;
  1810. FieldWithBarrier(bool) m_inlineCachesOnFunctionObject: 1;
  1811. // 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
  1812. // the state of the script context, or on other factors like whether it was defer parsed or not.
  1813. FieldWithBarrier(bool) m_hasSetIsObject : 1;
  1814. // 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.
  1815. // 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.
  1816. FieldWithBarrier(bool) m_hasAllNonLocalReferenced : 1;
  1817. FieldWithBarrier(bool) m_hasFunExprNameReference : 1;
  1818. FieldWithBarrier(bool) m_ChildCallsEval : 1;
  1819. // 24 bits from last tag
  1820. FieldWithBarrier(bool) m_CallsEval : 1;
  1821. FieldWithBarrier(bool) m_hasReferenceableBuiltInArguments : 1;
  1822. FieldWithBarrier(bool) m_isParamAndBodyScopeMerged : 1;
  1823. // Used in the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple times for each child function.
  1824. FieldWithBarrier(bool) m_hasDoneAllNonLocalReferenced : 1;
  1825. // Used by the script profiler, once the function compiled is sent this will be set to true.
  1826. FieldWithBarrier(bool) m_hasFunctionCompiledSent : 1;
  1827. FieldWithBarrier(bool) m_isFromNativeCodeModule : 1;
  1828. FieldWithBarrier(bool) m_isPartialDeserializedFunction : 1;
  1829. FieldWithBarrier(bool) m_isAsmJsScheduledForFullJIT : 1;
  1830. // 32 bits from last tag
  1831. FieldWithBarrier(bool) m_tag33 : 1;
  1832. FieldWithBarrier(bool) m_hasLocalClosureRegister : 1;
  1833. FieldWithBarrier(bool) m_hasParamClosureRegister : 1;
  1834. FieldWithBarrier(bool) m_hasLocalFrameDisplayRegister : 1;
  1835. FieldWithBarrier(bool) m_hasEnvRegister : 1;
  1836. FieldWithBarrier(bool) m_hasThisRegisterForEventHandler : 1;
  1837. FieldWithBarrier(bool) m_hasFirstInnerScopeRegister : 1;
  1838. FieldWithBarrier(bool) m_hasFuncExprScopeRegister : 1;
  1839. // 8 bits from last tag
  1840. FieldWithBarrier(bool) m_hasFirstTmpRegister : 1;
  1841. FieldWithBarrier(bool) m_hasActiveReference : 1;
  1842. FieldWithBarrier(bool) m_isJsBuiltInForceInline : 1;
  1843. #if DBG
  1844. FieldWithBarrier(bool) m_isSerialized : 1;
  1845. #endif
  1846. #ifdef PERF_COUNTERS
  1847. FieldWithBarrier(bool) m_isDeserializedFunction : 1;
  1848. #endif
  1849. #if DBG
  1850. // Indicates that nested functions can be allocated on the stack (but may not be)
  1851. FieldWithBarrier(bool) m_canDoStackNestedFunc : 1;
  1852. #endif
  1853. #ifdef IR_VIEWER
  1854. // whether IR Dump is enabled for this function (used by parseIR)
  1855. FieldWithBarrier(bool) m_isIRDumpEnabled : 1;
  1856. FieldWithBarrier(Js::DynamicObject*) m_irDumpBaseObject;
  1857. #endif /* IR_VIEWER */
  1858. FieldWithBarrier(uint8) bailOnMisingProfileCount;
  1859. FieldWithBarrier(uint8) bailOnMisingProfileRejitCount;
  1860. FieldWithBarrier(byte) inlineDepth; // Used by inlining to avoid recursively inlining functions excessively
  1861. FieldWithBarrier(FunctionExecutionStateMachine) executionState;
  1862. // Indicates how many times the function has been entered (so increases by one on each recursive call, decreases by one when we're done)
  1863. FieldWithBarrier(uint) m_depth;
  1864. FieldWithBarrier(uint32) loopInterpreterLimit;
  1865. FieldWithBarrier(uint32) debuggerScopeIndex;
  1866. FieldWithBarrier(uint32) savedPolymorphicCacheState;
  1867. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1868. //
  1869. // If you add compile-time attributes to the above set, be sure to add them to the attributes that are
  1870. // copied in FunctionBody::Clone
  1871. //
  1872. FieldNoBarrier(Js::ByteCodeCache*) byteCodeCache; // Not GC allocated so naked pointer
  1873. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1874. static bool shareInlineCaches;
  1875. #endif
  1876. FieldWithBarrier(FunctionEntryPointInfo*) defaultFunctionEntryPointInfo;
  1877. #if ENABLE_PROFILE_INFO
  1878. FieldWithBarrier(DynamicProfileInfo*) dynamicProfileInfo;
  1879. #endif
  1880. // select dynamic profile info saved off when we codegen and later
  1881. // used for rejit decisions (see bailout.cpp)
  1882. FieldWithBarrier(BYTE) savedInlinerVersion;
  1883. #if ENABLE_NATIVE_CODEGEN
  1884. FieldWithBarrier(ImplicitCallFlags) savedImplicitCallsFlags;
  1885. #endif
  1886. FunctionBody(ScriptContext* scriptContext, const char16* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount, Utf8SourceInfo* sourceInfo,
  1887. uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes, FunctionBodyFlags flags
  1888. #ifdef PERF_COUNTERS
  1889. , bool isDeserializedFunction = false
  1890. #endif
  1891. );
  1892. FunctionBody(ParseableFunctionInfo * parseableFunctionInfo);
  1893. void SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, JavascriptMethod directEntryPoint);
  1894. #if DYNAMIC_INTERPRETER_THUNK
  1895. void GenerateDynamicInterpreterThunk();
  1896. #endif
  1897. Js::JavascriptMethod GetEntryPoint(ProxyEntryPointInfo* entryPoint) const { return entryPoint->jsMethod; }
  1898. void CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo);
  1899. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1900. void DumpRegStats(FunctionBody *funcBody);
  1901. #endif
  1902. public:
  1903. FunctionBody(ByteCodeCache* cache, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext):
  1904. ParseableFunctionInfo((JavascriptMethod) nullptr, 0, (LocalFunctionId) 0, sourceInfo, scriptContext, 0, nullptr, 0, 0, FunctionInfo::Attributes::None, Flags_None)
  1905. {
  1906. // Dummy constructor- does nothing
  1907. // Must be stack allocated
  1908. // Used during deferred bytecode serialization
  1909. }
  1910. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1911. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes
  1912. , FunctionBodyFlags flags
  1913. #ifdef PERF_COUNTERS
  1914. , bool isDeserializedFunction
  1915. #endif
  1916. );
  1917. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const char16 * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1918. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, FunctionInfo::Attributes attributes
  1919. , FunctionBodyFlags flags
  1920. #ifdef PERF_COUNTERS
  1921. , bool isDeserializedFunction
  1922. #endif
  1923. );
  1924. static FunctionBody * NewFromParseableFunctionInfo(ParseableFunctionInfo * info);
  1925. FunctionEntryPointInfo * GetEntryPointInfo(int index) const;
  1926. FunctionEntryPointInfo * TryGetEntryPointInfo(int index) const;
  1927. bool DoRedeferFunction(uint inactiveThreshold) const;
  1928. void RedeferFunction();
  1929. void RedeferFunctionObjectTypes();
  1930. bool IsActiveFunction(ActiveFunctionSet * pActiveFuncs) const;
  1931. bool TestAndUpdateActiveFunctions(ActiveFunctionSet * pActiveFuncs) const;
  1932. void UpdateActiveFunctionSet(ActiveFunctionSet * pActiveFuncs, FunctionCodeGenRuntimeData *callSiteData) const;
  1933. void UpdateActiveFunctionsForOneDataSet(ActiveFunctionSet *pActiveFuncs, FunctionCodeGenRuntimeData *parentData, Field(FunctionCodeGenRuntimeData*)* dataSet, uint count) const;
  1934. uint GetInactiveCount() const { return inactiveCount; }
  1935. void SetInactiveCount(uint count) { inactiveCount = count; }
  1936. void IncrInactiveCount(uint increment);
  1937. bool InterpretedSinceCallCountCollection() const;
  1938. void CollectInterpretedCounts();
  1939. void ResetRedeferralAttributes() { this->m_hasActiveReference = false; }
  1940. Js::RootObjectBase * LoadRootObject() const;
  1941. Js::RootObjectBase * GetRootObject() const;
  1942. ByteBlock* GetAuxiliaryData() const { return this->GetAuxPtr<AuxPointerType::AuxBlock>(); }
  1943. ByteBlock* GetAuxiliaryDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::AuxBlock>(); }
  1944. void SetAuxiliaryData(ByteBlock* auxBlock) { this->SetAuxPtr<AuxPointerType::AuxBlock>(auxBlock); }
  1945. ByteBlock* GetAuxiliaryContextData()const { return this->GetAuxPtr<AuxPointerType::AuxContextBlock>(); }
  1946. ByteBlock* GetAuxiliaryContextDataWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AuxContextBlock>(); }
  1947. void SetAuxiliaryContextData(ByteBlock* auxContextBlock) { this->SetAuxPtr<AuxPointerType::AuxContextBlock>(auxContextBlock); }
  1948. void SetFormalsPropIdArray(PropertyIdArray * propIdArray);
  1949. PropertyIdArray* GetFormalsPropIdArray(bool checkForNull = true);
  1950. Var GetFormalsPropIdArrayOrNullObj();
  1951. ByteBlock* GetByteCode() const;
  1952. ByteBlock* GetOriginalByteCode(); // Returns original bytecode without probes (such as BPs).
  1953. Js::ByteCodeCache * GetByteCodeCache() const { return this->byteCodeCache; }
  1954. void SetByteCodeCache(Js::ByteCodeCache *byteCodeCache)
  1955. {
  1956. if (byteCodeCache != nullptr)
  1957. {
  1958. this->byteCodeCache = byteCodeCache;
  1959. }
  1960. }
  1961. #if DBG
  1962. void SetIsSerialized(bool serialized) { m_isSerialized = serialized; }
  1963. bool GetIsSerialized()const { return m_isSerialized; }
  1964. #endif
  1965. uint GetByteCodeCount() const { return GetCountField(CounterFields::ByteCodeCount); }
  1966. void SetByteCodeCount(uint count) { SetCountField(CounterFields::ByteCodeCount, count); }
  1967. uint GetByteCodeWithoutLDACount() const { return GetCountField(CounterFields::ByteCodeWithoutLDACount); }
  1968. void SetByteCodeWithoutLDACount(uint count) { SetCountField(CounterFields::ByteCodeWithoutLDACount, count); }
  1969. uint GetByteCodeInLoopCount() const { return GetCountField(CounterFields::ByteCodeInLoopCount); }
  1970. void SetByteCodeInLoopCount(uint count) { SetCountField(CounterFields::ByteCodeInLoopCount, count); }
  1971. uint16 GetEnvDepth() const { return m_envDepth; }
  1972. void SetEnvDepth(uint16 depth) { m_envDepth = depth; }
  1973. void SetEnvRegister(RegSlot reg);
  1974. void MapAndSetEnvRegister(RegSlot reg);
  1975. RegSlot GetEnvRegister() const;
  1976. void SetThisRegisterForEventHandler(RegSlot reg);
  1977. void MapAndSetThisRegisterForEventHandler(RegSlot reg);
  1978. RegSlot GetThisRegisterForEventHandler() const;
  1979. void SetLocalClosureRegister(RegSlot reg);
  1980. void MapAndSetLocalClosureRegister(RegSlot reg);
  1981. RegSlot GetLocalClosureRegister() const;
  1982. void SetParamClosureRegister(RegSlot reg);
  1983. void MapAndSetParamClosureRegister(RegSlot reg);
  1984. RegSlot GetParamClosureRegister() const;
  1985. void SetLocalFrameDisplayRegister(RegSlot reg);
  1986. void MapAndSetLocalFrameDisplayRegister(RegSlot reg);
  1987. RegSlot GetLocalFrameDisplayRegister() const;
  1988. void SetFirstInnerScopeRegister(RegSlot reg);
  1989. void MapAndSetFirstInnerScopeRegister(RegSlot reg);
  1990. RegSlot GetFirstInnerScopeRegister() const;
  1991. void SetFuncExprScopeRegister(RegSlot reg);
  1992. void MapAndSetFuncExprScopeRegister(RegSlot reg);
  1993. RegSlot GetFuncExprScopeRegister() const;
  1994. bool HasScopeObject() const { return hasScopeObject; }
  1995. void SetHasScopeObject(bool has) { hasScopeObject = has; }
  1996. uint GetInnerScopeCount() const { return GetCountField(CounterFields::InnerScopeCount); }
  1997. void SetInnerScopeCount(uint count) { SetCountField(CounterFields::InnerScopeCount, count); }
  1998. bool HasCachedScopePropIds() const { return hasCachedScopePropIds; }
  1999. void SetHasCachedScopePropIds(bool has) { hasCachedScopePropIds = has; }
  2000. uint32 GetInterpretedCount() const;
  2001. uint32 IncreaseInterpretedCount();
  2002. uint32 GetLoopInterpreterLimit() const { return loopInterpreterLimit; }
  2003. uint32 SetLoopInterpreterLimit(uint32 val) { return loopInterpreterLimit = val; }
  2004. // Gets the next index for tracking debugger scopes (increments the internal counter as well).
  2005. uint32 GetNextDebuggerScopeIndex() { return debuggerScopeIndex++; }
  2006. void SetDebuggerScopeIndex(uint32 index) { debuggerScopeIndex = index; }
  2007. size_t GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars);
  2008. void SetJsBuiltInForceInline() { m_isJsBuiltInForceInline = true; }
  2009. bool IsJsBuiltInForceInline() const { return m_isJsBuiltInForceInline; }
  2010. void AllocateLoopHeaders();
  2011. void ReleaseLoopHeaders();
  2012. Js::LoopHeader * GetLoopHeader(uint index) const;
  2013. Js::LoopHeader * GetLoopHeaderWithLock(uint index) const;
  2014. Js::LoopHeader * GetLoopHeaderArrayPtr() const
  2015. {
  2016. Assert(this->GetLoopHeaderArray() != nullptr);
  2017. return this->GetLoopHeaderArray();
  2018. }
  2019. #ifdef ASMJS_PLAT
  2020. void SetIsAsmJsFullJitScheduled(bool val){ m_isAsmJsScheduledForFullJIT = val; }
  2021. bool GetIsAsmJsFullJitScheduled(){ return m_isAsmJsScheduledForFullJIT; }
  2022. uint32 GetAsmJSTotalLoopCount() const
  2023. {
  2024. return m_asmJsTotalLoopCount;
  2025. }
  2026. void SetIsAsmJsFunction(bool isAsmJsFunction)
  2027. {
  2028. m_isAsmJsFunction = isAsmJsFunction;
  2029. }
  2030. #endif
  2031. const bool GetIsAsmJsFunction() const
  2032. {
  2033. return m_isAsmJsFunction;
  2034. }
  2035. #ifdef ASMJS_PLAT
  2036. bool IsHotAsmJsLoop()
  2037. {
  2038. // Negative MinTemplatizedJitLoopRunCount treats all loops as hot asm loop
  2039. if (CONFIG_FLAG(MinTemplatizedJitLoopRunCount) < 0 || m_asmJsTotalLoopCount > static_cast<uint>(CONFIG_FLAG(MinTemplatizedJitLoopRunCount)))
  2040. {
  2041. return true;
  2042. }
  2043. return false;
  2044. }
  2045. #endif
  2046. private:
  2047. void ResetLoops();
  2048. public:
  2049. static bool Is(void* ptr);
  2050. uint GetScriptId() const { return m_uScriptId; }
  2051. void* GetAddressOfScriptId() const
  2052. {
  2053. return (void*)&m_uScriptId;
  2054. }
  2055. static uint *GetJittedLoopIterationsSinceLastBailoutAddress(EntryPointInfo* info)
  2056. {
  2057. LoopEntryPointInfo* entryPoint = (LoopEntryPointInfo*)info;
  2058. return &entryPoint->jittedLoopIterationsSinceLastBailout;
  2059. }
  2060. FunctionEntryPointInfo* GetDefaultFunctionEntryPointInfo() const;
  2061. void SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint);
  2062. FunctionEntryPointInfo *GetSimpleJitEntryPointInfo() const;
  2063. void SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo);
  2064. void SetAsmJsExecutionMode();
  2065. void SetDefaultInterpreterExecutionMode();
  2066. ExecutionMode GetExecutionMode() const;
  2067. ExecutionMode GetInterpreterExecutionMode(const bool isPostBailout);
  2068. private:
  2069. bool IsInterpreterExecutionMode() const;
  2070. public:
  2071. bool TryTransitionToNextExecutionMode();
  2072. void TryTransitionToNextInterpreterExecutionMode();
  2073. void SetIsSpeculativeJitCandidate();
  2074. bool TryTransitionToJitExecutionMode();
  2075. void TransitionToSimpleJitExecutionMode();
  2076. void TransitionToFullJitExecutionMode();
  2077. void ReinitializeExecutionModeAndLimits();
  2078. private:
  2079. uint16 GetSimpleJitExecutedIterations() const;
  2080. public:
  2081. void ResetSimpleJitLimitAndCallCount();
  2082. private:
  2083. void SetSimpleJitCallCount(const uint16 simpleJitLimit) const;
  2084. void ResetSimpleJitCallCount();
  2085. public:
  2086. uint16 GetProfiledIterations() const;
  2087. public:
  2088. void OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo);
  2089. public:
  2090. void TraceExecutionMode(const char *const eventDescription = nullptr) const;
  2091. void TraceInterpreterExecutionMode() const;
  2092. private:
  2093. void DoTraceExecutionMode(const char *const eventDescription) const;
  2094. public:
  2095. bool DoSimpleJit() const;
  2096. bool DoSimpleJitWithLock() const;
  2097. bool DoSimpleJitDynamicProfile() const;
  2098. bool DoInterpreterProfile() const;
  2099. bool DoInterpreterProfileWithLock() const;
  2100. bool DoInterpreterAutoProfile() const;
  2101. public:
  2102. bool WasCalledFromLoop() const;
  2103. void SetWasCalledFromLoop();
  2104. public:
  2105. bool RecentlyBailedOutOfJittedLoopBody() const;
  2106. void SetRecentlyBailedOutOfJittedLoopBody(const bool value);
  2107. private:
  2108. static uint16 GetMinProfileIterations();
  2109. public:
  2110. static uint16 GetMinFunctionProfileIterations();
  2111. private:
  2112. static uint GetMinLoopProfileIterations(const uint loopInterpreterLimit);
  2113. public:
  2114. uint GetLoopProfileThreshold(const uint loopInterpreterLimit) const;
  2115. private:
  2116. static uint GetReducedLoopInterpretCount();
  2117. public:
  2118. uint GetLoopInterpretCount(LoopHeader* loopHeader) const;
  2119. private:
  2120. static bool DoObjectHeaderInlining();
  2121. static bool DoObjectHeaderInliningForConstructors();
  2122. public:
  2123. static bool DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity);
  2124. private:
  2125. static bool DoObjectHeaderInliningForObjectLiterals();
  2126. public:
  2127. static bool DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity);
  2128. static bool DoObjectHeaderInliningForObjectLiteral(const PropertyIdArray *const propIds);
  2129. static bool DoObjectHeaderInliningForEmptyObjects();
  2130. public:
  2131. #if DBG
  2132. int GetProfileSession() { return m_iProfileSession; }
  2133. #ifdef ENABLE_SCRIPT_DEBUGGING
  2134. Js::DebuggerMode GetDebuggerMode();
  2135. #endif
  2136. #endif
  2137. virtual void Finalize(bool isShutdown) override;
  2138. virtual void OnMark() override;
  2139. void Cleanup(bool isScriptContextClosing);
  2140. void CleanupSourceInfo(bool isScriptContextClosing);
  2141. template<bool IsScriptContextShutdown>
  2142. void CleanUpInlineCaches();
  2143. void CleanupRecyclerData(bool isRecyclerShutdown, bool doEntryPointCleanupCaptureStack);
  2144. #ifdef PERF_COUNTERS
  2145. void CleanupPerfCounter();
  2146. #endif
  2147. bool HasRejit() const
  2148. {
  2149. if(this->entryPoints)
  2150. {
  2151. return this->entryPoints->Count() > 1;
  2152. }
  2153. return false;
  2154. }
  2155. #pragma region SourceInfo Methods
  2156. void CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo);
  2157. void FinishSourceInfo();
  2158. RegSlot GetFrameDisplayRegister() const;
  2159. void SetFrameDisplayRegister(RegSlot frameDisplayRegister);
  2160. RegSlot GetObjectRegister() const;
  2161. void SetObjectRegister(RegSlot objectRegister);
  2162. bool HasObjectRegister() const { return GetObjectRegister() != 0; }
  2163. ScopeObjectChain *GetScopeObjectChain() const;
  2164. void SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain);
  2165. // fetch the Catch scope object which encloses the passed bytecode offset, returns NULL otherwise
  2166. Js::DebuggerScope * GetDiagCatchScopeObjectAt(int byteCodeOffset);
  2167. ByteBlock *GetProbeBackingBlock();
  2168. void SetProbeBackingBlock(ByteBlock* probeBackingBlock);
  2169. bool HasLineBreak() const;
  2170. bool HasLineBreak(charcount_t start, charcount_t end) const;
  2171. bool HasGeneratedFromByteCodeCache() const { return this->byteCodeCache != nullptr; }
  2172. void TrackLoad(int ichMin);
  2173. SmallSpanSequence* GetStatementMapSpanSequence() const { return m_sourceInfo.pSpanSequence; }
  2174. void RecordStatementMap(StatementMap* statementMap);
  2175. void RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data);
  2176. void RecordLoad(int ichMin, int bytecodeAfterLoad);
  2177. DebuggerScope* RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index = nullptr);
  2178. void RecordEndScopeObject(DebuggerScope* currentScope, int end);
  2179. DebuggerScope* AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  2180. bool TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope);
  2181. StatementMapList * GetStatementMaps() const { return static_cast<StatementMapList *>(this->GetAuxPtrWithLock<AuxPointerType::StatementMaps>()); }
  2182. void SetStatementMaps(StatementMapList *pStatementMaps) { this->SetAuxPtr<AuxPointerType::StatementMaps>(pStatementMaps); }
  2183. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenGetSetRuntimeData>(); }
  2184. Field(FunctionCodeGenRuntimeData*)* GetCodeGenGetSetRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenGetSetRuntimeData>(); }
  2185. void SetCodeGenGetSetRuntimeData(FunctionCodeGenRuntimeData** codeGenGetSetRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenGetSetRuntimeData>(codeGenGetSetRuntimeData); }
  2186. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenRuntimeData>(); }
  2187. Field(FunctionCodeGenRuntimeData*)* GetCodeGenRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenRuntimeData>(); }
  2188. void SetCodeGenRuntimeData(FunctionCodeGenRuntimeData** codeGenRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenRuntimeData>(codeGenRuntimeData); }
  2189. Field(FunctionCodeGenRuntimeData*)* GetCodeGenCallbackRuntimeData() const { return this->GetAuxPtr<AuxPointerType::CodeGenCallbackRuntimeData>(); }
  2190. Field(FunctionCodeGenRuntimeData*)* GetCodeGenCallbackRuntimeDataWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::CodeGenCallbackRuntimeData>(); }
  2191. void SetCodeGenCallbackRuntimeData(FunctionCodeGenRuntimeData** codeGenArgumentRuntimeData) { this->SetAuxPtr<AuxPointerType::CodeGenCallbackRuntimeData>(codeGenArgumentRuntimeData); }
  2192. template <typename TStatementMapList>
  2193. static StatementMap * GetNextNonSubexpressionStatementMap(TStatementMapList *statementMapList, int & startingAtIndex);
  2194. static StatementMap * GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex);
  2195. void RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType);
  2196. void RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  2197. // Find out an offset falls within the range. returns TRUE if found.
  2198. BOOL GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record);
  2199. bool GetLineCharOffset(int byteCodeOffset, ULONG* line, LONG* charOffset, bool canAllocateLineCache = true);
  2200. bool GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache = true);
  2201. // Given bytecode position, returns the start position of the statement and length of the statement.
  2202. bool GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength);
  2203. // skip any utf-8/utf-16 byte-order-mark. Returns the number of chars skipped.
  2204. static charcount_t SkipByteOrderMark(__in_bcount_z(4) LPCUTF8& documentStart)
  2205. {
  2206. charcount_t retValue = 0;
  2207. Assert(documentStart != nullptr);
  2208. if (documentStart[0] == 0xEF &&
  2209. documentStart[1] == 0xBB &&
  2210. documentStart[2] == 0xBF)
  2211. {
  2212. // UTF-8 - EF BB BF
  2213. // 3 bytes skipped - reports one char skipped
  2214. documentStart += 3;
  2215. retValue = 1;
  2216. }
  2217. else if ((documentStart[0] == 0xFF && documentStart[1] == 0xFE) ||
  2218. (documentStart[0] == 0xFE && documentStart[1] == 0xFF))
  2219. {
  2220. // UTF-16 LE - FF FE
  2221. // UTF-16 BE - FE FF
  2222. // 2 bytes skipped - reports one char skipped
  2223. documentStart += 2;
  2224. retValue = 1;
  2225. }
  2226. return retValue;
  2227. }
  2228. StatementMap* GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2229. int GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2230. StatementMap* GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  2231. StatementMap* GetMatchingStatementMapFromSource(int byteCodeOffset, int* pMapIndex = nullptr);
  2232. void RecordFrameDisplayRegister(RegSlot slot);
  2233. void RecordObjectRegister(RegSlot slot);
  2234. CrossFrameEntryExitRecordList* GetCrossFrameEntryExitRecords();
  2235. #ifdef VTUNE_PROFILING
  2236. uint GetStartOffset(uint statementIndex) const;
  2237. ULONG GetSourceLineNumber(uint statementIndex);
  2238. #endif
  2239. #pragma endregion
  2240. // Field accessors
  2241. bool GetHasBailoutInstrInJittedCode() const { return this->m_hasBailoutInstrInJittedCode; }
  2242. void SetHasBailoutInstrInJittedCode(bool hasBailout) { this->m_hasBailoutInstrInJittedCode = hasBailout; }
  2243. bool GetCanDefer() const { return this->functionInfo->CanBeDeferred() && this->m_depth == 0 && !this->m_hasActiveReference; }
  2244. bool GetCanReleaseLoopHeaders() const { return (this->m_depth == 0); }
  2245. void SetPendingLoopHeaderRelease(bool pendingLoopHeaderRelease) { this->m_pendingLoopHeaderRelease = pendingLoopHeaderRelease; }
  2246. bool GetIsFromNativeCodeModule() const { return m_isFromNativeCodeModule; }
  2247. void SetIsFromNativeCodeModule(bool isFromNativeCodeModule) { m_isFromNativeCodeModule = isFromNativeCodeModule; }
  2248. uint GetLoopNumber(LoopHeader const * loopHeader) const;
  2249. uint GetLoopNumberWithLock(LoopHeader const * loopHeader) const;
  2250. bool GetHasAllocatedLoopHeaders() { return this->GetLoopHeaderArray() != nullptr; }
  2251. Js::LoopHeader* GetLoopHeaderArray() const { return this->GetAuxPtr<AuxPointerType::LoopHeaderArray>(); }
  2252. Js::LoopHeader* GetLoopHeaderArrayWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::LoopHeaderArray>(); }
  2253. void SetLoopHeaderArray(Js::LoopHeader* loopHeaderArray) { this->SetAuxPtr<AuxPointerType::LoopHeaderArray>(loopHeaderArray); }
  2254. #if ENABLE_NATIVE_CODEGEN
  2255. Js::JavascriptMethod GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex);
  2256. void SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint, uint loopNum);
  2257. #endif
  2258. void RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPoint, JavascriptMethod oldOriginalEntryPoint, FunctionEntryPointInfo* newEntryPoint);
  2259. FunctionEntryPointInfo* CreateNewDefaultEntryPoint();
  2260. void AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPoint);
  2261. // Kind of entry point for original entry point
  2262. #if DBG
  2263. BOOL IsInterpreterThunk() const;
  2264. BOOL IsDynamicInterpreterThunk() const;
  2265. #endif
  2266. BOOL IsNativeOriginalEntryPoint() const;
  2267. bool IsSimpleJitOriginalEntryPoint() const;
  2268. #if DYNAMIC_INTERPRETER_THUNK
  2269. static BYTE GetOffsetOfDynamicInterpreterThunk() { return static_cast<BYTE>(offsetof(FunctionBody, m_dynamicInterpreterThunk)); }
  2270. void* GetDynamicInterpreterEntryPoint() const
  2271. {
  2272. return m_dynamicInterpreterThunk;
  2273. }
  2274. bool HasInterpreterThunkGenerated() const
  2275. {
  2276. return m_dynamicInterpreterThunk != nullptr;
  2277. }
  2278. DWORD GetDynamicInterpreterThunkSize() const;
  2279. #endif
  2280. bool GetHasHotLoop() const { return hasHotLoop; };
  2281. void SetHasHotLoop();
  2282. bool GetHasNestedLoop() const { return hasNestedLoop; };
  2283. void SetHasNestedLoop(bool nest) { hasNestedLoop = nest; };
  2284. bool IsInlineApplyDisabled();
  2285. void InitDisableInlineApply();
  2286. void SetDisableInlineApply(bool set);
  2287. bool IsInlineSpreadDisabled() const { return disableInlineSpread; }
  2288. void InitDisableInlineSpread() { disableInlineSpread = this->GetLocalFunctionId() != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this); }
  2289. void SetDisableInlineSpread(bool set) { disableInlineSpread = set; }
  2290. bool CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy);
  2291. #if DBG
  2292. bool HasValidSourceInfo();
  2293. #endif
  2294. #if DYNAMIC_INTERPRETER_THUNK
  2295. JavascriptMethod EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo);
  2296. #endif
  2297. #if ENABLE_NATIVE_CODEGEN
  2298. void SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint);
  2299. typedef void (*SetNativeEntryPointFuncType)(FunctionEntryPointInfo* entryPointInfo, Js::FunctionBody * functionBody, Js::JavascriptMethod entryPoint);
  2300. static void DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2301. static void ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2302. bool GetNativeEntryPointUsed() const { return m_nativeEntryPointUsed; }
  2303. void SetNativeEntryPointUsed(bool nativeEntryPointUsed) { this->m_nativeEntryPointUsed = nativeEntryPointUsed; }
  2304. bool GetHasDoneLoopBodyCodeGen() const { return hasDoneLoopBodyCodeGen; }
  2305. void SetHasDoneLoopBodyCodeGen(bool hasDoneLoopBodyCodeGen) { this->hasDoneLoopBodyCodeGen = hasDoneLoopBodyCodeGen; }
  2306. #endif
  2307. bool GetIsFuncRegistered() { return m_isFuncRegistered; }
  2308. void SetIsFuncRegistered(bool isRegistered) { m_isFuncRegistered = isRegistered; }
  2309. bool GetHasLoops() const { return this->GetLoopCount() != 0; }
  2310. uint IncrLoopCount() { return this->IncreaseCountField(CounterFields::LoopCount); }
  2311. uint GetLoopCount() const { return this->GetCountField(CounterFields::LoopCount); }
  2312. uint SetLoopCount(uint count) { return this->SetCountField(CounterFields::LoopCount, count); }
  2313. uint GetForInLoopDepth() const { return this->GetCountField(CounterFields::ForInLoopDepth); }
  2314. uint SetForInLoopDepth(uint count) { return this->SetCountField(CounterFields::ForInLoopDepth, count); }
  2315. bool AllocProfiledForInLoopCount(ProfileId* profileId)
  2316. {
  2317. ProfileId profiledForInLoopCount = this->GetProfiledForInLoopCount();
  2318. if (profiledForInLoopCount != Constants::NoProfileId)
  2319. {
  2320. *profileId = profiledForInLoopCount;
  2321. this->IncreaseCountField(CounterFields::ProfiledForInLoopCount);
  2322. return true;
  2323. }
  2324. return false;
  2325. }
  2326. ProfileId GetProfiledForInLoopCount() const { return (ProfileId)this->GetCountField(CounterFields::ProfiledForInLoopCount); }
  2327. void SetProfiledForInLoopCount(ProfileId count) { this->SetCountField(CounterFields::ProfiledForInLoopCount, count); }
  2328. bool AllocProfiledDivOrRem(ProfileId* profileId) { if (this->profiledDivOrRemCount != Constants::NoProfileId) { *profileId = this->profiledDivOrRemCount++; return true; } return false; }
  2329. ProfileId GetProfiledDivOrRemCount() { return this->profiledDivOrRemCount; }
  2330. bool AllocProfiledSwitch(ProfileId* profileId) { if (this->profiledSwitchCount != Constants::NoProfileId) { *profileId = this->profiledSwitchCount++; return true; } return false; }
  2331. ProfileId GetProfiledSwitchCount() { return this->profiledSwitchCount; }
  2332. bool AllocProfiledCallSiteId(ProfileId* profileId) { if (this->profiledCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledCallSiteCount++; return true; } return false; }
  2333. ProfileId GetProfiledCallSiteCount() const { return this->profiledCallSiteCount; }
  2334. void SetProfiledCallSiteCount(ProfileId callSiteId) { this->profiledCallSiteCount = callSiteId; }
  2335. bool AllocProfiledArrayCallSiteId(ProfileId* profileId) { if (this->profiledArrayCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledArrayCallSiteCount++; return true; } return false; }
  2336. ProfileId GetProfiledArrayCallSiteCount() const { return this->profiledArrayCallSiteCount; }
  2337. bool AllocProfiledReturnTypeId(ProfileId* profileId) { if (this->profiledReturnTypeCount != Constants::NoProfileId) { *profileId = this->profiledReturnTypeCount++; return true; } return false; }
  2338. ProfileId GetProfiledReturnTypeCount() const { return this->profiledReturnTypeCount; }
  2339. bool AllocProfiledSlotId(ProfileId* profileId) { if (this->profiledSlotCount != Constants::NoProfileId) { *profileId = this->profiledSlotCount++; return true; } return false; }
  2340. ProfileId GetProfiledSlotCount() const { return this->profiledSlotCount; }
  2341. bool AllocProfiledLdLenId(ProfileId* profileId) { if (this->profiledLdLenCount != Constants::NoProfileId) { *profileId = this->profiledLdLenCount++; return true; } return false; }
  2342. ProfileId GetProfiledLdLenCount() const { return this->profiledLdLenCount; }
  2343. bool AllocProfiledLdElemId(ProfileId* profileId) { if (this->profiledLdElemCount != Constants::NoProfileId) { *profileId = this->profiledLdElemCount++; return true; } return false; }
  2344. ProfileId GetProfiledLdElemCount() const { return this->profiledLdElemCount; }
  2345. bool AllocProfiledStElemId(ProfileId* profileId) { if (this->profiledStElemCount != Constants::NoProfileId) { *profileId = this->profiledStElemCount++; return true; } return false; }
  2346. ProfileId GetProfiledStElemCount() const { return this->profiledStElemCount; }
  2347. uint GetProfiledFldCount() const { return this->GetInlineCacheCount(); }
  2348. ArgSlot GetProfiledInParamsCount() const { return this->GetInParamsCount() > 1? this->GetInParamsCount() - 1 : 0; }
  2349. bool IsPartialDeserializedFunction() { return this->m_isPartialDeserializedFunction; }
  2350. #ifdef PERF_COUNTERS
  2351. bool IsDeserializedFunction() { return this->m_isDeserializedFunction; }
  2352. #endif
  2353. #ifdef IR_VIEWER
  2354. bool IsIRDumpEnabled() const { return this->m_isIRDumpEnabled; }
  2355. void SetIRDumpEnabled(bool enabled) { this->m_isIRDumpEnabled = enabled; }
  2356. Js::DynamicObject * GetIRDumpBaseObject();
  2357. #endif /* IR_VIEWER */
  2358. #if ENABLE_NATIVE_CODEGEN
  2359. void SetPolymorphicCallSiteInfoHead(PolymorphicCallSiteInfo *polyCallSiteInfo) { this->SetAuxPtr<AuxPointerType::PolymorphicCallSiteInfoHead>(polyCallSiteInfo); }
  2360. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoHead() { return this->GetAuxPtr<AuxPointerType::PolymorphicCallSiteInfoHead>(); }
  2361. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoWithLock() { return this->GetAuxPtrWithLock<AuxPointerType::PolymorphicCallSiteInfoHead>(); }
  2362. void SetCallbackInfoList(CallbackInfoList * callbackInfoList) { this->SetAuxPtr<AuxPointerType::CallbackArgOutInfoList>(callbackInfoList); }
  2363. CallbackInfoList * GetCallbackInfoList() { return this->GetAuxPtr<AuxPointerType::CallbackArgOutInfoList>(); }
  2364. CallbackInfoList * GetCallbackInfoListWithLock() { return this->GetAuxPtrWithLock<AuxPointerType::CallbackArgOutInfoList>(); }
  2365. #endif
  2366. FunctionBodyPolymorphicInlineCache * GetPolymorphicInlineCachesHead() { return this->GetAuxPtr<AuxPointerType::PolymorphicInlineCachesHead>(); }
  2367. void SetPolymorphicInlineCachesHead(FunctionBodyPolymorphicInlineCache * cache) { this->SetAuxPtr<AuxPointerType::PolymorphicInlineCachesHead>(cache); }
  2368. bool PolyInliningUsingFixedMethodsAllowedByConfigFlags(FunctionBody* topFunctionBody)
  2369. {
  2370. return !PHASE_OFF(Js::InlinePhase, this) && !PHASE_OFF(Js::InlinePhase, topFunctionBody) &&
  2371. !PHASE_OFF(Js::PolymorphicInlinePhase, this) && !PHASE_OFF(Js::PolymorphicInlinePhase, topFunctionBody) &&
  2372. !PHASE_OFF(Js::FixedMethodsPhase, this) && !PHASE_OFF(Js::FixedMethodsPhase, topFunctionBody) &&
  2373. !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, this) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, topFunctionBody);
  2374. }
  2375. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainer() const
  2376. {
  2377. return this->GetAuxPtr<AuxPointerType::PropertyIdOnRegSlotsContainer>();
  2378. }
  2379. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainerWithLock() const
  2380. {
  2381. return this->GetAuxPtrWithLock<AuxPointerType::PropertyIdOnRegSlotsContainer>();
  2382. }
  2383. void SetPropertyIdOnRegSlotsContainer(Js::PropertyIdOnRegSlotsContainer *propertyIdOnRegSlotsContainer)
  2384. {
  2385. this->SetAuxPtr<AuxPointerType::PropertyIdOnRegSlotsContainer>(propertyIdOnRegSlotsContainer);
  2386. }
  2387. private:
  2388. void ResetProfileIds();
  2389. public:
  2390. bool GetHasFinally() const { return m_hasFinally; }
  2391. void SetHasFinally(bool has){ m_hasFinally = has; }
  2392. bool GetFuncEscapes() const { return funcEscapes; }
  2393. void SetFuncEscapes(bool does) { funcEscapes = does; }
  2394. #if DBG
  2395. bool CanDoStackNestedFunc() const { return m_canDoStackNestedFunc; }
  2396. void SetCanDoStackNestedFunc() { m_canDoStackNestedFunc = true; }
  2397. #endif
  2398. RecyclerWeakReference<FunctionInfo> * GetStackNestedFuncParent();
  2399. FunctionInfo * GetStackNestedFuncParentStrongRef();
  2400. FunctionInfo * GetAndClearStackNestedFuncParent();
  2401. void ClearStackNestedFuncParent();
  2402. void SetStackNestedFuncParent(FunctionInfo * parentFunctionInfo);
  2403. uint GetScopeSlotArraySize() const
  2404. {
  2405. return scopeSlotArraySize;
  2406. }
  2407. #if defined(_M_IX86) || defined(_M_X64)
  2408. template <typename T>
  2409. static bool DoStackClosure(T functionBody)
  2410. {
  2411. return functionBody->DoStackNestedFunc()
  2412. && functionBody->GetNestedCount() != 0
  2413. && functionBody->GetScopeSlotArraySize() != 0
  2414. && functionBody->GetEnvDepth() != (uint16)-1;
  2415. }
  2416. #else
  2417. template <typename T>
  2418. static bool DoStackClosure(T functionBody)
  2419. {
  2420. return false;
  2421. }
  2422. #endif
  2423. bool DoStackFrameDisplay() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2424. bool DoStackScopeSlots() const { return DoStackClosure(this) && !PHASE_OFF(StackClosurePhase, this); }
  2425. bool GetIsFirstFunctionObject() const { return m_firstFunctionObject; }
  2426. void SetIsNotFirstFunctionObject() { m_firstFunctionObject = false; }
  2427. bool GetInlineCachesOnFunctionObject() { return m_inlineCachesOnFunctionObject; }
  2428. void SetInlineCachesOnFunctionObject(bool has) { m_inlineCachesOnFunctionObject = has; }
  2429. bool NeedScopeObjectForArguments(bool hasNonSimpleParams)
  2430. {
  2431. Assert(HasReferenceableBuiltInArguments());
  2432. // We can avoid creating a scope object with arguments present if:
  2433. bool dontNeedScopeObject =
  2434. // Either we are in strict mode, or have strict mode formal semantics from a non-simple parameter list, and
  2435. (GetIsStrictMode() || hasNonSimpleParams)
  2436. // Neither of the scopes are objects
  2437. && !HasScopeObject();
  2438. return
  2439. // Regardless of the conditions above, we won't need a scope object if there aren't any formals.
  2440. (GetInParamsCount() > 1 || GetHasRestParameter())
  2441. && !dontNeedScopeObject;
  2442. }
  2443. uint GetNumberOfRecursiveCallSites();
  2444. bool CanInlineRecursively(uint depth, bool tryAggressive = true);
  2445. public:
  2446. #if ENABLE_NATIVE_CODEGEN
  2447. bool CanInlineAgain() const
  2448. {
  2449. // Block excessive recursive inlining of the same function
  2450. return inlineDepth < static_cast<byte>(max(1, min(0xff, CONFIG_FLAG(MaxFuncInlineDepth))));
  2451. }
  2452. void OnBeginInlineInto()
  2453. {
  2454. ++inlineDepth;
  2455. }
  2456. void OnEndInlineInto()
  2457. {
  2458. --inlineDepth;
  2459. }
  2460. uint8 IncrementBailOnMisingProfileCount() { return ++bailOnMisingProfileCount; }
  2461. void ResetBailOnMisingProfileCount() { bailOnMisingProfileCount = 0; }
  2462. uint8 IncrementBailOnMisingProfileRejitCount() { return ++bailOnMisingProfileRejitCount; }
  2463. uint32 GetFrameHeight(EntryPointInfo* entryPointInfo) const;
  2464. #endif
  2465. RegSlot GetLocalsCount();
  2466. RegSlot GetConstantCount() const { return this->GetCountField(CounterFields::ConstantCount); }
  2467. void CheckAndSetConstantCount(RegSlot cNewConstants);
  2468. void SetConstantCount(RegSlot cNewConstants);
  2469. RegSlot GetVarCount();
  2470. void SetVarCount(RegSlot cNewVars);
  2471. void CheckAndSetVarCount(RegSlot cNewVars);
  2472. RegSlot MapRegSlot(RegSlot reg)
  2473. {
  2474. if (this->RegIsConst(reg))
  2475. {
  2476. reg = CONSTREG_TO_REGSLOT(reg);
  2477. Assert(reg < this->GetConstantCount());
  2478. }
  2479. else
  2480. {
  2481. reg += this->GetConstantCount();
  2482. }
  2483. return reg;
  2484. }
  2485. bool RegIsConst(RegSlot reg) { return reg > REGSLOT_TO_CONSTREG(this->GetConstantCount()); }
  2486. uint32 GetNonTempLocalVarCount();
  2487. uint32 GetFirstNonTempLocalIndex();
  2488. uint32 GetEndNonTempLocalIndex();
  2489. bool IsNonTempLocalVar(uint32 varIndex);
  2490. bool GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp = false);
  2491. RegSlot GetOutParamMaxDepth();
  2492. void SetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2493. void CheckAndSetOutParamMaxDepth(RegSlot cOutParamsDepth);
  2494. #if _M_X64
  2495. // 1 Var to push current m_outparam, 1 Var for "this"
  2496. // 6 Vars for register optimization in InterpreterStackFrame::OP_CallAsmInternalCommon
  2497. static constexpr RegSlot MinAsmJsOutParams() { return 1 + 1 + 6; }
  2498. #endif
  2499. RegSlot GetYieldRegister();
  2500. RegSlot GetFirstTmpRegister() const;
  2501. void SetFirstTmpRegister(RegSlot reg);
  2502. RegSlot GetFirstTmpReg();
  2503. void SetFirstTmpReg(RegSlot firstTmpReg);
  2504. RegSlot GetTempCount();
  2505. Js::ModuleID GetModuleID() const;
  2506. void CreateConstantTable();
  2507. void RecordNullObject(RegSlot location);
  2508. void RecordUndefinedObject(RegSlot location);
  2509. void RecordTrueObject(RegSlot location);
  2510. void RecordFalseObject(RegSlot location);
  2511. void RecordIntConstant(RegSlot location, unsigned int val);
  2512. void RecordStrConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool forcePropertyString);
  2513. void RecordBigIntConstant(RegSlot location, LPCOLESTR psz, uint32 cch, bool isNegative);
  2514. void RecordFloatConstant(RegSlot location, double d);
  2515. void RecordNullDisplayConstant(RegSlot location);
  2516. void RecordStrictNullDisplayConstant(RegSlot location);
  2517. void InitConstantSlots(Var *dstSlots);
  2518. Var GetConstantVar(RegSlot location);
  2519. Field(Js::Var)* GetConstTable() const { return this->m_constTable; }
  2520. void SetConstTable(Field(Js::Var)* constTable) { this->m_constTable = constTable; }
  2521. void MarkScript(ByteBlock * pblkByteCode, ByteBlock * pblkAuxiliaryData, ByteBlock* auxContextBlock,
  2522. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount);
  2523. void BeginExecution();
  2524. void EndExecution();
  2525. SourceInfo * GetSourceInfo() { return &this->m_sourceInfo; }
  2526. #ifdef ENABLE_SCRIPT_DEBUGGING
  2527. bool InstallProbe(int offset);
  2528. bool UninstallProbe(int offset);
  2529. bool ProbeAtOffset(int offset, OpCode* pOriginalOpcode);
  2530. #endif
  2531. static bool ShouldShareInlineCaches() { return CONFIG_FLAG(ShareInlineCaches); }
  2532. uint GetInlineCacheCount() const { return GetCountField(CounterFields::InlineCacheCount); }
  2533. void SetInlineCacheCount(uint count) { SetCountField(CounterFields::InlineCacheCount, count); }
  2534. uint GetRootObjectLoadInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadInlineCacheStart); }
  2535. void SetRootObjectLoadInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadInlineCacheStart, count); }
  2536. uint GetRootObjectLoadMethodInlineCacheStart() const { return GetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart); }
  2537. void SetRootObjectLoadMethodInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectLoadMethodInlineCacheStart, count); }
  2538. uint GetRootObjectStoreInlineCacheStart() const { return GetCountField(CounterFields::RootObjectStoreInlineCacheStart); }
  2539. void SetRootObjectStoreInlineCacheStart(uint count) { SetCountField(CounterFields::RootObjectStoreInlineCacheStart, count); }
  2540. uint GetIsInstInlineCacheCount() const { return GetCountField(CounterFields::IsInstInlineCacheCount); }
  2541. void SetIsInstInlineCacheCount(uint count) { SetCountField(CounterFields::IsInstInlineCacheCount, count); }
  2542. uint GetReferencedPropertyIdCount() const { return GetCountField(CounterFields::ReferencedPropertyIdCount); }
  2543. void SetReferencedPropertyIdCount(uint count) { SetCountField(CounterFields::ReferencedPropertyIdCount, count); }
  2544. uint GetObjLiteralCount() const { return GetCountField(CounterFields::ObjLiteralCount); }
  2545. void SetObjLiteralCount(uint count) { SetCountField(CounterFields::ObjLiteralCount, count); }
  2546. uint IncObjLiteralCount() { return IncreaseCountField(CounterFields::ObjLiteralCount); }
  2547. uint GetLiteralRegexCount() const { return GetCountField(CounterFields::LiteralRegexCount); }
  2548. void SetLiteralRegexCount(uint count) { SetCountField(CounterFields::LiteralRegexCount, count); }
  2549. uint IncLiteralRegexCount() { return IncreaseCountField(CounterFields::LiteralRegexCount); }
  2550. void AllocateForInCache();
  2551. EnumeratorCache * GetForInCache(uint index);
  2552. EnumeratorCache * GetForInCacheArray();
  2553. void CleanUpForInCache(bool isShutdown);
  2554. void AllocateInlineCache();
  2555. InlineCache * GetInlineCache(uint index);
  2556. bool CanFunctionObjectHaveInlineCaches();
  2557. void** GetInlineCaches();
  2558. #if DBG
  2559. byte* GetInlineCacheTypes();
  2560. #endif
  2561. IsInstInlineCache * GetIsInstInlineCache(uint index);
  2562. PolymorphicInlineCache * GetPolymorphicInlineCache(uint index);
  2563. PolymorphicInlineCache * CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache);
  2564. PolymorphicInlineCache * CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId);
  2565. private:
  2566. void ResetInlineCaches();
  2567. PolymorphicInlineCache * CreatePolymorphicInlineCache(uint index, uint16 size);
  2568. FieldWithBarrier(uint32) m_asmJsTotalLoopCount;
  2569. public:
  2570. void CreateCacheIdToPropertyIdMap();
  2571. void CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart, uint rootObjectStoreInlineCacheStart,
  2572. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount);
  2573. void SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId);
  2574. PropertyId GetPropertyIdFromCacheId(uint cacheId)
  2575. {
  2576. Assert(this->cacheIdToPropertyIdMap);
  2577. Assert(cacheId < this->GetInlineCacheCount());
  2578. return this->cacheIdToPropertyIdMap[cacheId];
  2579. }
  2580. #if DBG
  2581. void VerifyCacheIdToPropertyIdMap();
  2582. #endif
  2583. PropertyId* GetReferencedPropertyIdMap() const { return this->GetAuxPtr<AuxPointerType::ReferencedPropertyIdMap>(); }
  2584. PropertyId* GetReferencedPropertyIdMapWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::ReferencedPropertyIdMap>(); }
  2585. void SetReferencedPropertyIdMap(PropertyId* propIdMap) { this->SetAuxPtr<AuxPointerType::ReferencedPropertyIdMap>(propIdMap); }
  2586. void CreateReferencedPropertyIdMap(uint referencedPropertyIdCount);
  2587. void CreateReferencedPropertyIdMap();
  2588. PropertyId GetReferencedPropertyIdWithMapIndex(uint mapIndex);
  2589. PropertyId GetReferencedPropertyIdWithMapIndexWithLock(uint mapIndex);
  2590. void SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId);
  2591. PropertyId GetReferencedPropertyId(uint index);
  2592. PropertyId GetReferencedPropertyIdWithLock(uint index);
  2593. #if DBG
  2594. void VerifyReferencedPropertyIdMap();
  2595. #endif
  2596. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2597. void DumpFullFunctionName();
  2598. void DumpFunctionId(bool pad);
  2599. uint GetTraceFunctionNumber() const;
  2600. #endif
  2601. public:
  2602. uint NewObjectLiteral();
  2603. void AllocateObjectLiteralTypeArray();
  2604. Field(DynamicType*)* GetObjectLiteralTypeRef(uint index);
  2605. Field(DynamicType*)* GetObjectLiteralTypeRefWithLock(uint index);
  2606. uint NewLiteralRegex();
  2607. void AllocateLiteralRegexArray();
  2608. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexes() const { return this->GetAuxPtr<AuxPointerType::LiteralRegexes>(); }
  2609. Field(UnifiedRegex::RegexPattern*)* GetLiteralRegexesWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::LiteralRegexes>(); }
  2610. void SetLiteralRegexs(UnifiedRegex::RegexPattern ** literalRegexes) { this->SetAuxPtr<AuxPointerType::LiteralRegexes>(literalRegexes); }
  2611. UnifiedRegex::RegexPattern *GetLiteralRegex(const uint index);
  2612. UnifiedRegex::RegexPattern *GetLiteralRegexWithLock(const uint index);
  2613. #ifdef ASMJS_PLAT
  2614. AsmJsFunctionInfo* GetAsmJsFunctionInfo() const { return this->GetAuxPtr<AuxPointerType::AsmJsFunctionInfo>(); }
  2615. AsmJsFunctionInfo* GetAsmJsFunctionInfoWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AsmJsFunctionInfo>(); }
  2616. AsmJsFunctionInfo* AllocateAsmJsFunctionInfo();
  2617. AsmJsModuleInfo* GetAsmJsModuleInfo()const { return this->GetAuxPtr<AuxPointerType::AsmJsModuleInfo>(); }
  2618. AsmJsModuleInfo* GetAsmJsModuleInfoWithLock()const { return this->GetAuxPtrWithLock<AuxPointerType::AsmJsModuleInfo>(); }
  2619. void ResetAsmJsInfo()
  2620. {
  2621. this->SetAuxPtr<AuxPointerType::AsmJsFunctionInfo>(nullptr);
  2622. this->SetAuxPtr<AuxPointerType::AsmJsModuleInfo>(nullptr);
  2623. }
  2624. bool IsAsmJSModule() const { return m_isAsmjsMode && !m_isAsmJsFunction; }
  2625. AsmJsModuleInfo* AllocateAsmJsModuleInfo();
  2626. #endif
  2627. void SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern);
  2628. Field(DynamicType*)* GetObjectLiteralTypes() const { return this->GetAuxPtr<AuxPointerType::ObjLiteralTypes>(); }
  2629. Field(DynamicType*)* GetObjectLiteralTypesWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::ObjLiteralTypes>(); }
  2630. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArray() const { return this->GetAuxPtr<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(); }
  2631. Js::AuxArray<uint32> * GetSlotIdInCachedScopeToNestedIndexArrayWithLock() const { return this->GetAuxPtrWithLock<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(); }
  2632. Js::AuxArray<uint32> * AllocateSlotIdInCachedScopeToNestedIndexArray(uint32 slotCount);
  2633. private:
  2634. void ResetLiteralRegexes();
  2635. void ResetObjectLiteralTypes();
  2636. void SetObjectLiteralTypes(DynamicType** objLiteralTypes) { this->SetAuxPtr<AuxPointerType::ObjLiteralTypes>(objLiteralTypes); };
  2637. void SetSlotIdInCachedScopeToNestedIndexArray(Js::AuxArray<uint32> * slotIdInCachedScopeToNestedIndexArray) { this->SetAuxPtr<AuxPointerType::SlotIdInCachedScopeToNestedIndexArray>(slotIdInCachedScopeToNestedIndexArray); }
  2638. void ResetSlotIdInCachedScopeToNestedIndexArray() { SetSlotIdInCachedScopeToNestedIndexArray(nullptr); }
  2639. public:
  2640. void ResetByteCodeGenState();
  2641. void ResetByteCodeGenVisitState();
  2642. void FindClosestStatements(int32 characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation);
  2643. #if ENABLE_NATIVE_CODEGEN
  2644. template<AuxPointerType T>
  2645. FunctionCodeGenRuntimeData *EnsureCodeGenRuntimeDataCommon(
  2646. Recycler *const recycler,
  2647. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2648. FunctionBody *const inlinee);
  2649. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2650. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, FunctionBody *inlineeFuncBody) const;
  2651. FunctionCodeGenRuntimeData *EnsureInlineeCodeGenRuntimeData(
  2652. Recycler *const recycler,
  2653. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2654. FunctionBody *const inlinee);
  2655. const FunctionCodeGenRuntimeData *GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const;
  2656. FunctionCodeGenRuntimeData *EnsureLdFldInlineeCodeGenRuntimeData(
  2657. Recycler *const recycler,
  2658. const InlineCacheIndex inlineCacheIndex,
  2659. FunctionBody *const inlinee);
  2660. const FunctionCodeGenRuntimeData * GetCallbackInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2661. FunctionCodeGenRuntimeData * EnsureCallbackInlineeCodeGenRuntimeData(
  2662. Recycler *const recycler,
  2663. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2664. FunctionBody *const inlinee);
  2665. void LoadDynamicProfileInfo();
  2666. bool HasExecutionDynamicProfileInfo() const { return hasExecutionDynamicProfileInfo; }
  2667. bool HasDynamicProfileInfo() const { return dynamicProfileInfo != nullptr; }
  2668. bool NeedEnsureDynamicProfileInfo() const;
  2669. DynamicProfileInfo * GetDynamicProfileInfo() const { Assert(HasExecutionDynamicProfileInfo()); return dynamicProfileInfo; }
  2670. DynamicProfileInfo * GetAnyDynamicProfileInfo() const { Assert(HasDynamicProfileInfo()); return dynamicProfileInfo; }
  2671. DynamicProfileInfo * EnsureDynamicProfileInfo();
  2672. DynamicProfileInfo * AllocateDynamicProfile();
  2673. BYTE GetSavedInlinerVersion() const;
  2674. uint32 GetSavedPolymorphicCacheState() const;
  2675. void SetSavedPolymorphicCacheState(uint32 state);
  2676. ImplicitCallFlags GetSavedImplicitCallsFlags() const;
  2677. bool HasNonBuiltInCallee();
  2678. void RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 offset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum);
  2679. void SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint);
  2680. BOOL GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2681. BOOL GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2682. FunctionEntryPointInfo * GetEntryPointFromNativeAddress(DWORD_PTR codeAddress);
  2683. LoopEntryPointInfo * GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const;
  2684. #endif
  2685. void InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount);
  2686. void InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount);
  2687. void SetPropertyIdsOfFormals(PropertyIdArray * formalArgs);
  2688. PropertyIdArray * AllocatePropertyIdArrayForFormals(uint32 size, uint32 count, byte extraSlots);
  2689. bool DontRethunkAfterBailout() const { return dontRethunkAfterBailout; }
  2690. void SetDontRethunkAfterBailout() { dontRethunkAfterBailout = true; }
  2691. void ClearDontRethunkAfterBailout() { dontRethunkAfterBailout = false; }
  2692. void SaveState(ParseNodeFnc * pnodeFnc);
  2693. void RestoreState(ParseNodeFnc * pnodeFnc);
  2694. // 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.
  2695. // 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.
  2696. bool HasAllNonLocalReferenced() const { return m_hasAllNonLocalReferenced; }
  2697. void SetAllNonLocalReferenced(bool set) { m_hasAllNonLocalReferenced = set; }
  2698. bool HasSetIsObject() const { return m_hasSetIsObject; }
  2699. void SetHasSetIsObject(bool set) { m_hasSetIsObject = set; }
  2700. bool HasFuncExprNameReference() const { return m_hasFunExprNameReference; }
  2701. void SetFuncExprNameReference(bool value) { m_hasFunExprNameReference = value; }
  2702. bool GetChildCallsEval() const { return m_ChildCallsEval; }
  2703. void SetChildCallsEval(bool value) { m_ChildCallsEval = value; }
  2704. bool GetCallsEval() const { return m_CallsEval; }
  2705. void SetCallsEval(bool set) { m_CallsEval = set; }
  2706. bool HasReferenceableBuiltInArguments() const { return m_hasReferenceableBuiltInArguments; }
  2707. void SetHasReferenceableBuiltInArguments(bool value) { m_hasReferenceableBuiltInArguments = value; }
  2708. bool IsParamAndBodyScopeMerged() const { return m_isParamAndBodyScopeMerged; }
  2709. void SetParamAndBodyScopeNotMerged() { m_isParamAndBodyScopeMerged = false; }
  2710. // Used for the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple time for each child function.
  2711. bool HasDoneAllNonLocalReferenced() const { return m_hasDoneAllNonLocalReferenced; }
  2712. void SetHasDoneAllNonLocalReferenced(bool set) { m_hasDoneAllNonLocalReferenced = set; }
  2713. // 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.
  2714. bool HasFunctionCompiledSent() const { return m_hasFunctionCompiledSent; }
  2715. void SetHasFunctionCompiledSent(bool set) { m_hasFunctionCompiledSent = set; }
  2716. #if DBG_DUMP
  2717. void DumpStatementMaps();
  2718. void Dump();
  2719. void PrintStatementSourceLine(uint statementIndex);
  2720. void PrintStatementSourceLineFromStartOffset(uint cchStartOffset);
  2721. void DumpScopes();
  2722. #endif
  2723. uint GetStatementStartOffset(const uint statementIndex);
  2724. #ifdef IR_VIEWER
  2725. void GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2726. ULONG * line, LONG * col);
  2727. void GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2728. ULONG * line, LONG * col);
  2729. #endif
  2730. #if ENABLE_TTD
  2731. void GetSourceLineFromStartOffset_TTD(const uint startOffset, ULONG* line, LONG* col);
  2732. #endif
  2733. #ifdef ENABLE_SCRIPT_PROFILING
  2734. HRESULT RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent = FALSE);
  2735. HRESULT ReportScriptCompiled();
  2736. HRESULT ReportFunctionCompiled();
  2737. void SetEntryToProfileMode();
  2738. #endif
  2739. #ifdef ENABLE_SCRIPT_DEBUGGING
  2740. void CheckAndRegisterFuncToDiag(ScriptContext *scriptContext);
  2741. void SetEntryToDeferParseForDebugger();
  2742. #endif
  2743. void ClearEntryPoints();
  2744. void ResetEntryPoint();
  2745. void CleanupToReparseHelper();
  2746. void UpdateEntryPointsOnDebugReparse();
  2747. void AddDeferParseAttribute();
  2748. void RemoveDeferParseAttribute();
  2749. #if DBG
  2750. void MustBeInDebugMode();
  2751. #endif
  2752. static bool IsDummyGlobalRetStatement(const regex::Interval *sourceSpan)
  2753. {
  2754. Assert(sourceSpan != nullptr);
  2755. return sourceSpan->begin == 0 && sourceSpan->end == 0;
  2756. }
  2757. static void GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer);
  2758. template<class Fn>
  2759. void MapLoopHeaders(Fn fn) const
  2760. {
  2761. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2762. if(loopHeaderArray)
  2763. {
  2764. uint loopCount = this->GetLoopCount();
  2765. for(uint i = 0; i < loopCount; i++)
  2766. {
  2767. fn(i , &loopHeaderArray[i]);
  2768. }
  2769. }
  2770. }
  2771. template<class Fn>
  2772. void MapLoopHeadersWithLock(Fn fn) const
  2773. {
  2774. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArrayWithLock();
  2775. if (loopHeaderArray)
  2776. {
  2777. uint loopCount = this->GetLoopCount();
  2778. for (uint i = 0; i < loopCount; i++)
  2779. {
  2780. fn(i, &loopHeaderArray[i]);
  2781. }
  2782. }
  2783. }
  2784. template<class Fn>
  2785. bool MapLoopHeadersUntil(Fn fn) const
  2786. {
  2787. Js::LoopHeader* loopHeaderArray = this->GetLoopHeaderArray();
  2788. if (loopHeaderArray)
  2789. {
  2790. uint loopCount = this->GetLoopCount();
  2791. for (uint i = 0; i < loopCount; i++)
  2792. {
  2793. if (fn(i, &loopHeaderArray[i]))
  2794. {
  2795. return true;
  2796. }
  2797. }
  2798. return false;
  2799. }
  2800. return false;
  2801. }
  2802. template <class Fn>
  2803. void MapEntryPoints(Fn fn) const
  2804. {
  2805. if (this->entryPoints)
  2806. {
  2807. this->entryPoints->Map([&fn] (int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2808. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2809. if (strongRef)
  2810. {
  2811. fn(index, strongRef);
  2812. }
  2813. });
  2814. }
  2815. }
  2816. template <class Fn>
  2817. bool MapEntryPointsUntil(Fn fn) const
  2818. {
  2819. if (this->entryPoints)
  2820. {
  2821. return this->entryPoints->MapUntil([&fn](int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2822. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2823. if (strongRef)
  2824. {
  2825. return fn(index, strongRef);
  2826. }
  2827. return false;
  2828. });
  2829. }
  2830. return false;
  2831. }
  2832. bool DoJITLoopBody() const
  2833. {
  2834. return IsJitLoopBodyPhaseEnabled() && this->GetLoopHeaderArrayWithLock() != nullptr;
  2835. }
  2836. bool ForceJITLoopBody() const
  2837. {
  2838. return IsJitLoopBodyPhaseForced() && !this->GetHasTry();
  2839. }
  2840. bool IsGeneratorAndJitIsDisabled()
  2841. {
  2842. return this->IsCoroutine() && !(CONFIG_ISENABLED(Js::JitES6GeneratorsFlag) && !this->GetHasTry());
  2843. }
  2844. FunctionBodyFlags * GetAddressOfFlags() { return &this->flags; }
  2845. Js::RegSlot GetRestParamRegSlot();
  2846. public:
  2847. void RecordConstant(RegSlot location, Var var);
  2848. private:
  2849. inline void CheckEmpty();
  2850. inline void CheckNotExecuting();
  2851. BOOL GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee);
  2852. #if ENABLE_NATIVE_CODEGEN
  2853. int GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset);
  2854. int GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress);
  2855. #endif
  2856. void EnsureAuxStatementData();
  2857. StatementAdjustmentRecordList* GetStatementAdjustmentRecords();
  2858. };
  2859. class AutoRestoreFunctionInfo {
  2860. public:
  2861. AutoRestoreFunctionInfo(ParseableFunctionInfo *pfi, const JavascriptMethod originalEntryPoint) : pfi(pfi), funcBody(nullptr), originalEntryPoint(originalEntryPoint) {}
  2862. ~AutoRestoreFunctionInfo() {
  2863. if (this->pfi != nullptr && this->pfi->GetFunctionInfo()->GetFunctionProxy() != this->pfi)
  2864. {
  2865. FunctionInfo *functionInfo = this->pfi->GetFunctionInfo();
  2866. FunctionBody *functionBody = functionInfo->GetFunctionProxy()->GetFunctionBody();
  2867. functionBody->RedeferFunctionObjectTypes();
  2868. functionInfo->SetAttributes(
  2869. (FunctionInfo::Attributes)(functionInfo->GetAttributes() | FunctionInfo::Attributes::DeferredParse));
  2870. functionInfo->SetFunctionProxy(this->pfi);
  2871. functionInfo->SetOriginalEntryPoint(originalEntryPoint);
  2872. }
  2873. Assert(this->pfi == nullptr || (this->pfi->GetFunctionInfo()->GetFunctionProxy() == this->pfi && !this->pfi->IsFunctionBody()));
  2874. }
  2875. void Clear() { pfi = nullptr; funcBody = nullptr; }
  2876. ParseableFunctionInfo * pfi;
  2877. FunctionBody * funcBody;
  2878. const JavascriptMethod originalEntryPoint;
  2879. };
  2880. // If we throw or fail with the function body in an unfinished state, make sure the function info is still
  2881. // pointing to the old ParseableFunctionInfo and has the right attributes.
  2882. typedef SynchronizableList<FunctionBody*, JsUtil::List<FunctionBody*, ArenaAllocator, false, Js::FreeListedRemovePolicy> > FunctionBodyList;
  2883. struct ScopeSlots
  2884. {
  2885. public:
  2886. static uint const MaxEncodedSlotCount = Constants::UShortMaxValue;
  2887. // The slot index is at the same location as the vtable, so that we can distinguish between scope slot and frame display
  2888. static uint const EncodedSlotCountSlotIndex = 0;
  2889. static uint const ScopeMetadataSlotIndex = 1; // Either a FunctionBody* or DebuggerScope*
  2890. static uint const FirstSlotIndex = 2;
  2891. public:
  2892. ScopeSlots(Field(Var)* slotArray) : slotArray(slotArray)
  2893. {
  2894. }
  2895. bool IsDebuggerScopeSlotArray();
  2896. FunctionInfo* GetFunctionInfo()
  2897. {
  2898. Assert(!IsDebuggerScopeSlotArray());
  2899. return (FunctionInfo*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  2900. }
  2901. DebuggerScope* GetDebuggerScope()
  2902. {
  2903. Assert(IsDebuggerScopeSlotArray());
  2904. return (DebuggerScope*)PointerValue(slotArray[ScopeMetadataSlotIndex]);
  2905. }
  2906. Var GetScopeMetadataRaw() const
  2907. {
  2908. return slotArray[ScopeMetadataSlotIndex];
  2909. }
  2910. void SetScopeMetadata(Var scopeMetadataObj)
  2911. {
  2912. slotArray[ScopeMetadataSlotIndex] = scopeMetadataObj;
  2913. }
  2914. size_t GetCount() const
  2915. {
  2916. return ::Math::PointerCastToIntegralTruncate<size_t>(slotArray[EncodedSlotCountSlotIndex]);
  2917. }
  2918. void SetCount(uint count)
  2919. {
  2920. slotArray[EncodedSlotCountSlotIndex] = (Var)min<uint>(count, ScopeSlots::MaxEncodedSlotCount);
  2921. }
  2922. Var Get(uint i) const
  2923. {
  2924. Assert(i < GetCount());
  2925. return slotArray[i + FirstSlotIndex];
  2926. }
  2927. void Set(uint i, Var value)
  2928. {
  2929. Assert(i < GetCount());
  2930. slotArray[i + FirstSlotIndex] = value;
  2931. }
  2932. template<class Fn>
  2933. void Map(Fn fn)
  2934. {
  2935. uint count = GetCount();
  2936. for(uint i = 0; i < count; i++)
  2937. {
  2938. fn(GetSlot[i]);
  2939. }
  2940. }
  2941. // The first pointer sized value in the object for scope slots is the count, while it is a vtable
  2942. // for Activation object or with scope (a recyclable object)
  2943. // VTable values are always > 64K because they are a pointer, hence anything less than that implies
  2944. // a slot array.
  2945. // CONSIDER: Use TaggedInt instead of range of slot count to distinguish slot array with others.
  2946. static bool Is(void* object)
  2947. {
  2948. if (object == nullptr)
  2949. {
  2950. // Null slot in a frame where nothing is captured and the scope object has been eliminated
  2951. // by stack args optimization.
  2952. return false;
  2953. }
  2954. size_t slotCount = *((size_t*)object);
  2955. if(slotCount <= MaxEncodedSlotCount)
  2956. {
  2957. return true;
  2958. }
  2959. return false;
  2960. }
  2961. private:
  2962. Field(Field(Var)*) slotArray;
  2963. };
  2964. enum ScopeType
  2965. {
  2966. ScopeType_ActivationObject,
  2967. ScopeType_SlotArray,
  2968. ScopeType_WithScope
  2969. };
  2970. // A FrameDisplay encodes a FunctionObject's scope chain. It is an array of scopes, where each scope can be either an inline slot array
  2971. // or a RecyclableObject. A FrameDisplay for a given FunctionObject will consist of the FrameDisplay from it's enclosing scope, with any additional
  2972. // scopes prepended. Due to with statements etc. a function may introduce multiple scopes to the FrameDisplay.
  2973. struct FrameDisplay
  2974. {
  2975. FrameDisplay(uint16 len, bool strictMode = false) :
  2976. tag(true),
  2977. length(len),
  2978. strictMode(strictMode)
  2979. #if _M_X64
  2980. , unused(0)
  2981. #endif
  2982. {
  2983. }
  2984. void SetTag(bool tag) { this->tag = tag; }
  2985. void SetItem(uint index, void* item);
  2986. void *GetItem(uint index);
  2987. uint16 GetLength() const { return length; }
  2988. void SetLength(uint16 len) { this->length = len; }
  2989. bool GetStrictMode() const { return strictMode; }
  2990. void SetStrictMode(bool flag) { this->strictMode = flag; }
  2991. Field(void*)* GetDataAddress() { return this->scopes; }
  2992. static uint32 GetOffsetOfStrictMode() { return offsetof(FrameDisplay, strictMode); }
  2993. static uint32 GetOffsetOfLength() { return offsetof(FrameDisplay, length); }
  2994. static uint32 GetOffsetOfScopes() { return offsetof(FrameDisplay, scopes); }
  2995. static ScopeType GetScopeType(void* scope);
  2996. private:
  2997. Field(bool) tag; // Tag it so that the NativeCodeGenerator::IsValidVar would not think this is var
  2998. Field(bool) strictMode;
  2999. Field(uint16) length;
  3000. #if defined(TARGET_64)
  3001. Field(uint32) unused;
  3002. #endif
  3003. Field(void*) scopes[];
  3004. };
  3005. #pragma region Function Body helper classes
  3006. #pragma region Debugging related source classes
  3007. // Contains only the beginning part of the statement. This will mainly used in SmallSpanSequence which will further be compressed
  3008. // and stored in the buffer
  3009. struct StatementData
  3010. {
  3011. StatementData()
  3012. : sourceBegin(0),
  3013. bytecodeBegin(0)
  3014. {
  3015. }
  3016. int sourceBegin;
  3017. int bytecodeBegin;
  3018. };
  3019. struct StatementLocation
  3020. {
  3021. Js::FunctionBody* function;
  3022. regex::Interval statement;
  3023. regex::Interval bytecodeSpan;
  3024. };
  3025. // Small span in the Statement buffer of the SmallSpanSequence
  3026. struct SmallSpan
  3027. {
  3028. ushort sourceBegin;
  3029. ushort bytecodeBegin;
  3030. SmallSpan(uint32 val)
  3031. {
  3032. sourceBegin = (ushort)(val >> 16);
  3033. bytecodeBegin = (ushort)(val & 0x0000FFFF);
  3034. }
  3035. operator unsigned int()
  3036. {
  3037. return (uint32)sourceBegin << 16 | bytecodeBegin;
  3038. }
  3039. };
  3040. // Iterator which contains the state at particular index. These values will used when fetching next item from
  3041. // SmallSpanSequence
  3042. class SmallSpanSequenceIter
  3043. {
  3044. friend class SmallSpanSequence;
  3045. public:
  3046. SmallSpanSequenceIter()
  3047. : accumulatedIndex(-1),
  3048. accumulatedSourceBegin(0),
  3049. accumulatedBytecodeBegin(0),
  3050. indexOfActualOffset(0)
  3051. {
  3052. }
  3053. // Below are used for fast access when the last access happened nearby.
  3054. // so the actual index would be accumulatedIndex / 2 + (remainder for which byte).
  3055. int accumulatedIndex;
  3056. int accumulatedSourceBegin;
  3057. int accumulatedBytecodeBegin;
  3058. int indexOfActualOffset;
  3059. };
  3060. struct ThrowMapEntry
  3061. {
  3062. uint32 nativeBufferOffset;
  3063. uint32 statementIndex;
  3064. };
  3065. // This class compacts the range of the statement to BYTEs instead of ints.
  3066. // Instead of having start and end as int32s we will have them stored in bytes, and they will be
  3067. // treated as start offset and end offset.
  3068. // For simplicity, this class should be heap allocated, since it can be allocated from either the background
  3069. // or main thread.
  3070. class SmallSpanSequence
  3071. {
  3072. private:
  3073. BOOL GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data);
  3074. ushort GetDiff(int current, int prev);
  3075. public:
  3076. // Each item in the list contains two set of begins (one for bytecode and for sourcespan).
  3077. // The allowed valued for source and bytecode span is in between SHORT_MAX - 1 to SHORT_MIN (inclusive).
  3078. // otherwise its a miss
  3079. JsUtil::GrowingUint32HeapArray * pStatementBuffer;
  3080. // Contains list of values which are missed in StatementBuffer.
  3081. JsUtil::GrowingUint32HeapArray * pActualOffsetList;
  3082. // The first value of the sequence
  3083. int baseValue;
  3084. SmallSpanSequence();
  3085. ~SmallSpanSequence()
  3086. {
  3087. Cleanup();
  3088. }
  3089. void Cleanup()
  3090. {
  3091. if (pStatementBuffer != nullptr)
  3092. {
  3093. HeapDelete(pStatementBuffer);
  3094. pStatementBuffer = nullptr;
  3095. }
  3096. if (pActualOffsetList != nullptr)
  3097. {
  3098. HeapDelete(pActualOffsetList);
  3099. pActualOffsetList = nullptr;
  3100. }
  3101. }
  3102. // Trys to match passed bytecode in the statement, and returns the statement which includes that.
  3103. BOOL GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data);
  3104. // Record the statement data in the statement buffer in the compressed manner.
  3105. BOOL RecordARange(SmallSpanSequenceIter &iter, StatementData * data);
  3106. // Reset the accumulator's state and value.
  3107. void Reset(SmallSpanSequenceIter &iter);
  3108. uint32 Count() const { return pStatementBuffer ? pStatementBuffer->Count() : 0; }
  3109. BOOL Item(int index, SmallSpanSequenceIter &iter, StatementData &data);
  3110. // Below function will not change any state, so it will not alter accumulated index and value
  3111. BOOL Seek(int index, StatementData & data);
  3112. };
  3113. #pragma endregion
  3114. // This container represent the property ids for the locals which are placed at direct slot
  3115. // and list of formals args if user has not used the arguments object in the script for the current function
  3116. struct PropertyIdOnRegSlotsContainer
  3117. {
  3118. Field(PropertyId *) propertyIdsForRegSlots;
  3119. Field(uint) length;
  3120. // This keeps the upper bound of register slots for the formals. While emitting locals in the body we skip
  3121. // the properties that are below this limit.
  3122. Field(RegSlot) formalsUpperBound;
  3123. Field(PropertyIdArray *) propertyIdsForFormalArgs;
  3124. PropertyIdOnRegSlotsContainer();
  3125. static PropertyIdOnRegSlotsContainer * New(Recycler * recycler);
  3126. void CreateRegSlotsArray(Recycler * recycler, uint _length);
  3127. void SetFormalArgs(PropertyIdArray * formalArgs);
  3128. // Helper methods
  3129. void Insert(RegSlot reg, PropertyId propId);
  3130. void FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot);
  3131. // Whether reg belongs to non-temp locals
  3132. bool IsRegSlotFormal(RegSlot reg);
  3133. };
  3134. // Flags for the DebuggerScopeProperty object.
  3135. typedef int DebuggerScopePropertyFlags;
  3136. const int DebuggerScopePropertyFlags_None = 0x000000000;
  3137. const int DebuggerScopePropertyFlags_Const = 0x000000001;
  3138. const int DebuggerScopePropertyFlags_CatchObject = 0x000000002;
  3139. const int DebuggerScopePropertyFlags_WithObject = 0x000000004;
  3140. const int DebuggerScopePropertyFlags_ForInOrOfCollection = 0x000000008;
  3141. const int DebuggerScopePropertyFlags_HasDuplicateInBody = 0x000000016;
  3142. // Used to store local property info for with/catch objects, lets, or consts
  3143. // that are needed for the debugger.
  3144. class DebuggerScopeProperty
  3145. {
  3146. public:
  3147. Js::PropertyId propId; // The property ID of the scope variable.
  3148. RegSlot location; // Contains the location of the scope variable (regslot, slotarray, direct).
  3149. int byteCodeInitializationOffset; // The byte code offset used when comparing let/const variables for dead zone exclusion debugger side.
  3150. DebuggerScopePropertyFlags flags; // Flags for the property.
  3151. bool IsConst() const { return (flags & DebuggerScopePropertyFlags_Const) != 0; }
  3152. bool IsCatchObject() const { return (flags & DebuggerScopePropertyFlags_CatchObject) != 0; }
  3153. bool IsWithObject() const { return (flags & DebuggerScopePropertyFlags_WithObject) != 0; }
  3154. bool IsForInOrForOfCollectionScope() const { return (flags & DebuggerScopePropertyFlags_ForInOrOfCollection) != 0; }
  3155. public:
  3156. // Determines if the current property is in a dead zone. Note that the property makes
  3157. // no assumptions about what scope it's in, that is determined by DebuggerScope.
  3158. // byteCodeOffset - The current offset in bytecode that the debugger is at.
  3159. bool IsInDeadZone(int byteCodeOffset) const
  3160. {
  3161. if (IsForInOrForOfCollectionScope())
  3162. {
  3163. // These are let/const loop variables of a for-in or for-of loop
  3164. // in the scope for the collection expression. They are always
  3165. // in TDZ in this scope, never initialized by the bytecode.
  3166. return true;
  3167. }
  3168. if (this->byteCodeInitializationOffset == Constants::InvalidByteCodeOffset && !(IsCatchObject() || IsWithObject()))
  3169. {
  3170. 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.");
  3171. return false;
  3172. }
  3173. return byteCodeOffset < this->byteCodeInitializationOffset;
  3174. }
  3175. };
  3176. // Used to track with, catch, and block scopes for the debugger to determine context.
  3177. class DebuggerScope
  3178. {
  3179. protected:
  3180. DEFINE_VTABLE_CTOR_NOBASE(DebuggerScope);
  3181. public:
  3182. typedef JsUtil::List<DebuggerScopeProperty> DebuggerScopePropertyList;
  3183. DebuggerScope(Recycler* recycler, DiagExtraScopesType scopeType, RegSlot scopeLocation, int rangeBegin)
  3184. : scopeType(scopeType),
  3185. scopeProperties(nullptr),
  3186. parentScope(nullptr),
  3187. siblingScope(nullptr),
  3188. scopeLocation(scopeLocation),
  3189. recycler(recycler)
  3190. {
  3191. this->range.begin = rangeBegin;
  3192. this->range.end = -1;
  3193. }
  3194. virtual ~DebuggerScope() {}
  3195. static bool Is(void* ptr);
  3196. DebuggerScope * GetSiblingScope(RegSlot location, FunctionBody *functionBody);
  3197. void AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags);
  3198. bool GetPropertyIndex(Js::PropertyId propertyId, int& i);
  3199. bool HasProperty(Js::PropertyId propertyId);
  3200. bool IsOffsetInScope(int offset) const;
  3201. bool Contains(Js::PropertyId propertyId, RegSlot location) const;
  3202. bool IsBlockScope() const;
  3203. bool IsBlockObjectScope() const
  3204. {
  3205. return this->scopeType == Js::DiagBlockScopeInObject;
  3206. }
  3207. bool IsCatchScope() const;
  3208. bool IsWithScope() const;
  3209. bool IsSlotScope() const;
  3210. bool IsParamScope() const;
  3211. bool HasProperties() const;
  3212. bool IsAncestorOf(const DebuggerScope* potentialChildScope);
  3213. bool AreAllPropertiesInDeadZone(int byteCodeOffset) const;
  3214. RegSlot GetLocation() const { Assert(IsOwnScope()); return scopeLocation; }
  3215. bool IsOwnScope() const { return scopeLocation != Js::Constants::NoRegister; }
  3216. bool TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const;
  3217. bool TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const;
  3218. bool UpdatePropertyInitializationOffset(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3219. void UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  3220. void UpdatePropertiesInForInOrOfCollectionScope();
  3221. void SetParentScope(DebuggerScope* parentScope) { this->parentScope = parentScope; }
  3222. DebuggerScope* GetParentScope() const { return parentScope; }
  3223. DebuggerScope* FindCommonAncestor(DebuggerScope* debuggerScope);
  3224. int GetEnd() const { return range.end; }
  3225. int GetStart() const { return range.begin; }
  3226. void SetScopeLocation(RegSlot scopeLocation) { this->scopeLocation = scopeLocation; }
  3227. void SetBegin(int begin);
  3228. void SetEnd(int end);
  3229. #if DBG
  3230. void Dump();
  3231. PCWSTR GetDebuggerScopeTypeString(DiagExtraScopesType scopeType);
  3232. #endif
  3233. #if ENABLE_TTD
  3234. Js::PropertyId GetPropertyIdForSlotIndex_TTD(uint32 slotIndex) const;
  3235. #endif
  3236. public:
  3237. // The list of scope properties in this scope object.
  3238. // For with scope: Has 1 property that represents the scoped object.
  3239. // For catch scope: Has 1 property that represents the exception object.
  3240. // For block scope: Has 0-n properties that represent let/const variables in that scope.
  3241. Field(DebuggerScopePropertyList*) scopeProperties;
  3242. Field(DiagExtraScopesType) scopeType; // The type of scope being represented (With, Catch, or Block scope).
  3243. Field(DebuggerScope*) siblingScope; // Valid only when current scope is slot/activationobject and symbols are on direct regslot
  3244. static const int InvalidScopeIndex = -1;
  3245. private:
  3246. int GetScopeDepth() const;
  3247. bool UpdatePropertyInitializationOffsetInternal(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  3248. void EnsurePropertyListIsAllocated();
  3249. private:
  3250. FieldNoBarrier(Recycler*) recycler;
  3251. Field(DebuggerScope*) parentScope;
  3252. Field(regex::Interval) range; // The start and end byte code writer offsets used when comparing where the debugger is currently stopped at (breakpoint location).
  3253. Field(RegSlot) scopeLocation;
  3254. };
  3255. class ScopeObjectChain
  3256. {
  3257. public:
  3258. typedef JsUtil::List<DebuggerScope*> ScopeObjectChainList;
  3259. ScopeObjectChain(Recycler* recycler)
  3260. : pScopeChain(nullptr)
  3261. {
  3262. pScopeChain = RecyclerNew(recycler, ScopeObjectChainList, recycler);
  3263. }
  3264. // This function will return DebuggerScopeProperty when the property is found and correctly in the range.
  3265. // 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,
  3266. // and isConst will be updated.
  3267. // If the property is not found at all, it will return false, and isPropertyInDebuggerScope will be false.
  3268. bool TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone);
  3269. // List of all Scope Objects in a function. Scopes are added to this list as when they are created in bytecode gen part.
  3270. Field(ScopeObjectChainList*) pScopeChain;
  3271. };
  3272. #pragma endregion
  3273. } // namespace Js