FunctionBody.h 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347
  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. struct CodeGenWorkItem;
  7. class SourceContextInfo;
  8. class FunctionBailOutRecord;
  9. struct DeferredFunctionStub;
  10. #ifdef DYNAMIC_PROFILE_MUTATOR
  11. class DynamicProfileMutator;
  12. class DynamicProfileMutatorImpl;
  13. #endif
  14. #define MAX_FUNCTION_BODY_DEBUG_STRING_SIZE 42 //11*3+8+1
  15. namespace Js
  16. {
  17. #pragma region Class Forward Declarations
  18. class ByteCodeBufferReader;
  19. class ByteCodeBufferBuilder;
  20. class ByteCodeCache;
  21. class ScopeInfo;
  22. class SmallSpanSequence;
  23. struct StatementLocation;
  24. class SmallSpanSequenceIter;
  25. struct StatementData;
  26. struct PropertyIdOnRegSlotsContainer;
  27. struct InlineCache;
  28. struct PolymorphicInlineCache;
  29. struct IsInstInlineCache;
  30. class ScopeObjectChain;
  31. class EntryPointInfo;
  32. class FunctionProxy;
  33. class ParseableFunctionInfo;
  34. class FunctionBody;
  35. class DebuggerScopeProperty;
  36. class DebuggerScope;
  37. class FunctionEntryPointInfo;
  38. #ifndef TEMP_DISABLE_ASMJS
  39. class AsmJsFunctionInfo;
  40. class AmsJsModuleInfo;
  41. #endif
  42. class ArrayBuffer;
  43. class FunctionCodeGenRuntimeData;
  44. #pragma endregion
  45. typedef JsUtil::BaseDictionary<Js::PropertyId, const Js::PropertyRecord*, RecyclerNonLeafAllocator, PowerOf2SizePolicy, DefaultComparer, JsUtil::SimpleDictionaryEntry> PropertyRecordList;
  46. typedef JsUtil::BaseHashSet<void*, Recycler, PowerOf2SizePolicy> TypeRefSet;
  47. // Definition of scopes such as With, Catch and Block which will be used further in the debugger for additional look-ups.
  48. enum DiagExtraScopesType
  49. {
  50. DiagUnknownScope, // Unknown scope set when deserializing bytecode and the scope is not yet known.
  51. DiagWithScope, // With scope.
  52. DiagCatchScopeDirect, // Catch scope in regslot
  53. DiagCatchScopeInSlot, // Catch scope in slot array
  54. DiagCatchScopeInObject, // Catch scope in scope object
  55. DiagBlockScopeDirect, // Block scope in regslot
  56. DiagBlockScopeInSlot, // Block scope in slot array
  57. DiagBlockScopeInObject, // Block scope in activation object
  58. DiagBlockScopeRangeEnd, // Used to end a block scope range.
  59. };
  60. class PropertyGuard
  61. {
  62. friend class PropertyGuardValidator;
  63. private:
  64. intptr_t value;
  65. public:
  66. static PropertyGuard* New(Recycler* recycler) { return RecyclerNewLeaf(recycler, Js::PropertyGuard); }
  67. PropertyGuard() : value(1) {}
  68. PropertyGuard(intptr_t value) : value(value) { Assert(this->value != 0); }
  69. inline static size_t const GetSizeOfValue() { return sizeof(((PropertyGuard*)0)->value); }
  70. inline static size_t const GetOffsetOfValue() { return offsetof(PropertyGuard, value); }
  71. intptr_t GetValue() const { return this->value; }
  72. bool IsValid() { return this->value != 0; }
  73. void SetValue(intptr_t value) { Assert(value != 0); this->value = value; }
  74. intptr_t const* GetAddressOfValue() { return &this->value; }
  75. void Invalidate() { this->value = 0; }
  76. };
  77. class PropertyGuardValidator
  78. {
  79. // Required by EquivalentTypeGuard::SetType.
  80. CompileAssert(offsetof(PropertyGuard, value) == 0);
  81. CompileAssert(offsetof(ConstructorCache, guard.value) == offsetof(PropertyGuard, value));
  82. };
  83. class JitIndexedPropertyGuard : public Js::PropertyGuard
  84. {
  85. private:
  86. int index;
  87. public:
  88. JitIndexedPropertyGuard(intptr_t value, int index):
  89. Js::PropertyGuard(value), index(index) {}
  90. int GetIndex() const { return this->index; }
  91. };
  92. class JitTypePropertyGuard : public Js::JitIndexedPropertyGuard
  93. {
  94. public:
  95. JitTypePropertyGuard(Js::Type* type, int index):
  96. JitIndexedPropertyGuard(reinterpret_cast<intptr_t>(type), index) {}
  97. Js::Type* GetType() const { return reinterpret_cast<Js::Type*>(this->GetValue()); }
  98. };
  99. struct TypeGuardTransferEntry
  100. {
  101. PropertyId propertyId;
  102. JitIndexedPropertyGuard* guards[0];
  103. TypeGuardTransferEntry(): propertyId(Js::Constants::NoProperty) {}
  104. };
  105. class FakePropertyGuardWeakReference: public RecyclerWeakReference<Js::PropertyGuard>
  106. {
  107. public:
  108. static FakePropertyGuardWeakReference* New(Recycler* recycler, Js::PropertyGuard* guard)
  109. {
  110. Assert(guard != nullptr);
  111. return RecyclerNewLeaf(recycler, Js::FakePropertyGuardWeakReference, guard);
  112. }
  113. FakePropertyGuardWeakReference(const Js::PropertyGuard* guard)
  114. {
  115. this->strongRef = (char*)guard;
  116. this->strongRefHeapBlock = &CollectedRecyclerWeakRefHeapBlock::Instance;
  117. }
  118. void Zero()
  119. {
  120. Assert(this->strongRef != nullptr);
  121. this->strongRef = nullptr;
  122. }
  123. };
  124. struct CtorCacheGuardTransferEntry
  125. {
  126. PropertyId propertyId;
  127. ConstructorCache* caches[0];
  128. CtorCacheGuardTransferEntry(): propertyId(Js::Constants::NoProperty) {}
  129. };
  130. #define EQUIVALENT_TYPE_CACHE_SIZE (8)
  131. struct EquivalentTypeCache
  132. {
  133. Js::Type* types[EQUIVALENT_TYPE_CACHE_SIZE];
  134. PropertyGuard *guard;
  135. TypeEquivalenceRecord record;
  136. uint nextEvictionVictim;
  137. bool isLoadedFromProto;
  138. bool hasFixedValue;
  139. EquivalentTypeCache(): nextEvictionVictim(EQUIVALENT_TYPE_CACHE_SIZE) {}
  140. bool ClearUnusedTypes(Recycler *recycler);
  141. void SetGuard(PropertyGuard *theGuard) { this->guard = theGuard; }
  142. void SetIsLoadedFromProto() { this->isLoadedFromProto = true; }
  143. bool IsLoadedFromProto() const { return this->isLoadedFromProto; }
  144. void SetHasFixedValue() { this->hasFixedValue = true; }
  145. bool HasFixedValue() const { return this->hasFixedValue; }
  146. };
  147. class JitEquivalentTypeGuard : public JitIndexedPropertyGuard
  148. {
  149. // This pointer is allocated from background thread first, and then transferred to recycler,
  150. // so as to keep the cached types alive.
  151. EquivalentTypeCache* cache;
  152. uint32 objTypeSpecFldId;
  153. public:
  154. JitEquivalentTypeGuard(Type* type, int index, uint32 objTypeSpecFldId):
  155. JitIndexedPropertyGuard(reinterpret_cast<intptr_t>(type), index), cache(nullptr), objTypeSpecFldId(objTypeSpecFldId) {}
  156. Js::Type* GetType() const { return reinterpret_cast<Js::Type*>(this->GetValue()); }
  157. void SetType(const Js::Type* type)
  158. {
  159. this->SetValue(reinterpret_cast<intptr_t>(type));
  160. }
  161. uint32 GetObjTypeSpecFldId() const
  162. {
  163. return this->objTypeSpecFldId;
  164. }
  165. Js::EquivalentTypeCache* GetCache() const
  166. {
  167. return this->cache;
  168. }
  169. void SetCache(Js::EquivalentTypeCache* cache)
  170. {
  171. this->cache = cache;
  172. }
  173. };
  174. #pragma region Inline Cache Info class declarations
  175. class PolymorphicCacheUtilizationArray
  176. {
  177. private:
  178. byte *utilArray;
  179. public:
  180. PolymorphicCacheUtilizationArray()
  181. : utilArray(nullptr)
  182. {
  183. }
  184. void EnsureUtilArray(Recycler * const recycler, Js::FunctionBody * functionBody);
  185. void SetUtil(Js::FunctionBody* functionBody, uint index, byte util);
  186. byte GetUtil(Js::FunctionBody* functionBody, uint index);
  187. };
  188. class PolymorphicInlineCacheInfo sealed
  189. {
  190. private:
  191. InlineCachePointerArray<PolymorphicInlineCache> polymorphicInlineCaches;
  192. PolymorphicCacheUtilizationArray polymorphicCacheUtilizationArray;
  193. FunctionBody * functionBody;
  194. public:
  195. PolymorphicInlineCacheInfo(FunctionBody * functionBody)
  196. : functionBody(functionBody)
  197. {
  198. }
  199. InlineCachePointerArray<PolymorphicInlineCache> * GetPolymorphicInlineCaches() { return &polymorphicInlineCaches; }
  200. PolymorphicCacheUtilizationArray * GetUtilArray() { return &polymorphicCacheUtilizationArray; }
  201. FunctionBody * GetFunctionBody() { return functionBody; }
  202. };
  203. class EntryPointPolymorphicInlineCacheInfo sealed
  204. {
  205. private:
  206. PolymorphicInlineCacheInfo selfInfo;
  207. SListBase<PolymorphicInlineCacheInfo*> inlineeInfo;
  208. static void SetPolymorphicInlineCache(PolymorphicInlineCacheInfo * polymorphicInlineCacheInfo, FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, byte polyCacheUtil);
  209. public:
  210. EntryPointPolymorphicInlineCacheInfo(FunctionBody * functionBody)
  211. : selfInfo(functionBody)
  212. {
  213. }
  214. PolymorphicInlineCacheInfo * GetSelfInfo() { return &selfInfo; }
  215. PolymorphicInlineCacheInfo * EnsureInlineeInfo(Recycler * recycler, FunctionBody * inlineeFunctionBody);
  216. PolymorphicInlineCacheInfo * GetInlineeInfo(FunctionBody * inlineeFunctionBody);
  217. void SetPolymorphicInlineCache(FunctionBody * functionBody, uint index, PolymorphicInlineCache * polymorphicInlineCache, bool isInlinee, byte polyCacheUtil);
  218. template <class Fn>
  219. void MapInlinees(Fn fn)
  220. {
  221. SListBase<PolymorphicInlineCacheInfo*>::Iterator iter(&inlineeInfo);
  222. while (iter.Next())
  223. {
  224. fn(iter.Data());
  225. }
  226. }
  227. };
  228. #pragma endregion
  229. #ifdef FIELD_ACCESS_STATS
  230. struct FieldAccessStats
  231. {
  232. uint totalInlineCacheCount;
  233. uint noInfoInlineCacheCount;
  234. uint monoInlineCacheCount;
  235. uint emptyMonoInlineCacheCount;
  236. uint polyInlineCacheCount;
  237. uint nullPolyInlineCacheCount;
  238. uint emptyPolyInlineCacheCount;
  239. uint ignoredPolyInlineCacheCount;
  240. uint highUtilPolyInlineCacheCount;
  241. uint lowUtilPolyInlineCacheCount;
  242. uint equivPolyInlineCacheCount;
  243. uint nonEquivPolyInlineCacheCount;
  244. uint disabledPolyInlineCacheCount;
  245. uint clonedMonoInlineCacheCount;
  246. uint clonedPolyInlineCacheCount;
  247. FieldAccessStats() :
  248. totalInlineCacheCount(0), noInfoInlineCacheCount(0), monoInlineCacheCount(0), emptyMonoInlineCacheCount(0),
  249. polyInlineCacheCount(0), nullPolyInlineCacheCount(0), emptyPolyInlineCacheCount(0), ignoredPolyInlineCacheCount(0),
  250. highUtilPolyInlineCacheCount(0), lowUtilPolyInlineCacheCount(0),
  251. equivPolyInlineCacheCount(0), nonEquivPolyInlineCacheCount(0), disabledPolyInlineCacheCount(0),
  252. clonedMonoInlineCacheCount(0), clonedPolyInlineCacheCount(0) {}
  253. void Add(FieldAccessStats* other);
  254. };
  255. typedef FieldAccessStats* FieldAccessStatsPtr;
  256. #else
  257. typedef void* FieldAccessStatsPtr;
  258. #endif
  259. #pragma region Entry point class declarations
  260. class ProxyEntryPointInfo: public ExpirableObject
  261. {
  262. public:
  263. // These are public because we don't manage them nor their consistency;
  264. // the user of this class does.
  265. void * address;
  266. ProxyEntryPointInfo(void* address, ThreadContext* context = nullptr):
  267. ExpirableObject(context),
  268. address(address)
  269. {
  270. }
  271. static DWORD GetAddressOffset() { return offsetof(ProxyEntryPointInfo, address); }
  272. virtual void Expire()
  273. {
  274. AssertMsg(false, "Expire called on object that doesn't support expiration");
  275. }
  276. virtual void EnterExpirableCollectMode()
  277. {
  278. AssertMsg(false, "EnterExpirableCollectMode called on object that doesn't support expiration");
  279. }
  280. virtual bool IsFunctionEntryPointInfo() const { return false; }
  281. };
  282. // Not thread safe.
  283. // Note that instances of this class are read from and written to from the
  284. // main and JIT threads.
  285. class EntryPointInfo : public ProxyEntryPointInfo
  286. {
  287. private:
  288. enum State : BYTE
  289. {
  290. NotScheduled, // code gen has not been scheduled
  291. CodeGenPending, // code gen job has been scheduled
  292. CodeGenQueued, // code gen has been queued and all the code gen data has been gathered.
  293. CodeGenRecorded, // backend completed, but job still pending
  294. CodeGenDone, // code gen job successfully completed
  295. JITCapReached, // workitem created but JIT cap reached
  296. PendingCleanup, // workitem needs to be cleaned up but couldn't for some reason- it'll be cleaned up at the next opportunity
  297. CleanedUp // the entry point has been cleaned up
  298. };
  299. #if ENABLE_NATIVE_CODEGEN
  300. class JitTransferData
  301. {
  302. friend EntryPointInfo;
  303. private:
  304. TypeRefSet* jitTimeTypeRefs;
  305. void** runtimeTypeRefs;
  306. int runtimeTypeRefCount;
  307. int propertyGuardCount;
  308. // This is a dynamically sized array of dynamically sized TypeGuardTransferEntries. It's heap allocated by the JIT
  309. // thread and lives until entry point is installed, at which point it is explicitly freed.
  310. TypeGuardTransferEntry* propertyGuardsByPropertyId;
  311. size_t propertyGuardsByPropertyIdPlusSize;
  312. // This is a dynamically sized array of dynamically sized CtorCacheGuardTransferEntry. It's heap allocated by the JIT
  313. // thread and lives until entry point is installed, at which point it is explicitly freed.
  314. CtorCacheGuardTransferEntry* ctorCacheGuardsByPropertyId;
  315. size_t ctorCacheGuardsByPropertyIdPlusSize;
  316. int equivalentTypeGuardCount;
  317. int lazyBailoutPropertyCount;
  318. // This is a dynamically sized array of JitEquivalentTypeGuards. It's heap allocated by the JIT thread and lives
  319. // until entry point is installed, at which point it is explicitly freed. We need it during installation so as to
  320. // swap the cache associated with each guard from the heap to the recycler (so the types in the cache are kept alive).
  321. JitEquivalentTypeGuard** equivalentTypeGuards;
  322. Js::PropertyId* lazyBailoutProperties;
  323. NativeCodeData* data;
  324. bool falseReferencePreventionBit;
  325. bool isReady;
  326. public:
  327. JitTransferData():
  328. jitTimeTypeRefs(nullptr), runtimeTypeRefCount(0), runtimeTypeRefs(nullptr),
  329. propertyGuardCount(0), propertyGuardsByPropertyId(nullptr), propertyGuardsByPropertyIdPlusSize(0),
  330. ctorCacheGuardsByPropertyId(nullptr), ctorCacheGuardsByPropertyIdPlusSize(0),
  331. equivalentTypeGuardCount(0), equivalentTypeGuards(nullptr), data(nullptr),
  332. falseReferencePreventionBit(true), isReady(false), lazyBailoutProperties(nullptr), lazyBailoutPropertyCount(0){}
  333. void AddJitTimeTypeRef(void* typeRef, Recycler* recycler);
  334. int GetRuntimeTypeRefCount() { return this->runtimeTypeRefCount; }
  335. void** GetRuntimeTypeRefs() { return this->runtimeTypeRefs; }
  336. void SetRuntimeTypeRefs(void** runtimeTypeRefs, int count) { this->runtimeTypeRefs = runtimeTypeRefs; this->runtimeTypeRefCount = count; }
  337. JitEquivalentTypeGuard** GetEquivalentTypeGuards() const { return this->equivalentTypeGuards; }
  338. void SetEquivalentTypeGuards(JitEquivalentTypeGuard** guards, int count)
  339. {
  340. this->equivalentTypeGuardCount = count;
  341. this->equivalentTypeGuards = guards;
  342. }
  343. void SetLazyBailoutProperties(Js::PropertyId* properties, int count)
  344. {
  345. this->lazyBailoutProperties = properties;
  346. this->lazyBailoutPropertyCount = count;
  347. }
  348. bool GetIsReady() { return this->isReady; }
  349. void SetIsReady() { this->isReady = true; }
  350. private:
  351. void EnsureJitTimeTypeRefs(Recycler* recycler);
  352. };
  353. NativeCodeData * data;
  354. CodeGenNumberChunk * numberChunks;
  355. SmallSpanSequence *nativeThrowSpanSequence;
  356. typedef JsUtil::BaseHashSet<RecyclerWeakReference<FunctionBody>*, Recycler, PowerOf2SizePolicy> WeakFuncRefSet;
  357. WeakFuncRefSet *weakFuncRefSet;
  358. // Need to keep strong references to the guards here so they don't get collected while the entry point is alive.
  359. typedef JsUtil::BaseDictionary<Js::PropertyId, PropertyGuard*, Recycler, PowerOf2SizePolicy> SharedPropertyGuardDictionary;
  360. SharedPropertyGuardDictionary* sharedPropertyGuards;
  361. typedef JsUtil::List<LazyBailOutRecord, HeapAllocator> BailOutRecordMap;
  362. BailOutRecordMap* bailoutRecordMap;
  363. // This array holds fake weak references to type property guards. We need it to zero out the weak references when the
  364. // entry point is finalized and the guards are about to be freed. Otherwise, if one of the guards was to be invalidated
  365. // from the thread context, we would AV trying to access freed memory. Note that the guards themselves are allocated by
  366. // NativeCodeData::Allocator and are kept alive by the data field. The weak references are recycler allocated, and so
  367. // the array must be recycler allocated also, so that the recycler doesn't collect the weak references.
  368. FakePropertyGuardWeakReference** propertyGuardWeakRefs;
  369. EquivalentTypeCache* equivalentTypeCaches;
  370. EntryPointInfo ** registeredEquivalentTypeCacheRef;
  371. int propertyGuardCount;
  372. int equivalentTypeCacheCount;
  373. #endif
  374. CodeGenWorkItem * workItem;
  375. void * nativeAddress;
  376. ptrdiff_t codeSize;
  377. bool isAsmJsFunction; // true if entrypoint is for asmjs function
  378. uintptr_t mModuleAddress; //asm Module address
  379. #ifdef FIELD_ACCESS_STATS
  380. FieldAccessStatsPtr fieldAccessStats;
  381. #endif
  382. protected:
  383. JavascriptLibrary* library;
  384. #if ENABLE_NATIVE_CODEGEN
  385. typedef JsUtil::List<NativeOffsetInlineeFramePair, HeapAllocator> InlineeFrameMap;
  386. InlineeFrameMap* inlineeFrameMap;
  387. #endif
  388. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  389. StackBackTrace* cleanupStack;
  390. #endif
  391. public:
  392. enum CleanupReason
  393. {
  394. NotCleanedUp,
  395. CodeGenFailedOOM,
  396. CodeGenFailedStackOverflow,
  397. CodeGenFailedAborted,
  398. NativeCodeInstallFailure,
  399. CleanUpForFinalize
  400. };
  401. uint frameHeight;
  402. private:
  403. #if ENABLE_NATIVE_CODEGEN
  404. typedef SListCounted<ConstructorCache*, Recycler> ConstructorCacheList;
  405. ConstructorCacheList* constructorCaches;
  406. EntryPointPolymorphicInlineCacheInfo * polymorphicInlineCacheInfo;
  407. // This field holds any recycler allocated references that must be kept alive until
  408. // we install the entry point. It is freed at that point, so anything that must survive
  409. // until the EntryPointInfo itself goes away, must be copied somewhere else.
  410. JitTransferData* jitTransferData;
  411. // If we pin types this array contains strong references to types, otherwise it holds weak references.
  412. void **runtimeTypeRefs;
  413. uint32 pendingPolymorphicCacheState;
  414. #endif
  415. State state; // Single state member so users can query state w/o a lock
  416. #if ENABLE_DEBUG_CONFIG_OPTIONS
  417. CleanupReason cleanupReason;
  418. #endif
  419. BYTE pendingInlinerVersion;
  420. bool isLoopBody;
  421. bool hasJittedStackClosure;
  422. #if ENABLE_NATIVE_CODEGEN
  423. ImplicitCallFlags pendingImplicitCallFlags;
  424. #endif
  425. public:
  426. virtual void Finalize(bool isShutdown) override;
  427. virtual bool IsFunctionEntryPointInfo() const override { return true; }
  428. protected:
  429. EntryPointInfo(void* address, JavascriptLibrary* library, void* validationCookie, ThreadContext* context = nullptr, bool isLoopBody = false) :
  430. ProxyEntryPointInfo(address, context),
  431. #if ENABLE_NATIVE_CODEGEN
  432. nativeThrowSpanSequence(nullptr), workItem(nullptr), weakFuncRefSet(nullptr),
  433. jitTransferData(nullptr), sharedPropertyGuards(nullptr), propertyGuardCount(0), propertyGuardWeakRefs(nullptr),
  434. equivalentTypeCacheCount(0), equivalentTypeCaches(nullptr), constructorCaches(nullptr), state(NotScheduled), data(nullptr),
  435. numberChunks(nullptr), polymorphicInlineCacheInfo(nullptr), runtimeTypeRefs(nullptr),
  436. isLoopBody(isLoopBody), hasJittedStackClosure(false), registeredEquivalentTypeCacheRef(nullptr), bailoutRecordMap(nullptr),
  437. #endif
  438. library(library), codeSize(0), nativeAddress(nullptr), isAsmJsFunction(false), validationCookie(validationCookie)
  439. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  440. , cleanupStack(nullptr)
  441. , cleanupReason(NotCleanedUp)
  442. #endif
  443. #if DBG_DUMP | defined(VTUNE_PROFILING)
  444. , nativeOffsetMaps(&HeapAllocator::Instance)
  445. #endif
  446. #ifdef FIELD_ACCESS_STATS
  447. , fieldAccessStats(nullptr)
  448. #endif
  449. {}
  450. virtual void ReleasePendingWorkItem() {};
  451. virtual void OnCleanup(bool isShutdown) = 0;
  452. #ifdef PERF_COUNTERS
  453. virtual void OnRecorded() = 0;
  454. #endif
  455. private:
  456. State GetState() const
  457. {
  458. Assert(this->state >= NotScheduled && this->state <= CleanedUp);
  459. return this->state;
  460. }
  461. public:
  462. ScriptContext* GetScriptContext();
  463. virtual FunctionBody *GetFunctionBody() const = 0;
  464. #if ENABLE_NATIVE_CODEGEN
  465. EntryPointPolymorphicInlineCacheInfo * EnsurePolymorphicInlineCacheInfo(Recycler * recycler, FunctionBody * functionBody);
  466. EntryPointPolymorphicInlineCacheInfo * GetPolymorphicInlineCacheInfo() { return polymorphicInlineCacheInfo; }
  467. JitTransferData* GetJitTransferData() { return this->jitTransferData; }
  468. JitTransferData* EnsureJitTransferData(Recycler* recycler);
  469. #ifdef FIELD_ACCESS_STATS
  470. FieldAccessStats* GetFieldAccessStats() { return this->fieldAccessStats; }
  471. FieldAccessStats* EnsureFieldAccessStats(Recycler* recycler);
  472. #endif
  473. void PinTypeRefs(ScriptContext* scriptContext);
  474. void InstallGuards(ScriptContext* scriptContext);
  475. #endif
  476. void Cleanup(bool isShutdown, bool captureCleanupStack);
  477. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  478. void CaptureCleanupStackTrace();
  479. #endif
  480. bool IsNotScheduled() const
  481. {
  482. return this->GetState() == NotScheduled;
  483. }
  484. bool IsCodeGenPending() const
  485. {
  486. return this->GetState() == CodeGenPending;
  487. }
  488. bool IsNativeCode() const
  489. {
  490. #if ENABLE_NATIVE_CODEGEN
  491. return this->GetState() == CodeGenRecorded ||
  492. this->GetState() == CodeGenDone;
  493. #else
  494. return false;
  495. #endif
  496. }
  497. bool IsCodeGenDone() const
  498. {
  499. #if ENABLE_NATIVE_CODEGEN
  500. return this->GetState() == CodeGenDone;
  501. #else
  502. return false;
  503. #endif
  504. }
  505. bool IsCodeGenQueued() const
  506. {
  507. #if ENABLE_NATIVE_CODEGEN
  508. return this->GetState() == CodeGenQueued;
  509. #else
  510. return false;
  511. #endif
  512. }
  513. bool IsJITCapReached() const
  514. {
  515. #if ENABLE_NATIVE_CODEGEN
  516. return this->GetState() == JITCapReached;
  517. #else
  518. return false;
  519. #endif
  520. }
  521. bool IsCleanedUp() const
  522. {
  523. return this->GetState() == CleanedUp;
  524. }
  525. bool IsPendingCleanup() const
  526. {
  527. return this->GetState() == PendingCleanup;
  528. }
  529. void SetPendingCleanup()
  530. {
  531. this->state = PendingCleanup;
  532. }
  533. #if ENABLE_DEBUG_CONFIG_OPTIONS
  534. void SetCleanupReason(CleanupReason reason)
  535. {
  536. this->cleanupReason = reason;
  537. }
  538. #endif
  539. bool IsLoopBody() const
  540. {
  541. return this->isLoopBody;
  542. }
  543. #if ENABLE_NATIVE_CODEGEN
  544. bool HasJittedStackClosure() const
  545. {
  546. return this->hasJittedStackClosure;
  547. }
  548. void SetHasJittedStackClosure()
  549. {
  550. this->hasJittedStackClosure = true;
  551. }
  552. #endif
  553. #ifndef TEMP_DISABLE_ASMJS
  554. void SetModuleAddress(uintptr_t moduleAddress)
  555. {
  556. Assert(this->GetIsAsmJSFunction());
  557. Assert(moduleAddress);
  558. mModuleAddress = moduleAddress;
  559. }
  560. uintptr_t GetModuleAddress()const
  561. {
  562. Assert(this->GetIsAsmJSFunction());
  563. Assert(mModuleAddress); // module address should not be null
  564. return mModuleAddress;
  565. }
  566. #endif
  567. void Reset(bool resetStateToNotScheduled = true);
  568. #if ENABLE_NATIVE_CODEGEN
  569. void SetCodeGenPending(CodeGenWorkItem * workItem)
  570. {
  571. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  572. Assert(workItem != nullptr);
  573. this->workItem = workItem;
  574. this->state = CodeGenPending;
  575. }
  576. void SetCodeGenPending()
  577. {
  578. Assert(this->GetState() == CodeGenQueued);
  579. this->state = CodeGenPending;
  580. }
  581. void SetCodeGenQueued()
  582. {
  583. Assert(this->GetState() == CodeGenPending);
  584. this->state = CodeGenQueued;
  585. }
  586. void RevertToNotScheduled()
  587. {
  588. Assert(this->GetState() == CodeGenPending);
  589. Assert(this->workItem != nullptr);
  590. this->workItem = nullptr;
  591. this->state = NotScheduled;
  592. }
  593. void SetCodeGenPendingWithStackAllocatedWorkItem()
  594. {
  595. Assert(this->GetState() == NotScheduled || this->GetState() == CleanedUp);
  596. this->workItem = nullptr;
  597. this->state = CodeGenPending;
  598. }
  599. void SetCodeGenRecorded(void * nativeAddress, ptrdiff_t codeSize,
  600. NativeCodeData * data, NativeCodeData * transferData, CodeGenNumberChunk * numberChunks)
  601. {
  602. Assert(this->GetState() == CodeGenQueued);
  603. Assert(nativeAddress != nullptr);
  604. Assert(codeSize > 0);
  605. Assert(this->jitTransferData != nullptr || transferData == nullptr);
  606. this->nativeAddress = (void *)nativeAddress;
  607. this->codeSize = codeSize;
  608. this->data = data;
  609. if (transferData != nullptr)
  610. {
  611. this->jitTransferData->data = transferData;
  612. }
  613. this->numberChunks = numberChunks;
  614. this->state = CodeGenRecorded;
  615. #ifdef PERF_COUNTERS
  616. this->OnRecorded();
  617. #endif
  618. }
  619. void SetCodeGenDone()
  620. {
  621. Assert(this->GetState() == CodeGenRecorded);
  622. this->state = CodeGenDone;
  623. this->workItem = nullptr;
  624. }
  625. void SetJITCapReached()
  626. {
  627. Assert(this->GetState() == CodeGenQueued);
  628. this->state = JITCapReached;
  629. this->workItem = nullptr;
  630. }
  631. SmallSpanSequence* GetNativeThrowSpanSequence() const
  632. {
  633. Assert(this->GetState() != NotScheduled);
  634. Assert(this->GetState() != CleanedUp);
  635. return nativeThrowSpanSequence;
  636. }
  637. void SetNativeThrowSpanSequence(SmallSpanSequence* seq)
  638. {
  639. Assert(this->GetState() == CodeGenQueued);
  640. Assert(this->nativeThrowSpanSequence == nullptr);
  641. nativeThrowSpanSequence = seq;
  642. }
  643. bool IsInNativeAddressRange(DWORD_PTR codeAddress) {
  644. return (IsNativeCode() &&
  645. codeAddress >= GetNativeAddress() &&
  646. codeAddress < GetNativeAddress() + GetCodeSize());
  647. }
  648. #endif
  649. DWORD_PTR GetNativeAddress() const
  650. {
  651. // need the assert to skip for asmjsFunction as nativeAddress can be interpreter too for asmjs
  652. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone || this->isAsmJsFunction);
  653. return (DWORD_PTR)this->nativeAddress;
  654. }
  655. ptrdiff_t GetCodeSize() const
  656. {
  657. Assert(this->GetState() == CodeGenRecorded || this->GetState() == CodeGenDone);
  658. return codeSize;
  659. }
  660. CodeGenWorkItem * GetWorkItem() const
  661. {
  662. State state = this->GetState();
  663. Assert(state != NotScheduled || this->workItem == nullptr);
  664. Assert(state == CleanedUp && this->workItem == nullptr ||
  665. state != CleanedUp);
  666. if (state == PendingCleanup)
  667. {
  668. return nullptr;
  669. }
  670. return this->workItem;
  671. }
  672. #ifndef TEMP_DISABLE_ASMJS
  673. // set code size, used by TJ to set the code size
  674. void SetCodeSize(ptrdiff_t size)
  675. {
  676. Assert(isAsmJsFunction);
  677. this->codeSize = size;
  678. }
  679. void SetNativeAddress(void* address)
  680. {
  681. Assert(isAsmJsFunction);
  682. this->nativeAddress = address;
  683. }
  684. void SetIsAsmJSFunction(bool value)
  685. {
  686. this->isAsmJsFunction = value;
  687. }
  688. #endif
  689. bool GetIsAsmJSFunction()const
  690. {
  691. return this->isAsmJsFunction;
  692. }
  693. #ifndef TEMP_DISABLE_ASMJS
  694. void SetTJCodeGenDone()
  695. {
  696. Assert(isAsmJsFunction);
  697. this->state = CodeGenDone;
  698. this->workItem = nullptr;
  699. }
  700. #endif
  701. #if ENABLE_NATIVE_CODEGEN
  702. void AddWeakFuncRef(RecyclerWeakReference<FunctionBody> *weakFuncRef, Recycler *recycler);
  703. WeakFuncRefSet *EnsureWeakFuncRefSet(Recycler *recycler);
  704. void EnsureIsReadyToCall();
  705. void ProcessJitTransferData();
  706. void ResetOnNativeCodeInstallFailure();
  707. virtual void OnNativeCodeInstallFailure() = 0;
  708. Js::PropertyGuard* RegisterSharedPropertyGuard(Js::PropertyId propertyId, ScriptContext* scriptContext);
  709. bool HasSharedPropertyGuards() { return this->sharedPropertyGuards != nullptr; }
  710. bool HasSharedPropertyGuard(Js::PropertyId propertyId);
  711. bool TryGetSharedPropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard*& guard);
  712. void RecordTypeGuards(int propertyGuardCount, TypeGuardTransferEntry* typeGuardTransferRecord, size_t typeGuardTransferPlusSize);
  713. void RecordCtorCacheGuards(CtorCacheGuardTransferEntry* ctorCacheTransferRecord, size_t ctorCacheTransferPlusSize);
  714. void FreePropertyGuards();
  715. void FreeJitTransferData();
  716. void RegisterEquivalentTypeCaches();
  717. void UnregisterEquivalentTypeCaches();
  718. bool ClearEquivalentTypeCaches();
  719. void RegisterConstructorCache(Js::ConstructorCache* constructorCache, Recycler* recycler);
  720. uint GetConstructorCacheCount() const { return this->constructorCaches != nullptr ? this->constructorCaches->Count() : 0; }
  721. uint32 GetPendingPolymorphicCacheState() const { return this->pendingPolymorphicCacheState; }
  722. void SetPendingPolymorphicCacheState(uint32 state) { this->pendingPolymorphicCacheState = state; }
  723. BYTE GetPendingInlinerVersion() const { return this->pendingInlinerVersion; }
  724. void SetPendingInlinerVersion(BYTE version) { this->pendingInlinerVersion = version; }
  725. ImplicitCallFlags GetPendingImplicitCallFlags() const { return this->pendingImplicitCallFlags; }
  726. void SetPendingImplicitCallFlags(ImplicitCallFlags flags) { this->pendingImplicitCallFlags = flags; }
  727. virtual void Invalidate(bool prolongEntryPoint) { Assert(false); }
  728. void RecordBailOutMap(JsUtil::List<LazyBailOutRecord, ArenaAllocator>* bailoutMap);
  729. void RecordInlineeFrameMap(JsUtil::List<NativeOffsetInlineeFramePair, ArenaAllocator>* tempInlineeFrameMap);
  730. InlineeFrameRecord* FindInlineeFrame(void* returnAddress);
  731. bool HasInlinees() { return this->frameHeight > 0; }
  732. void DoLazyBailout(BYTE** addressOfeturnAddress, Js::FunctionBody* functionBody, const PropertyRecord* propertyRecord);
  733. #endif
  734. #if DBG_DUMP
  735. public:
  736. #else if defined(VTUNE_PROFILING)
  737. private:
  738. #endif
  739. #if DBG_DUMP | defined(VTUNE_PROFILING)
  740. // NativeOffsetMap is public for DBG_DUMP, private for VTUNE_PROFILING
  741. struct NativeOffsetMap
  742. {
  743. uint32 statementIndex;
  744. regex::Interval nativeOffsetSpan;
  745. };
  746. private:
  747. JsUtil::List<NativeOffsetMap, HeapAllocator> nativeOffsetMaps;
  748. public:
  749. void RecordNativeMap(uint32 offset, uint32 statementIndex);
  750. int GetNativeOffsetMapCount() const;
  751. #endif
  752. #if DBG_DUMP && ENABLE_NATIVE_CODEGEN
  753. void DumpNativeOffsetMaps();
  754. void DumpNativeThrowSpanSequence();
  755. NativeOffsetMap* GetNativeOffsetMap(int index)
  756. {
  757. Assert(index >= 0);
  758. Assert(index < GetNativeOffsetMapCount());
  759. return &nativeOffsetMaps.Item(index);
  760. }
  761. #endif
  762. #ifdef VTUNE_PROFILING
  763. public:
  764. uint PopulateLineInfo(void* pLineInfo, FunctionBody* body);
  765. #endif
  766. protected:
  767. void* validationCookie;
  768. };
  769. class FunctionEntryPointInfo : public EntryPointInfo
  770. {
  771. public:
  772. FunctionProxy * functionProxy;
  773. FunctionEntryPointInfo* nextEntryPoint;
  774. // The offset on the native stack, from which the locals are located (Populated at RegAlloc phase). Used for debug purpose.
  775. int32 localVarSlotsOffset;
  776. // The offset which stores that any of the locals are changed from the debugger.
  777. int32 localVarChangedOffset;
  778. uint entryPointIndex;
  779. uint8 callsCount;
  780. uint8 lastCallsCount;
  781. bool nativeEntryPointProcessed;
  782. private:
  783. ExecutionMode jitMode;
  784. FunctionEntryPointInfo* mOldFunctionEntryPointInfo; // strong ref to oldEntryPointInfo(Int or TJ) in asm to ensure we don't collect it before JIT is completed
  785. bool mIsTemplatizedJitMode; // true only if in TJ mode, used only for debugging
  786. public:
  787. static const uint8 GetDecrCallCountPerBailout()
  788. {
  789. return (100 / (uint8)CONFIG_FLAG(RejitRatioLimit)) + 1;
  790. }
  791. FunctionEntryPointInfo(FunctionProxy * functionInfo, void * address, ThreadContext* context, void* validationCookie);
  792. #ifndef TEMP_DISABLE_ASMJS
  793. //AsmJS Support
  794. void SetOldFunctionEntryPointInfo(FunctionEntryPointInfo* entrypointInfo);
  795. FunctionEntryPointInfo* GetOldFunctionEntryPointInfo()const;
  796. void SetIsTJMode(bool value);
  797. bool GetIsTJMode()const;
  798. //End AsmJS Support
  799. #endif
  800. virtual FunctionBody *GetFunctionBody() const override;
  801. #if ENABLE_NATIVE_CODEGEN
  802. ExecutionMode GetJitMode() const;
  803. void SetJitMode(const ExecutionMode jitMode);
  804. virtual void Invalidate(bool prolongEntryPoint) override;
  805. virtual void Expire() override;
  806. virtual void EnterExpirableCollectMode() override;
  807. virtual void OnNativeCodeInstallFailure() override;
  808. #endif
  809. virtual void OnCleanup(bool isShutdown) override;
  810. virtual void ReleasePendingWorkItem() override;
  811. #ifdef PERF_COUNTERS
  812. virtual void OnRecorded() override;
  813. #endif
  814. };
  815. class LoopEntryPointInfo : public EntryPointInfo
  816. {
  817. public:
  818. LoopHeader* loopHeader;
  819. LoopEntryPointInfo(LoopHeader* loopHeader, Js::JavascriptLibrary* library, void* validationCookie) :
  820. loopHeader(loopHeader), mIsTemplatizedJitMode(false),EntryPointInfo(nullptr, library, validationCookie, /*threadContext*/ nullptr, /*isLoopBody*/ true)
  821. #ifdef BGJIT_STATS
  822. ,used(false)
  823. #endif
  824. { }
  825. virtual FunctionBody *GetFunctionBody() const override;
  826. virtual void OnCleanup(bool isShutdown) override;
  827. #if ENABLE_NATIVE_CODEGEN
  828. virtual void OnNativeCodeInstallFailure() override;
  829. #endif
  830. #ifndef TEMP_DISABLE_ASMJS
  831. void SetIsTJMode(bool value)
  832. {
  833. Assert(this->GetIsAsmJSFunction());
  834. mIsTemplatizedJitMode = value;
  835. }
  836. bool GetIsTJMode()const
  837. {
  838. return mIsTemplatizedJitMode;
  839. };
  840. #endif
  841. #ifdef PERF_COUNTERS
  842. virtual void OnRecorded() override;
  843. #endif
  844. #ifdef BGJIT_STATS
  845. bool IsUsed() const
  846. {
  847. return this->used;
  848. }
  849. void MarkAsUsed()
  850. {
  851. this->used = true;
  852. }
  853. #endif
  854. private:
  855. #ifdef BGJIT_STATS
  856. bool used;
  857. #endif
  858. bool mIsTemplatizedJitMode;
  859. };
  860. typedef RecyclerWeakReference<FunctionEntryPointInfo> FunctionEntryPointWeakRef;
  861. typedef SynchronizableList<FunctionEntryPointWeakRef*, JsUtil::List<FunctionEntryPointWeakRef*>> FunctionEntryPointList;
  862. typedef SynchronizableList<LoopEntryPointInfo*, JsUtil::List<LoopEntryPointInfo*>> LoopEntryPointList;
  863. #pragma endregion
  864. struct LoopHeader
  865. {
  866. private:
  867. LoopEntryPointList* entryPoints;
  868. public:
  869. uint startOffset;
  870. uint endOffset;
  871. uint interpretCount;
  872. uint profiledLoopCounter;
  873. bool isNested;
  874. bool isInTry;
  875. FunctionBody * functionBody;
  876. #if DBG_DUMP
  877. uint nativeCount;
  878. #endif
  879. static const uint NoLoop = (uint)-1;
  880. static const uint GetOffsetOfProfiledLoopCounter() { return offsetof(LoopHeader, profiledLoopCounter); }
  881. static const uint GetOffsetOfInterpretCount() { return offsetof(LoopHeader, interpretCount); }
  882. bool Contains(Js::LoopHeader * loopHeader) const
  883. {
  884. return (this->startOffset <= loopHeader->startOffset && loopHeader->endOffset <= this->endOffset);
  885. }
  886. bool Contains(uint offset) const
  887. {
  888. return this->startOffset <= offset && offset < this->endOffset;
  889. }
  890. void * GetCurrentEntryPoint() const
  891. {
  892. LoopEntryPointInfo * entryPoint = GetCurrentEntryPointInfo();
  893. if (entryPoint != nullptr)
  894. {
  895. return this->entryPoints->Item(this->GetCurrentEntryPointIndex())->address;
  896. }
  897. return nullptr;
  898. }
  899. LoopEntryPointInfo * GetCurrentEntryPointInfo() const
  900. {
  901. Assert(this->entryPoints->Count() > 0);
  902. return this->entryPoints->Item(this->GetCurrentEntryPointIndex());
  903. }
  904. uint GetByteCodeCount()
  905. {
  906. return (endOffset - startOffset);
  907. }
  908. int GetCurrentEntryPointIndex() const
  909. {
  910. return this->entryPoints->Count() - 1;
  911. }
  912. LoopEntryPointInfo * GetEntryPointInfo(int index) const
  913. {
  914. return this->entryPoints->Item(index);
  915. }
  916. template <class Fn>
  917. void MapEntryPoints(Fn fn) const
  918. {
  919. if (this->entryPoints) // ETW rundown may call this before entryPoints initialization
  920. {
  921. this->entryPoints->Map([&](int index, LoopEntryPointInfo * entryPoint)
  922. {
  923. if (entryPoint != nullptr)
  924. {
  925. fn(index, entryPoint);
  926. }
  927. });
  928. }
  929. }
  930. template <class DebugSite, class Fn>
  931. HRESULT MapEntryPoints(DebugSite site, Fn fn) const // external debugging version
  932. {
  933. return Map(site, this->entryPoints, [&](int index, LoopEntryPointInfo * entryPoint)
  934. {
  935. if (entryPoint != nullptr)
  936. {
  937. fn(index, entryPoint);
  938. }
  939. });
  940. }
  941. void Init(FunctionBody * functionBody);
  942. #if ENABLE_NATIVE_CODEGEN
  943. int CreateEntryPoint();
  944. void ReleaseEntryPoints();
  945. #endif
  946. void ResetInterpreterCount()
  947. {
  948. this->interpretCount = 0;
  949. }
  950. void ResetProfiledLoopCounter()
  951. {
  952. this->profiledLoopCounter = 0;
  953. }
  954. };
  955. class FunctionProxy;
  956. #ifdef RECYCLER_WRITE_BARRIER
  957. CompileAssert(sizeof(WriteBarrierPtr<FunctionProxy>) == sizeof(FunctionProxy*));
  958. typedef WriteBarrierPtr<FunctionProxy>* FunctionProxyArray;
  959. typedef WriteBarrierPtr<FunctionProxy>* FunctionProxyPtrPtr;
  960. #else
  961. typedef FunctionProxy** FunctionProxyArray;
  962. typedef FunctionProxy** FunctionProxyPtrPtr;
  963. #endif
  964. //
  965. // FunctionProxy represents a user defined function
  966. // This could be either from a source file or the byte code cache
  967. // The function need not have been compiled yet- it could be parsed or compiled
  968. // at a later time
  969. //
  970. class FunctionProxy : public FunctionInfo
  971. {
  972. protected:
  973. FunctionProxy(JavascriptMethod entryPoint, Attributes attributes, int nestedCount, int derivedSize,
  974. LocalFunctionId functionId, ScriptContext* scriptContext, Utf8SourceInfo* utf8SourceInfo, uint functionNumber);
  975. DEFINE_VTABLE_CTOR_NO_REGISTER(FunctionProxy, FunctionInfo);
  976. public:
  977. enum SetDisplayNameFlags
  978. {
  979. SetDisplayNameFlagsNone = 0,
  980. SetDisplayNameFlagsDontCopy = 1,
  981. SetDisplayNameFlagsRecyclerAllocated = 2
  982. };
  983. typedef RecyclerWeakReference<DynamicType> FunctionTypeWeakRef;
  984. typedef JsUtil::List<FunctionTypeWeakRef*, Recycler, false, WeakRefFreeListedRemovePolicy> FunctionTypeWeakRefList;
  985. uint32 GetSourceContextId() const;
  986. wchar_t* GetDebugNumberSet(wchar(&bufferToWriteTo)[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]) const;
  987. bool GetIsTopLevel() { return m_isTopLevel; }
  988. void SetIsTopLevel(bool set) { m_isTopLevel = set; }
  989. bool GetIsAnonymousFunction() const { return this->GetDisplayName() == Js::Constants::AnonymousFunction; }
  990. uint GetNestedCount() const { return m_nestedCount; }
  991. void Copy(FunctionProxy* other);
  992. ParseableFunctionInfo* EnsureDeserialized();
  993. ScriptContext* GetScriptContext() const;
  994. Utf8SourceInfo* GetUtf8SourceInfo() const { return this->m_utf8SourceInfo; }
  995. void SetReferenceInParentFunction(FunctionProxyPtrPtr reference);
  996. void UpdateReferenceInParentFunction(FunctionProxy* newFunctionInfo);
  997. DWORD_PTR GetSecondaryHostSourceContext() const;
  998. DWORD_PTR GetHostSourceContext() const;
  999. SourceContextInfo * GetSourceContextInfo() const;
  1000. SRCINFO const * GetHostSrcInfo() const;
  1001. uint GetFunctionNumber() const { return m_functionNumber; }
  1002. virtual void Finalize(bool isShutdown) override;
  1003. void UpdateFunctionBodyImpl(FunctionBody* body);
  1004. bool IsFunctionBody() const;
  1005. ProxyEntryPointInfo* GetDefaultEntryPointInfo() const;
  1006. ScriptFunctionType * GetDeferredPrototypeType() const;
  1007. ScriptFunctionType * EnsureDeferredPrototypeType();
  1008. JavascriptMethod GetDirectEntryPoint(ProxyEntryPointInfo* entryPoint) const;
  1009. // Function object type list methods
  1010. FunctionTypeWeakRefList* EnsureFunctionObjectTypeList();
  1011. void RegisterFunctionObjectType(DynamicType* functionType);
  1012. template <typename Fn>
  1013. void MapFunctionObjectTypes(Fn func);
  1014. static uint GetOffsetOfDeferredPrototypeType() { return offsetof(Js::FunctionProxy, deferredPrototypeType); }
  1015. static Js::ScriptFunctionType * EnsureFunctionProxyDeferredPrototypeType(FunctionProxy * proxy)
  1016. {
  1017. return proxy->EnsureDeferredPrototypeType();
  1018. }
  1019. void SetIsPublicLibraryCode() { m_isPublicLibraryCode = true; }
  1020. bool IsPublicLibraryCode() const { return m_isPublicLibraryCode; }
  1021. #if DBG
  1022. bool HasValidEntryPoint() const;
  1023. bool HasValidProfileEntryPoint() const;
  1024. bool HasValidNonProfileEntryPoint() const;
  1025. #endif
  1026. virtual void SetDisplayName(const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) = 0;
  1027. virtual const wchar_t* GetDisplayName() const = 0;
  1028. virtual uint GetDisplayNameLength() const = 0;
  1029. virtual uint GetShortDisplayNameOffset() const = 0;
  1030. static const wchar_t* WrapWithBrackets(const wchar_t* name, charcount_t sz, ScriptContext* scriptContext);
  1031. // Used only in the library function stringify (toString, DiagGetValueString).
  1032. // If we need more often to give the short name, we should create a member variable which points to the short name
  1033. // this is also now being used for function.name.
  1034. const wchar_t* GetShortDisplayName(charcount_t * shortNameLength);
  1035. bool IsJitLoopBodyPhaseEnabled() const
  1036. {
  1037. // Consider: Allow JitLoopBody in generator functions for loops that do not yield.
  1038. return !PHASE_OFF(JITLoopBodyPhase, this) && DoFullJit() && !this->IsGenerator();
  1039. }
  1040. bool IsJitLoopBodyPhaseForced() const
  1041. {
  1042. return
  1043. IsJitLoopBodyPhaseEnabled() &&
  1044. (
  1045. PHASE_FORCE(JITLoopBodyPhase, this)
  1046. #ifdef ENABLE_PREJIT
  1047. || Configuration::Global.flags.Prejit
  1048. #endif
  1049. );
  1050. }
  1051. ULONG GetHostStartLine() const;
  1052. ULONG GetHostStartColumn() const;
  1053. bool DoFullJit() const
  1054. {
  1055. return !PHASE_OFF(FullJitPhase, this);
  1056. }
  1057. protected:
  1058. // Static method(s)
  1059. static void SetDisplayName(const wchar_t* srcName, WriteBarrierPtr<const wchar_t>* destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  1060. static bool SetDisplayName(const wchar_t* srcName, const wchar_t** destName, uint displayNameLength, ScriptContext * scriptContext, SetDisplayNameFlags flags = SetDisplayNameFlagsNone);
  1061. static bool IsConstantFunctionName(const wchar_t* srcName);
  1062. protected:
  1063. NoWriteBarrierPtr<ScriptContext> m_scriptContext; // Memory context for this function body
  1064. WriteBarrierPtr<Utf8SourceInfo> m_utf8SourceInfo;
  1065. // WriteBarrier-TODO: Consider changing this to NoWriteBarrierPtr, and skip tagging- also, tagging is likely unnecessary since that pointer in question is likely not resolvable
  1066. FunctionProxyPtrPtr m_referenceInParentFunction; // Reference to nested function reference to this function in the parent function body (tagged to not be actual reference)
  1067. WriteBarrierPtr<ScriptFunctionType> deferredPrototypeType;
  1068. // Script function types not including the deferred prototype type
  1069. WriteBarrierPtr<FunctionTypeWeakRefList> m_functionObjectTypeList;
  1070. WriteBarrierPtr<ProxyEntryPointInfo> m_defaultEntryPointInfo; // The default entry point info for the function proxy
  1071. NoWriteBarrierField<uint> m_derivedSize;
  1072. NoWriteBarrierField<uint> m_functionNumber; // Per thread global function number
  1073. #define DEFINE_FUNCTION_PROXY_FIELDS 1
  1074. #define CURRENT_ACCESS_MODIFIER protected:
  1075. #include "SerializableFunctionFields.h"
  1076. bool m_isTopLevel : 1; // Indicates that this function is top-level function, currently being used in script profiler and debugger
  1077. bool m_isPublicLibraryCode: 1; // Indicates this function is public boundary library code that should be visible in JS stack
  1078. void CleanupFunctionProxyCounters()
  1079. {
  1080. PERF_COUNTER_DEC(Code, TotalFunction);
  1081. }
  1082. ULONG ComputeAbsoluteLineNumber(ULONG relativeLineNumber) const;
  1083. ULONG ComputeAbsoluteColumnNumber(ULONG relativeLineNumber, ULONG relativeColumnNumber) const;
  1084. ULONG GetLineNumberInHostBuffer(ULONG relativeLineNumber) const;
  1085. private:
  1086. ScriptFunctionType * AllocDeferredPrototypeType();
  1087. };
  1088. // Represents a function from the byte code cache which will
  1089. // be deserialized upon use
  1090. class DeferDeserializeFunctionInfo: public FunctionProxy
  1091. {
  1092. friend struct ByteCodeSerializer;
  1093. private:
  1094. DeferDeserializeFunctionInfo(int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, Attributes attributes);
  1095. public:
  1096. static DeferDeserializeFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, ByteCodeCache* byteCodeCache, const byte* serializedFunction, Utf8SourceInfo* utf8SourceInfo, const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, NativeModule *nativeModule, Attributes attributes);
  1097. virtual void Finalize(bool isShutdown) override;
  1098. FunctionBody* Deserialize();
  1099. virtual const wchar_t* GetDisplayName() const override;
  1100. void SetDisplayName(const wchar_t* displayName);
  1101. virtual void SetDisplayName(const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1102. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1103. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1104. LPCWSTR GetSourceInfo(int& lineNumber, int& columnNumber) const;
  1105. private:
  1106. const byte* m_functionBytes;
  1107. ByteCodeCache* m_cache;
  1108. const wchar_t * m_displayName; // Optional name
  1109. uint m_displayNameLength;
  1110. uint m_displayShortNameOffset;
  1111. NativeModule *m_nativeModule;
  1112. };
  1113. class ParseableFunctionInfo: public FunctionProxy
  1114. {
  1115. friend class ByteCodeBufferReader;
  1116. protected:
  1117. ParseableFunctionInfo(JavascriptMethod method, int nestedFunctionCount, int derivedSize, LocalFunctionId functionId, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext, uint functionNumber, const wchar_t* displayName, uint m_displayNameLength, uint displayShortNameOffset, Attributes attributes, Js::PropertyRecordList* propertyRecordList);
  1118. public:
  1119. static ParseableFunctionInfo* New(ScriptContext* scriptContext, int nestedFunctionCount, LocalFunctionId functionId, Utf8SourceInfo* utf8SourceInfo, const wchar_t* displayName, uint m_displayNameLength, uint displayShortNameOffset, Js::PropertyRecordList* propertyRecordList, Attributes attributes);
  1120. DEFINE_VTABLE_CTOR_NO_REGISTER(ParseableFunctionInfo, FunctionProxy);
  1121. FunctionBody* Parse(ScriptFunction ** functionRef = nullptr, bool isByteCodeDeserialization = false);
  1122. #ifndef TEMP_DISABLE_ASMJS
  1123. FunctionBody* ParseAsmJs(Parser * p, __out CompileScriptException * se, __out ParseNodePtr * ptree);
  1124. #endif
  1125. virtual uint GetDisplayNameLength() const { return m_displayNameLength; }
  1126. virtual uint GetShortDisplayNameOffset() const { return m_displayShortNameOffset; }
  1127. bool GetIsDeclaration() const { return m_isDeclaration; }
  1128. void SetIsDeclaration(const bool is) { m_isDeclaration = is; }
  1129. bool GetIsAccessor() const { return m_isAccessor; }
  1130. void SetIsAccessor(const bool is) { m_isAccessor = is; }
  1131. bool GetIsGlobalFunc() const { return m_isGlobalFunc; }
  1132. void SetIsStaticNameFunction(const bool is) { m_isStaticNameFunction = is; }
  1133. bool GetIsStaticNameFunction() const { return m_isStaticNameFunction; }
  1134. void SetIsNamedFunctionExpression(const bool is) { m_isNamedFunctionExpression = is; }
  1135. bool GetIsNamedFunctionExpression() const { return m_isNamedFunctionExpression; }
  1136. void SetIsNameIdentifierRef (const bool is) { m_isNameIdentifierRef = is; }
  1137. bool GetIsNameIdentifierRef () const { return m_isNameIdentifierRef ; }
  1138. // Fake global ->
  1139. // 1) new Function code's global code
  1140. // 2) global code generated from the reparsing deferred parse function
  1141. bool IsFakeGlobalFunc(ulong flags) const;
  1142. void SetIsGlobalFunc(bool is) { m_isGlobalFunc = is; }
  1143. bool GetIsStrictMode() const { return m_isStrictMode; }
  1144. void SetIsStrictMode() { m_isStrictMode = true; }
  1145. bool GetIsAsmjsMode() const { return m_isAsmjsMode; }
  1146. void SetIsAsmjsMode(bool value)
  1147. {
  1148. m_isAsmjsMode = value;
  1149. #if DBG
  1150. if (value)
  1151. {
  1152. m_wasEverAsmjsMode = true;
  1153. }
  1154. #endif
  1155. }
  1156. bool GetHasImplicitArgIns() { return m_hasImplicitArgIns; }
  1157. void SetHasImplicitArgIns(bool has) { m_hasImplicitArgIns = has; }
  1158. ulong GetGrfscr() const;
  1159. void SetGrfscr(ulong grfscr);
  1160. ///----------------------------------------------------------------------------
  1161. ///
  1162. /// ParseableFunctionInfo::GetInParamsCount
  1163. ///
  1164. /// GetInParamsCount() returns the number of "in parameters" that have
  1165. /// currently been declared for this function:
  1166. /// - If this is "RegSlot_VariableCount", the function takes a variable number
  1167. /// of parameters.
  1168. ///
  1169. /// Consider: Change to store type information about parameters- names, type,
  1170. /// direction, etc.
  1171. ///
  1172. ///----------------------------------------------------------------------------
  1173. ArgSlot GetInParamsCount() const { return m_inParamCount; }
  1174. void SetInParamsCount(ArgSlot newInParamCount);
  1175. ArgSlot GetReportedInParamsCount() const;
  1176. void SetReportedInParamsCount(ArgSlot newReportedInParamCount);
  1177. void ResetInParams();
  1178. ScopeInfo* GetScopeInfo() const { return this->m_scopeInfo; }
  1179. void SetScopeInfo(ScopeInfo* scopeInfo) { this->m_scopeInfo = scopeInfo; }
  1180. PropertyId GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName);
  1181. bool IsTrackedPropertyId(PropertyId pid);
  1182. Js::PropertyRecordList* GetBoundPropertyRecords() { return this->m_boundPropertyRecords; }
  1183. void SetBoundPropertyRecords(Js::PropertyRecordList* boundPropertyRecords)
  1184. {
  1185. Assert(this->m_boundPropertyRecords == nullptr);
  1186. this->m_boundPropertyRecords = boundPropertyRecords;
  1187. }
  1188. void ClearBoundPropertyRecords()
  1189. {
  1190. this->m_boundPropertyRecords = nullptr;
  1191. }
  1192. ParseableFunctionInfo* Clone(ScriptContext *scriptContext, uint sourceIndex = Js::Constants::InvalidSourceIndex);
  1193. ParseableFunctionInfo* CopyFunctionInfoInto(ScriptContext *scriptContext, Js::ParseableFunctionInfo* functionInfo, uint sourceIndex = Js::Constants::InvalidSourceIndex);
  1194. void CloneSourceInfo(ScriptContext* scriptContext, const ParseableFunctionInfo& other, ScriptContext* othersScriptContext, uint sourceIndex);
  1195. void SetInitialDefaultEntryPoint();
  1196. void SetDeferredParsingEntryPoint();
  1197. void SetEntryPoint(ProxyEntryPointInfo* entryPoint, Js::JavascriptMethod address) {
  1198. entryPoint->address = address;
  1199. }
  1200. bool IsDynamicScript() const;
  1201. uint LengthInBytes() const { return m_cbLength; }
  1202. uint StartOffset() const;
  1203. ULONG GetLineNumber() const;
  1204. ULONG GetColumnNumber() const;
  1205. template <class T>
  1206. LPCWSTR GetSourceName(const T& sourceContextInfo) const;
  1207. template <class T>
  1208. static LPCWSTR GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction);
  1209. LPCWSTR GetSourceName() const;
  1210. ULONG GetRelativeLineNumber() const { return m_lineNumber; }
  1211. ULONG GetRelativeColumnNumber() const { return m_columnNumber; }
  1212. uint GetSourceIndex() const;
  1213. LPCUTF8 GetSource(const wchar_t* reason = nullptr) const;
  1214. charcount_t LengthInChars() const { return m_cchLength; }
  1215. charcount_t StartInDocument() const;
  1216. bool IsEval() const { return m_isEval; }
  1217. bool IsDynamicFunction() const;
  1218. bool GetDontInline() { return m_dontInline; }
  1219. void SetDontInline(bool is) { m_dontInline = is; }
  1220. LPCUTF8 GetStartOfDocument(const wchar_t* reason = nullptr) const;
  1221. bool IsReparsed() const { return m_reparsed; }
  1222. void SetReparsed(bool set) { m_reparsed = set; }
  1223. bool IsByteCodeDebugMode() { return isByteCodeDebugMode; }
  1224. void SetIsByteCodeDebugMode(bool set) { isByteCodeDebugMode = set; }
  1225. bool GetExternalDisplaySourceName(BSTR* sourceName);
  1226. void SetDoBackendArgumentsOptimization(bool set)
  1227. {
  1228. if (m_doBackendArgumentsOptimization)
  1229. {
  1230. m_doBackendArgumentsOptimization = set;
  1231. }
  1232. }
  1233. bool GetDoBackendArgumentsOptimization()
  1234. {
  1235. return m_doBackendArgumentsOptimization;
  1236. }
  1237. bool IsFunctionParsed()
  1238. {
  1239. return !IsDeferredParseFunction() || m_hasBeenParsed;
  1240. }
  1241. void SetFunctionParsed(bool hasBeenParsed)
  1242. {
  1243. m_hasBeenParsed = hasBeenParsed;
  1244. }
  1245. void SetSourceInfo(uint sourceIndex, ParseNodePtr node, bool isEval, bool isDynamicFunction);
  1246. void Copy(FunctionBody* other);
  1247. const wchar_t* GetExternalDisplayName() const;
  1248. //
  1249. // Algorithm to retrieve a function body's external display name. Template supports both
  1250. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1251. //
  1252. template <class T>
  1253. static const wchar_t* GetExternalDisplayName(const T* funcBody)
  1254. {
  1255. Assert(funcBody != nullptr);
  1256. Assert(funcBody->GetDisplayName() != nullptr);
  1257. return funcBody->GetDisplayName();
  1258. }
  1259. virtual const wchar_t* GetDisplayName() const override;
  1260. void SetDisplayName(const wchar_t* displayName);
  1261. virtual void SetDisplayName(const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, SetDisplayNameFlags flags = SetDisplayNameFlagsNone) override;
  1262. virtual void Finalize(bool isShutdown) override;
  1263. Var GetCachedSourceString()
  1264. {
  1265. return cachedSourceString;
  1266. }
  1267. void SetCachedSourceString(Var sourceString)
  1268. {
  1269. Assert(this->cachedSourceString == nullptr);
  1270. this->cachedSourceString = sourceString;
  1271. }
  1272. FunctionProxyArray GetNestedFuncArray();
  1273. FunctionProxy* GetNestedFunc(uint index);
  1274. FunctionProxyPtrPtr GetNestedFuncReference(uint index);
  1275. ParseableFunctionInfo* GetNestedFunctionForExecution(uint index);
  1276. void SetNestedFunc(FunctionProxy* nestedFunc, uint index, ulong flags);
  1277. void ClearNestedFunctionParentFunctionReference();
  1278. void SetCapturesThis() { attributes = (Attributes)(attributes | Attributes::CapturesThis); }
  1279. bool GetCapturesThis() { return (attributes & Attributes::CapturesThis) != 0; }
  1280. void BuildDeferredStubs(ParseNode *pnodeFnc);
  1281. DeferredFunctionStub *GetDeferredStubs() const { return this->deferredStubs; }
  1282. void SetDeferredStubs(DeferredFunctionStub *stub) { this->deferredStubs = stub; }
  1283. void RegisterFuncToDiag(ScriptContext * scriptContext, wchar_t const * pszTitle);
  1284. protected:
  1285. static HRESULT MapDeferredReparseError(HRESULT& hrParse, const CompileScriptException& se);
  1286. bool m_hasBeenParsed : 1; // Has function body been parsed- true for actual function bodies, false for deferparse
  1287. bool m_isDeclaration : 1;
  1288. bool m_isAccessor : 1; // Function is a property getter or setter
  1289. bool m_isStaticNameFunction : 1;
  1290. bool m_isNamedFunctionExpression : 1;
  1291. bool m_isNameIdentifierRef : 1;
  1292. bool m_isClassMember : 1;
  1293. bool m_isStrictMode : 1;
  1294. bool m_isAsmjsMode : 1;
  1295. bool m_isAsmJsFunction : 1;
  1296. bool m_isGlobalFunc : 1;
  1297. bool m_doBackendArgumentsOptimization :1;
  1298. bool m_isEval : 1; // Source code is in 'eval'
  1299. bool m_isDynamicFunction : 1; // Source code is in 'Function'
  1300. bool m_hasImplicitArgIns : 1;
  1301. bool m_dontInline : 1; // Used by the JIT's inliner
  1302. // Indicates if the function has been reparsed for debug attach/detach scenario.
  1303. bool m_reparsed : 1;
  1304. bool isByteCodeDebugMode : 1; // Whether last time generated bytecode was generated for debug mode.
  1305. // This field is not required for deferred parsing but because our thunks can't handle offsets > 128 bytes
  1306. // yet, leaving this here for now. We can look at optimizing the function info and function proxy structures some
  1307. // more and also fix our thunks to handle 8 bit offsets
  1308. NoWriteBarrierField<bool> m_utf8SourceHasBeenSet; // start of UTF8-encoded source
  1309. NoWriteBarrierField<uint> m_sourceIndex; // index into the scriptContext's list of saved sources
  1310. #if DYNAMIC_INTERPRETER_THUNK
  1311. void* m_dynamicInterpreterThunk; // Unique 'thunk' for every interpreted function - used for ETW symbol decoding.
  1312. #endif
  1313. NoWriteBarrierField<uint> m_cbStartOffset; // pUtf8Source is this many bytes from the start of the scriptContext's source buffer.
  1314. // This is generally the same as m_cchStartOffset unless the buffer has a BOM
  1315. #define DEFINE_PARSEABLE_FUNCTION_INFO_FIELDS 1
  1316. #define CURRENT_ACCESS_MODIFIER protected:
  1317. #include "SerializableFunctionFields.h"
  1318. ULONG m_lineNumber;
  1319. ULONG m_columnNumber;
  1320. WriteBarrierPtr<const wchar_t> m_displayName; // Optional name
  1321. uint m_displayNameLength;
  1322. uint m_displayShortNameOffset;
  1323. WriteBarrierPtr<ScopeInfo> m_scopeInfo;
  1324. WriteBarrierPtr<PropertyRecordList> m_boundPropertyRecords;
  1325. WriteBarrierVar cachedSourceString;
  1326. WriteBarrierPtr<DeferredFunctionStub> deferredStubs;
  1327. public:
  1328. #if DBG
  1329. bool m_wasEverAsmjsMode; // has m_isAsmjsMode ever been true
  1330. NoWriteBarrierField<Js::LocalFunctionId> deferredParseNextFunctionId;
  1331. #endif
  1332. #if DBG
  1333. NoWriteBarrierField<UINT> scopeObjectSize; // If the scope is an activation object - its size
  1334. #endif
  1335. };
  1336. //
  1337. // Algorithm to retrieve a function body's source name (url). Template supports both
  1338. // local FunctionBody and ScriptDAC (debugging) scenarios.
  1339. //
  1340. template <class T>
  1341. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo) const
  1342. {
  1343. return GetSourceName<T>(sourceContextInfo, this->m_isEval, this->m_isDynamicFunction);
  1344. }
  1345. template <class T>
  1346. LPCWSTR ParseableFunctionInfo::GetSourceName(const T& sourceContextInfo, bool m_isEval, bool m_isDynamicFunction)
  1347. {
  1348. if (sourceContextInfo->IsDynamic())
  1349. {
  1350. if (m_isEval)
  1351. {
  1352. return Constants::EvalCode;
  1353. }
  1354. else if (m_isDynamicFunction)
  1355. {
  1356. return Constants::FunctionCode;
  1357. }
  1358. else
  1359. {
  1360. return Constants::UnknownScriptCode;
  1361. }
  1362. }
  1363. else
  1364. {
  1365. return sourceContextInfo->url;
  1366. }
  1367. }
  1368. class FunctionBody : public ParseableFunctionInfo
  1369. {
  1370. DEFINE_VTABLE_CTOR_NO_REGISTER(FunctionBody, ParseableFunctionInfo);
  1371. friend class ByteCodeBufferBuilder;
  1372. friend class ByteCodeBufferReader;
  1373. public:
  1374. // same as MachDouble, used in the Func.h
  1375. static const uint DIAGLOCALSLOTSIZE = 8;
  1376. struct StatementMap
  1377. {
  1378. StatementMap() : isSubexpression(false) {}
  1379. static StatementMap * New(Recycler* recycler)
  1380. {
  1381. return RecyclerNew(recycler, StatementMap);
  1382. }
  1383. regex::Interval sourceSpan;
  1384. regex::Interval byteCodeSpan;
  1385. bool isSubexpression;
  1386. };
  1387. // The type of StatementAdjustmentRecord.
  1388. // A bitmask that can be OR'ed of multiple values of the enum.
  1389. enum StatementAdjustmentType : ushort
  1390. {
  1391. SAT_None = 0,
  1392. // Specifies an adjustment for next statement when going from current to next.
  1393. // Used for transitioning from current stmt to next during normal control-flow,
  1394. // such as offset of Br after if-block when there is else block present,
  1395. // when throw happens inside if and we ignore exceptions (next statement in the list
  1396. // would be 'else' but we need to pass flow control to Br target rather than entering 'else').
  1397. SAT_FromCurrentToNext = 0x01,
  1398. // Specifies an adjustment for beginning of next statement.
  1399. // If there is adjustment record, the statement following it starts at specified offset and not at offset specified in statementMap.
  1400. // Used for set next statement from arbitrary location.
  1401. SAT_NextStatementStart = 0x02,
  1402. SAT_All = SAT_FromCurrentToNext | SAT_NextStatementStart
  1403. };
  1404. class StatementAdjustmentRecord
  1405. {
  1406. uint m_byteCodeOffset;
  1407. StatementAdjustmentType m_adjustmentType;
  1408. public:
  1409. StatementAdjustmentRecord();
  1410. StatementAdjustmentRecord(StatementAdjustmentType type, int byteCodeOffset);
  1411. StatementAdjustmentRecord(const StatementAdjustmentRecord& other);
  1412. uint GetByteCodeOffset();
  1413. StatementAdjustmentType GetAdjustmentType();
  1414. };
  1415. // Offset and entry/exit of a block that must be processed in new interpreter frame rather than current.
  1416. // Used for try and catch blocks.
  1417. class CrossFrameEntryExitRecord
  1418. {
  1419. uint m_byteCodeOffset;
  1420. // true means enter, false means exit.
  1421. bool m_isEnterBlock;
  1422. public:
  1423. CrossFrameEntryExitRecord();
  1424. CrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  1425. CrossFrameEntryExitRecord(const CrossFrameEntryExitRecord& other);
  1426. uint GetByteCodeOffset() const;
  1427. bool GetIsEnterBlock();
  1428. };
  1429. typedef JsUtil::List<Js::FunctionBody::StatementMap*> StatementMapList;
  1430. // Note: isLeaf = true template param below means that recycler should not be used to dispose the items.
  1431. typedef JsUtil::List<StatementAdjustmentRecord, Recycler, /* isLeaf = */ true> StatementAdjustmentRecordList;
  1432. typedef JsUtil::List<CrossFrameEntryExitRecord, Recycler, /* isLeaf = */ true> CrossFrameEntryExitRecordList;
  1433. // Contains recorded at bytecode generation time information about statements and try-catch blocks.
  1434. // Used by debugger.
  1435. struct AuxStatementData
  1436. {
  1437. // Contains statement adjustment data:
  1438. // For given bytecode, following statement needs an adjustment, see StatementAdjustmentType for details.
  1439. StatementAdjustmentRecordList* m_statementAdjustmentRecords;
  1440. // Contain data about entry/exit of blocks that cause processing in different interpreter stack frame, such as try or catch.
  1441. CrossFrameEntryExitRecordList* m_crossFrameBlockEntryExisRecords;
  1442. AuxStatementData();
  1443. };
  1444. class SourceInfo
  1445. {
  1446. friend class RemoteFunctionBody;
  1447. friend class ByteCodeBufferReader;
  1448. friend class ByteCodeBufferBuilder;
  1449. public:
  1450. SmallSpanSequence * pSpanSequence;
  1451. RegSlot frameDisplayRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1452. RegSlot objectRegister; // this register slot cannot be 0 so we use that sentinel value to indicate invalid
  1453. WriteBarrierPtr<ScopeObjectChain> pScopeObjectChain;
  1454. WriteBarrierPtr<ByteBlock> m_probeBackingBlock; // NULL if no Probes, otherwise a copy of the unmodified the byte-codeblock //Delay
  1455. int32 m_probeCount; // The number of installed probes (such as breakpoints).
  1456. // List of bytecode offset for the Branch bytecode.
  1457. WriteBarrierPtr<AuxStatementData> m_auxStatementData;
  1458. SourceInfo():
  1459. frameDisplayRegister(0),
  1460. objectRegister(0),
  1461. pScopeObjectChain(nullptr),
  1462. m_probeBackingBlock(nullptr),
  1463. m_probeCount(0),
  1464. m_auxStatementData(nullptr),
  1465. pSpanSequence(nullptr)
  1466. {
  1467. }
  1468. };
  1469. private:
  1470. WriteBarrierPtr<ByteBlock> auxBlock; // Optional auxiliary information
  1471. WriteBarrierPtr<ByteBlock> auxContextBlock; // Optional auxiliary context specific information
  1472. WriteBarrierPtr<ByteBlock> byteCodeBlock; // Function byte-code for script functions
  1473. WriteBarrierPtr<FunctionEntryPointList> entryPoints;
  1474. WriteBarrierPtr<Js::LoopHeader> loopHeaderArray;
  1475. WriteBarrierPtr<Var> m_constTable;
  1476. WriteBarrierPtr<FunctionCodeGenRuntimeData*> m_codeGenRuntimeData;
  1477. WriteBarrierPtr<FunctionCodeGenRuntimeData*> m_codeGenGetSetRuntimeData;
  1478. WriteBarrierPtr<void*> inlineCaches;
  1479. InlineCachePointerArray<PolymorphicInlineCache> polymorphicInlineCaches; // Contains the latest polymorphic inline caches
  1480. WriteBarrierPtr<PolymorphicInlineCache> polymorphicInlineCachesHead; // DList of all polymorphic inline caches that aren't finalized yet
  1481. WriteBarrierPtr<PropertyId> cacheIdToPropertyIdMap;
  1482. WriteBarrierPtr<PropertyId> referencedPropertyIdMap;
  1483. WriteBarrierPtr<UnifiedRegex::RegexPattern*>literalRegexes;
  1484. WriteBarrierPtr<AsmJsFunctionInfo> asmJsFunctionInfo;
  1485. WriteBarrierPtr<AsmJsModuleInfo> asmJsModuleInfo;
  1486. // For SourceInfo
  1487. WriteBarrierPtr<PropertyId> propertyIdsForScopeSlotArray;
  1488. // This is used for showing locals for the current frame.
  1489. WriteBarrierPtr<PropertyIdOnRegSlotsContainer> propertyIdOnRegSlotsContainer;
  1490. #if DBG
  1491. #define InlineCacheTypeNone 0x00
  1492. #define InlineCacheTypeInlineCache 0x01
  1493. #define InlineCacheTypeIsInst 0x02
  1494. WriteBarrierPtr<byte> m_inlineCacheTypes;
  1495. #endif
  1496. WriteBarrierPtr<StatementMapList> pStatementMaps;
  1497. public:
  1498. static DWORD GetConstTableOffset() { return offsetof(FunctionBody, m_constTable); }
  1499. static DWORD GetAuxiliaryDataOffset() { return offsetof(FunctionBody, auxBlock); }
  1500. static DWORD GetAuxiliaryContextDataOffset() { return offsetof(FunctionBody, auxContextBlock); }
  1501. static DWORD GetObjLiteralTypesOffset() { return offsetof(FunctionBody, objLiteralTypes); }
  1502. static DWORD GetInlineCachesOffset() { return offsetof(FunctionBody, inlineCaches); }
  1503. static DWORD GetInlineCacheCountOffset() { return offsetof(FunctionBody, inlineCacheCount); }
  1504. static DWORD GetLiteralRegexesOffset() { return offsetof(FunctionBody, literalRegexes); }
  1505. static DWORD GetDerivedSizeOffset() { return offsetof(FunctionBody, m_derivedSize); }
  1506. static DWORD GetReferencedPropertyIdMapOffset() { return offsetof(FunctionBody, referencedPropertyIdMap); }
  1507. static DWORD GetCacheIdToPropertyIdMapOffset() { return offsetof(FunctionBody, cacheIdToPropertyIdMap); }
  1508. static DWORD GetAsmJsTotalLoopCountOffset(){ return offsetof(FunctionBody, m_asmJsTotalLoopCount); }
  1509. #if DBG
  1510. int m_DEBUG_executionCount; // Count of outstanding on InterpreterStackFrame
  1511. bool m_nativeEntryPointIsInterpreterThunk; // NativeEntry entry point is in fact InterpreterThunk.
  1512. // Set by bgjit in OutOfMemory scenario during codegen.
  1513. #endif
  1514. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1515. NoWriteBarrierField<uint> regAllocStoreCount;
  1516. NoWriteBarrierField<uint> regAllocLoadCount;
  1517. NoWriteBarrierField<uint> callCountStats;
  1518. #endif
  1519. NoWriteBarrierField<uint> interpretedCount;
  1520. NoWriteBarrierField<uint> loopInterpreterLimit;
  1521. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1522. //
  1523. // If you add compile-time attributes to this set, be sure to add them to the attributes that are
  1524. // copied in FunctionBody::Clone
  1525. //
  1526. SourceInfo m_sourceInfo; // position of the source
  1527. // Data needed by profiler:
  1528. NoWriteBarrierField<uint> m_uScriptId; // Delay //Script Block it belongs to. This is function no. of the global function created by engine for each block
  1529. #if DBG
  1530. NoWriteBarrierField<int> m_iProfileSession; // Script profile session the meta data of this function is reported to.
  1531. #endif // DEBUG
  1532. // R0 is reserved for the return value, R1 for the root object
  1533. static const RegSlot ReturnValueRegSlot = 0;
  1534. static const RegSlot RootObjectRegSlot = 1;
  1535. static const RegSlot FirstRegSlot = 1;
  1536. // This value be set on the stack (on a particular offset), when the frame value got changed.
  1537. static const int LocalsChangeDirtyValue = 1;
  1538. enum FunctionBodyFlags : byte
  1539. {
  1540. Flags_None = 0x00,
  1541. Flags_StackNestedFunc = 0x01,
  1542. Flags_HasOrParentHasArguments = 0x02,
  1543. Flags_HasTry = 0x04,
  1544. Flags_HasThis = 0x08,
  1545. Flags_NonUserCode = 0x10,
  1546. Flags_HasOnlyThisStatements = 0x20,
  1547. Flags_HasNoExplicitReturnValue = 0x40, // Returns undefined, i.e. has no return statements or return with no expression
  1548. Flags_HasRestParameter = 0x80
  1549. };
  1550. #define DEFINE_FUNCTION_BODY_FIELDS 1
  1551. #define CURRENT_ACCESS_MODIFIER public:
  1552. #include "SerializableFunctionFields.h"
  1553. private:
  1554. bool m_tag : 1; // Used to tag the low bit to prevent possible GC false references
  1555. bool m_nativeEntryPointUsed : 1; // Code might have been generated but not yet used.
  1556. bool hasDoneLoopBodyCodeGen : 1; // Code generated for loop body, but not necessary available to execute yet.
  1557. bool m_isFuncRegistered : 1;
  1558. bool m_isFuncRegisteredToDiag : 1; // Mentions the function's context is registered with diagprobe.
  1559. bool funcEscapes : 1;
  1560. bool m_hasBailoutInstrInJittedCode : 1; // Indicates whether function has bailout instructions. Valid only if hasDoneCodeGen is true
  1561. bool m_pendingLoopHeaderRelease : 1; // Indicates whether loop headers need to be released
  1562. bool hasExecutionDynamicProfileInfo : 1;
  1563. bool cleanedUp: 1;
  1564. bool sourceInfoCleanedUp: 1;
  1565. bool dontRethunkAfterBailout : 1;
  1566. bool disableInlineApply : 1;
  1567. bool disableInlineSpread : 1;
  1568. bool hasHotLoop: 1;
  1569. bool wasCalledFromLoop : 1;
  1570. bool hasNestedLoop : 1;
  1571. bool recentlyBailedOutOfJittedLoopBody : 1;
  1572. bool m_firstFunctionObject: 1;
  1573. bool m_inlineCachesOnFunctionObject: 1;
  1574. // 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
  1575. // the state of the script context, or on other factors like whether it was defer parsed or not.
  1576. bool m_hasSetIsObject : 1;
  1577. // 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.
  1578. // 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.
  1579. bool m_hasAllNonLocalReferenced : 1;
  1580. bool m_hasFunExprNameReference : 1;
  1581. bool m_ChildCallsEval : 1;
  1582. bool m_CallsEval : 1;
  1583. bool m_hasReferenceableBuiltInArguments : 1;
  1584. // Used in the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple times for each child function.
  1585. bool m_hasDoneAllNonLocalReferenced : 1;
  1586. // Used by the script profiler, once the function compiled is sent this will be set to true.
  1587. bool m_hasFunctionCompiledSent : 1;
  1588. bool m_isFromNativeCodeModule : 1;
  1589. bool m_isPartialDeserializedFunction : 1;
  1590. bool m_isAsmJsScheduledForFullJIT : 1;
  1591. #ifdef PERF_COUNTERS
  1592. bool m_isDeserializedFunction : 1;
  1593. #endif
  1594. #if DBG
  1595. // Indicates that nested functions can be allocated on the stack (but may not be)
  1596. bool m_canDoStackNestedFunc : 1;
  1597. #endif
  1598. #if DBG
  1599. bool initializedExecutionModeAndLimits : 1;
  1600. #endif
  1601. #ifdef IR_VIEWER
  1602. // whether IR Dump is enabled for this function (used by parseIR)
  1603. bool m_isIRDumpEnabled : 1;
  1604. WriteBarrierPtr<Js::DynamicObject> m_irDumpBaseObject;
  1605. #endif /* IR_VIEWER */
  1606. NoWriteBarrierField<uint8> bailOnMisingProfileCount;
  1607. NoWriteBarrierField<uint8> bailOnMisingProfileRejitCount;
  1608. NoWriteBarrierField<byte> inlineDepth; // Used by inlining to avoid recursively inlining functions excessively
  1609. NoWriteBarrierField<ExecutionMode> executionMode;
  1610. NoWriteBarrierField<uint16> interpreterLimit;
  1611. NoWriteBarrierField<uint16> autoProfilingInterpreter0Limit;
  1612. NoWriteBarrierField<uint16> profilingInterpreter0Limit;
  1613. NoWriteBarrierField<uint16> autoProfilingInterpreter1Limit;
  1614. NoWriteBarrierField<uint16> simpleJitLimit;
  1615. NoWriteBarrierField<uint16> profilingInterpreter1Limit;
  1616. NoWriteBarrierField<uint16> fullJitThreshold;
  1617. NoWriteBarrierField<uint16> fullJitRequeueThreshold;
  1618. NoWriteBarrierField<uint16> committedProfiledIterations;
  1619. NoWriteBarrierField<uint> m_depth; // Indicates how many times the function has been entered (so increases by one on each recursive call, decreases by one when we're done)
  1620. WriteBarrierPtr<RecyclerWeakReference<FunctionBody>> stackNestedFuncParent;
  1621. // >>>>>>WARNING! WARNING!<<<<<<<<<<
  1622. //
  1623. // If you add compile-time attributes to the above set, be sure to add them to the attributes that are
  1624. // copied in FunctionBody::Clone
  1625. //
  1626. NoWriteBarrierPtr<Js::ByteCodeCache> byteCodeCache; // Not GC allocated so naked pointer
  1627. NoWriteBarrierField<int> serializationIndex;
  1628. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1629. static bool shareInlineCaches;
  1630. #endif
  1631. WriteBarrierPtr<DynamicType*> objLiteralTypes;
  1632. WriteBarrierPtr<FunctionEntryPointInfo> defaultFunctionEntryPointInfo;
  1633. WriteBarrierPtr<FunctionEntryPointInfo> simpleJitEntryPointInfo;
  1634. #if ENABLE_PROFILE_INFO
  1635. WriteBarrierPtr<DynamicProfileInfo> dynamicProfileInfo;
  1636. WriteBarrierPtr<PolymorphicCallSiteInfo> polymorphicCallSiteInfoHead;
  1637. #endif
  1638. FunctionBailOutRecord * functionBailOutRecord;
  1639. // select dynamic profile info saved off when we codegen and later
  1640. // used for rejit decisions (see bailout.cpp)
  1641. NoWriteBarrierField<BYTE> savedInlinerVersion;
  1642. #if ENABLE_NATIVE_CODEGEN
  1643. NoWriteBarrierField<ImplicitCallFlags> savedImplicitCallsFlags;
  1644. #endif
  1645. // State of inline caches (polymorphic vs. monomorphic) reflected in
  1646. // last jitted version of this func.
  1647. NoWriteBarrierField<uint32> savedPolymorphicCacheState;
  1648. // Used to track where we are when adding debugger scopes to the scope chain
  1649. // in order to avoid re-adding existing entries.
  1650. NoWriteBarrierField<int> debuggerScopeIndex;
  1651. FunctionBody(ScriptContext* scriptContext, const wchar_t* displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount, Utf8SourceInfo* sourceInfo,
  1652. uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* propRecordList, Attributes attributes
  1653. #ifdef PERF_COUNTERS
  1654. , bool isDeserializedFunction = false
  1655. #endif
  1656. );
  1657. void SetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod originalEntryPoint, Var directEntryPoint);
  1658. #if DYNAMIC_INTERPRETER_THUNK
  1659. void GenerateDynamicInterpreterThunk();
  1660. #endif
  1661. void CloneByteCodeInto(ScriptContext * scriptContext, FunctionBody *newFunctionBody, uint sourceIndex);
  1662. void * GetEntryPoint(ProxyEntryPointInfo* entryPoint) const { return entryPoint->address; }
  1663. void CaptureDynamicProfileState(FunctionEntryPointInfo* entryPointInfo);
  1664. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1665. void DumpRegStats(FunctionBody *funcBody);
  1666. #endif
  1667. // Gets the next index for tracking debugger scopes (increments the internal counter as well).
  1668. int GetNextDebuggerScopeIndex();
  1669. public:
  1670. FunctionBody(ByteCodeCache* cache, Utf8SourceInfo* sourceInfo, ScriptContext* scriptContext):
  1671. ParseableFunctionInfo((JavascriptMethod) nullptr, 0, 0, (LocalFunctionId) 0, sourceInfo, scriptContext, 0, nullptr, 0, 0, None, nullptr)
  1672. {
  1673. // Dummy constructor- does nothing
  1674. // Must be stack allocated
  1675. // Used during deferred bytecode serialization
  1676. }
  1677. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const wchar_t * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1678. Utf8SourceInfo* sourceInfo, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, Attributes attributes
  1679. #ifdef PERF_COUNTERS
  1680. , bool isDeserializedFunction
  1681. #endif
  1682. );
  1683. static FunctionBody * NewFromRecycler(Js::ScriptContext * scriptContext, const wchar_t * displayName, uint displayNameLength, uint displayShortNameOffset, uint nestedCount,
  1684. Utf8SourceInfo* sourceInfo, uint uFunctionNumber, uint uScriptId, Js::LocalFunctionId functionId, Js::PropertyRecordList* boundPropertyRecords, Attributes attributes
  1685. #ifdef PERF_COUNTERS
  1686. , bool isDeserializedFunction
  1687. #endif
  1688. );
  1689. FunctionEntryPointInfo * GetEntryPointInfo(int index) const;
  1690. FunctionEntryPointInfo * TryGetEntryPointInfo(int index) const;
  1691. Js::RootObjectBase * LoadRootObject() const;
  1692. Js::RootObjectBase * GetRootObject() const;
  1693. ByteBlock* GetAuxiliaryData();
  1694. ByteBlock* GetAuxiliaryContextData();
  1695. ByteBlock* GetByteCode();
  1696. ByteBlock* GetOriginalByteCode(); // Returns original bytecode without probes (such as BPs).
  1697. const Js::ByteCodeCache * GetByteCodeCache() const;
  1698. void SetSerializationIndex(int index) { Assert(serializationIndex == -1 && index != -1); serializationIndex = index; }
  1699. const int GetSerializationIndex() const;
  1700. uint GetByteCodeCount() const { return m_byteCodeCount; }
  1701. uint GetByteCodeWithoutLDACount() const { return m_byteCodeWithoutLDACount; }
  1702. uint GetByteCodeInLoopCount() const { return m_byteCodeInLoopCount; }
  1703. uint16 GetEnvDepth() const { return m_envDepth; }
  1704. void SetEnvDepth(uint16 depth) { m_envDepth = depth; }
  1705. RegSlot GetEnvReg() const { return envRegister; }
  1706. void SetEnvReg(RegSlot reg) { Assert(envRegister == Constants::NoRegister); envRegister = this->MapRegSlot(reg); }
  1707. RegSlot GetThisRegForEventHandler() const { return thisRegisterForEventHandler; }
  1708. void SetThisRegForEventHandler(RegSlot reg) { Assert(thisRegisterForEventHandler == Constants::NoRegister); thisRegisterForEventHandler = this->MapRegSlot(reg); }
  1709. bool HasScopeObject() const { return hasScopeObject; }
  1710. void SetHasScopeObject(bool has) { hasScopeObject = has; }
  1711. void SetLocalClosureReg(RegSlot reg) { Assert(localClosureRegister == Constants::NoRegister); localClosureRegister = this->MapRegSlot(reg); }
  1712. RegSlot GetLocalClosureReg() const { return localClosureRegister; }
  1713. void SetLocalFrameDisplayReg(RegSlot reg) { Assert(localFrameDisplayRegister == Constants::NoRegister); localFrameDisplayRegister = this->MapRegSlot(reg); }
  1714. RegSlot GetLocalFrameDisplayReg() const { return localFrameDisplayRegister; /*localClosureRegister == Constants::NoRegister ? Constants::NoRegister : localClosureRegister + 1;*/ }
  1715. RegSlot FirstInnerScopeReg() const { Assert(firstInnerScopeRegister != Constants::NoRegister); return firstInnerScopeRegister; }
  1716. void SetFirstInnerScopeReg(RegSlot reg) { Assert(reg != Constants::NoRegister); firstInnerScopeRegister = this->MapRegSlot(reg); }
  1717. RegSlot GetFuncExprScopeReg() const { return funcExprScopeRegister; }
  1718. void SetFuncExprScopeReg(RegSlot reg) { Assert(reg != Constants::NoRegister); funcExprScopeRegister = this->MapRegSlot(reg); }
  1719. uint GetInnerScopeCount() const { return innerScopeCount; }
  1720. void SetInnerScopeCount(uint count) { innerScopeCount = count; }
  1721. bool HasCachedScopePropIds() const { return hasCachedScopePropIds; }
  1722. void SetHasCachedScopePropIds(bool has) { hasCachedScopePropIds = has; }
  1723. size_t GetLoopBodyName(uint loopNumber, _Out_writes_opt_z_(sizeInChars) WCHAR* displayName, _In_ size_t sizeInChars);
  1724. void AllocateLoopHeaders();
  1725. void ReleaseLoopHeaders();
  1726. Js::LoopHeader * GetLoopHeader(uint index) const;
  1727. Js::Var GetLoopHeaderArrayPtr() const
  1728. {
  1729. Assert(this->loopHeaderArray != nullptr);
  1730. return this->loopHeaderArray;
  1731. }
  1732. #ifndef TEMP_DISABLE_ASMJS
  1733. void SetIsAsmJsFullJitScheduled(bool val){ m_isAsmJsScheduledForFullJIT = val; }
  1734. bool GetIsAsmJsFullJitScheduled(){ return m_isAsmJsScheduledForFullJIT; }
  1735. uint32 GetAsmJSTotalLoopCount() const
  1736. {
  1737. return m_asmJsTotalLoopCount;
  1738. }
  1739. void SetIsAsmJsFunction(bool isAsmJsFunction)
  1740. {
  1741. m_isAsmJsFunction = isAsmJsFunction;
  1742. }
  1743. #endif
  1744. const bool GetIsAsmJsFunction() const
  1745. {
  1746. return m_isAsmJsFunction;
  1747. }
  1748. #ifndef TEMP_DISABLE_ASMJS
  1749. bool IsHotAsmJsLoop()
  1750. {
  1751. // Negative MinTemplatizedJitLoopRunCount treats all loops as hot asm loop
  1752. if (CONFIG_FLAG(MinTemplatizedJitLoopRunCount) < 0 || m_asmJsTotalLoopCount > static_cast<uint>(CONFIG_FLAG(MinTemplatizedJitLoopRunCount)))
  1753. {
  1754. return true;
  1755. }
  1756. return false;
  1757. }
  1758. #endif
  1759. private:
  1760. void ResetLoops();
  1761. public:
  1762. static bool Is(void* ptr);
  1763. uint GetScriptId() const { return m_uScriptId; }
  1764. void* GetAddressOfScriptId() const
  1765. {
  1766. return (void*)&m_uScriptId;
  1767. }
  1768. uint8 *GetCallsCountAddress(EntryPointInfo* info) const
  1769. {
  1770. FunctionEntryPointInfo* entryPoint = (FunctionEntryPointInfo*) info;
  1771. return &entryPoint->callsCount;
  1772. }
  1773. FunctionEntryPointInfo* GetDefaultFunctionEntryPointInfo() const;
  1774. void SetDefaultFunctionEntryPointInfo(FunctionEntryPointInfo* entryPointInfo, const JavascriptMethod originalEntryPoint);
  1775. FunctionEntryPointInfo *GetSimpleJitEntryPointInfo() const;
  1776. void SetSimpleJitEntryPointInfo(FunctionEntryPointInfo *const entryPointInfo);
  1777. private:
  1778. void VerifyExecutionMode(const ExecutionMode executionMode) const;
  1779. public:
  1780. ExecutionMode GetDefaultInterpreterExecutionMode() const;
  1781. ExecutionMode GetExecutionMode() const;
  1782. ExecutionMode GetInterpreterExecutionMode(const bool isPostBailout);
  1783. void SetExecutionMode(const ExecutionMode executionMode);
  1784. private:
  1785. bool IsInterpreterExecutionMode() const;
  1786. public:
  1787. bool TryTransitionToNextExecutionMode();
  1788. void TryTransitionToNextInterpreterExecutionMode();
  1789. void SetIsSpeculativeJitCandidate();
  1790. bool TryTransitionToJitExecutionMode();
  1791. void TransitionToSimpleJitExecutionMode();
  1792. void TransitionToFullJitExecutionMode();
  1793. private:
  1794. void VerifyExecutionModeLimits();
  1795. void InitializeExecutionModeAndLimits();
  1796. public:
  1797. void ReinitializeExecutionModeAndLimits();
  1798. private:
  1799. void SetFullJitThreshold(const uint16 newFullJitThreshold, const bool skipSimpleJit = false);
  1800. void CommitExecutedIterations();
  1801. void CommitExecutedIterations(uint16 &limit, const uint executedIterations);
  1802. private:
  1803. uint16 GetSimpleJitExecutedIterations() const;
  1804. public:
  1805. void ResetSimpleJitLimitAndCallCount();
  1806. private:
  1807. void SetSimpleJitCallCount(const uint16 simpleJitLimit) const;
  1808. void ResetSimpleJitCallCount();
  1809. public:
  1810. uint16 GetProfiledIterations() const;
  1811. public:
  1812. void OnFullJitDequeued(const FunctionEntryPointInfo *const entryPointInfo);
  1813. public:
  1814. void TraceExecutionMode(const char *const eventDescription = nullptr) const;
  1815. void TraceInterpreterExecutionMode() const;
  1816. private:
  1817. void DoTraceExecutionMode(const char *const eventDescription) const;
  1818. public:
  1819. static bool IsNewSimpleJit();
  1820. bool DoSimpleJit() const;
  1821. bool DoSimpleJitDynamicProfile() const;
  1822. private:
  1823. bool DoInterpreterProfile() const;
  1824. bool DoInterpreterAutoProfile() const;
  1825. public:
  1826. bool WasCalledFromLoop() const;
  1827. void SetWasCalledFromLoop();
  1828. public:
  1829. bool RecentlyBailedOutOfJittedLoopBody() const;
  1830. void SetRecentlyBailedOutOfJittedLoopBody(const bool value);
  1831. private:
  1832. static uint16 GetMinProfileIterations();
  1833. public:
  1834. static uint16 GetMinFunctionProfileIterations();
  1835. private:
  1836. static uint GetMinLoopProfileIterations(const uint loopInterpreterLimit);
  1837. public:
  1838. uint GetLoopProfileThreshold(const uint loopInterpreterLimit) const;
  1839. private:
  1840. static uint GetReducedLoopInterpretCount();
  1841. public:
  1842. uint GetLoopInterpretCount(LoopHeader* loopHeader) const;
  1843. private:
  1844. static bool DoObjectHeaderInlining();
  1845. static bool DoObjectHeaderInliningForConstructors();
  1846. public:
  1847. static bool DoObjectHeaderInliningForConstructor(const uint32 inlineSlotCapacity);
  1848. private:
  1849. static bool DoObjectHeaderInliningForObjectLiterals();
  1850. public:
  1851. static bool DoObjectHeaderInliningForObjectLiteral(const uint32 inlineSlotCapacity);
  1852. static bool DoObjectHeaderInliningForObjectLiteral(const PropertyIdArray *const propIds, ScriptContext *const scriptContext);
  1853. static bool DoObjectHeaderInliningForEmptyObjects();
  1854. public:
  1855. #if DBG
  1856. int GetProfileSession() { return m_iProfileSession; }
  1857. #endif
  1858. virtual void Finalize(bool isShutdown) override;
  1859. void Cleanup(bool isScriptContextClosing);
  1860. void CleanupSourceInfo(bool isScriptContextClosing);
  1861. template<bool IsScriptContextShutdown>
  1862. void CleanUpInlineCaches();
  1863. void CleanupRecyclerData(bool isRecyclerShutdown, bool doEntryPointCleanupCaptureStack);
  1864. #ifdef PERF_COUNTERS
  1865. void CleanupPerfCounter();
  1866. #endif
  1867. virtual void Dispose(bool isShutdown) override { }
  1868. bool HasRejit() const
  1869. {
  1870. if(this->entryPoints)
  1871. {
  1872. return this->entryPoints->Count() > 1;
  1873. }
  1874. return false;
  1875. }
  1876. #pragma region SourceInfo Methods
  1877. void CopySourceInfo(ParseableFunctionInfo* originalFunctionInfo);
  1878. void FinishSourceInfo();
  1879. RegSlot GetFrameDisplayRegister() const;
  1880. void SetFrameDisplayRegister(RegSlot frameDisplayRegister);
  1881. RegSlot GetObjectRegister() const;
  1882. void SetObjectRegister(RegSlot objectRegister);
  1883. bool HasObjectRegister() const { return GetObjectRegister() != 0; }
  1884. ScopeObjectChain *GetScopeObjectChain() const;
  1885. void SetScopeObjectChain(ScopeObjectChain *pScopeObjectChain);
  1886. // fetch the Catch scope object which encloses the passed bytecode offset, returns NULL otherwise
  1887. Js::DebuggerScope * GetDiagCatchScopeObjectAt(int byteCodeOffset);
  1888. ByteBlock *GetProbeBackingBlock();
  1889. void SetProbeBackingBlock(ByteBlock* probeBackingBlock);
  1890. bool HasLineBreak() const;
  1891. bool HasLineBreak(charcount_t start, charcount_t end) const;
  1892. bool HasGeneratedFromByteCodeCache() const { return this->byteCodeCache != nullptr; }
  1893. bool EndsAfter(size_t offset) const;
  1894. void TrackLoad(int ichMin);
  1895. SmallSpanSequence* GetStatementMapSpanSequence() const { return m_sourceInfo.pSpanSequence; }
  1896. void RecordStatementMap(StatementMap* statementMap);
  1897. void RecordStatementMap(SmallSpanSequenceIter &iter, StatementData * data);
  1898. void RecordLoad(int ichMin, int bytecodeAfterLoad);
  1899. DebuggerScope* RecordStartScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation, int* index = nullptr);
  1900. void RecordEndScopeObject(DebuggerScope* currentScope, int end);
  1901. DebuggerScope* AddScopeObject(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  1902. bool TryGetDebuggerScopeAt(int index, DebuggerScope*& debuggerScope);
  1903. StatementMapList * GetStatementMaps() const;
  1904. static StatementMap * GetNextNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex);
  1905. static StatementMap * GetPrevNonSubexpressionStatementMap(StatementMapList *statementMapList, int & startingAtIndex);
  1906. void RecordStatementAdjustment(uint offset, StatementAdjustmentType adjType);
  1907. void RecordCrossFrameEntryExitRecord(uint byteCodeOffset, bool isEnterBlock);
  1908. // Find out an offset falls within the range. returns TRUE if found.
  1909. BOOL GetBranchOffsetWithin(uint start, uint end, StatementAdjustmentRecord* record);
  1910. bool GetLineCharOffset(int byteCodeOffset, ULONG* line, LONG* charOffset, bool canAllocateLineCache = true);
  1911. bool GetLineCharOffsetFromStartChar(int startCharOfStatement, ULONG* _line, LONG* _charOffset, bool canAllocateLineCache = true);
  1912. // Given bytecode position, returns the start position of the statement and length of the statement.
  1913. bool GetStatementIndexAndLengthAt(int byteCodeOffset, UINT32* statementIndex, UINT32* statementLength);
  1914. // skip any utf-8/utf-16 byte-order-mark. Returns the number of chars skipped.
  1915. static charcount_t SkipByteOrderMark(__in_bcount_z(4) LPCUTF8& documentStart)
  1916. {
  1917. charcount_t retValue = 0;
  1918. Assert(documentStart != nullptr);
  1919. if (documentStart[0] == 0xEF &&
  1920. documentStart[1] == 0xBB &&
  1921. documentStart[2] == 0xBF)
  1922. {
  1923. // UTF-8 - EF BB BF
  1924. // 3 bytes skipped - reports one char skipped
  1925. documentStart += 3;
  1926. retValue = 1;
  1927. }
  1928. else if ((documentStart[0] == 0xFF && documentStart[1] == 0xFE) ||
  1929. (documentStart[0] == 0xFE && documentStart[1] == 0xFF))
  1930. {
  1931. // UTF-16 LE - FF FE
  1932. // UTF-16 BE - FE FF
  1933. // 2 bytes skipped - reports one char skipped
  1934. documentStart += 2;
  1935. retValue = 1;
  1936. }
  1937. return retValue;
  1938. }
  1939. StatementMap* GetMatchingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  1940. int GetEnclosingStatementIndexFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  1941. StatementMap* GetEnclosingStatementMapFromByteCode(int byteCodeOffset, bool ignoreSubexpressions = false);
  1942. StatementMap* GetMatchingStatementMapFromSource(int byteCodeOffset, int* pMapIndex = nullptr);
  1943. void RecordFrameDisplayRegister(RegSlot slot);
  1944. void RecordObjectRegister(RegSlot slot);
  1945. CrossFrameEntryExitRecordList* GetCrossFrameEntryExitRecords();
  1946. #ifdef VTUNE_PROFILING
  1947. uint GetStartOffset(uint statementIndex) const;
  1948. ULONG GetSourceLineNumber(uint statementIndex);
  1949. #endif
  1950. #pragma endregion
  1951. // Field accessors
  1952. bool GetHasBailoutInstrInJittedCode() const { return this->m_hasBailoutInstrInJittedCode; }
  1953. void SetHasBailoutInstrInJittedCode(bool hasBailout) { this->m_hasBailoutInstrInJittedCode = hasBailout; }
  1954. bool GetCanReleaseLoopHeaders() const { return (this->m_depth == 0); }
  1955. void SetPendingLoopHeaderRelease(bool pendingLoopHeaderRelease) { this->m_pendingLoopHeaderRelease = pendingLoopHeaderRelease; }
  1956. bool GetIsFromNativeCodeModule() const { return m_isFromNativeCodeModule; }
  1957. void SetIsFromNativeCodeModule(bool isFromNativeCodeModule) { m_isFromNativeCodeModule = isFromNativeCodeModule; }
  1958. uint GetLoopNumber(LoopHeader const * loopHeader) const;
  1959. bool GetHasAllocatedLoopHeaders() { return this->loopHeaderArray != nullptr; }
  1960. #if ENABLE_NATIVE_CODEGEN
  1961. Js::JavascriptMethod GetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, int entryPointIndex);
  1962. void SetLoopBodyEntryPoint(Js::LoopHeader * loopHeader, EntryPointInfo* entryPointInfo, Js::JavascriptMethod entryPoint);
  1963. #endif
  1964. void RestoreOldDefaultEntryPoint(FunctionEntryPointInfo* oldEntryPoint, JavascriptMethod oldOriginalEntryPoint, FunctionEntryPointInfo* newEntryPoint);
  1965. FunctionEntryPointInfo* CreateNewDefaultEntryPoint();
  1966. void AddEntryPointToEntryPointList(FunctionEntryPointInfo* entryPoint);
  1967. // Kind of entry point for original entry point
  1968. BOOL IsInterpreterThunk() const;
  1969. BOOL IsDynamicInterpreterThunk() const;
  1970. BOOL IsNativeOriginalEntryPoint() const;
  1971. bool IsSimpleJitOriginalEntryPoint() const;
  1972. #if DYNAMIC_INTERPRETER_THUNK
  1973. static BYTE GetOffsetOfDynamicInterpreterThunk() { return offsetof(FunctionBody, m_dynamicInterpreterThunk); }
  1974. void* GetDynamicInterpreterEntryPoint() const
  1975. {
  1976. return m_dynamicInterpreterThunk;
  1977. }
  1978. bool HasInterpreterThunkGenerated() const
  1979. {
  1980. return m_dynamicInterpreterThunk != nullptr;
  1981. }
  1982. DWORD GetDynamicInterpreterThunkSize() const;
  1983. #endif
  1984. bool GetHasHotLoop() const { return hasHotLoop; };
  1985. void SetHasHotLoop();
  1986. bool GetHasNestedLoop() const { return hasNestedLoop; };
  1987. void SetHasNestedLoop(bool nest) { hasNestedLoop = nest; };
  1988. bool IsInlineApplyDisabled();
  1989. void InitDisableInlineApply();
  1990. void SetDisableInlineApply(bool set);
  1991. bool IsInlineSpreadDisabled() const { return disableInlineSpread; }
  1992. void InitDisableInlineSpread() { disableInlineSpread = this->functionId != Js::Constants::NoFunctionId && PHASE_OFF(Js::InlinePhase, this); }
  1993. void SetDisableInlineSpread(bool set) { disableInlineSpread = set; }
  1994. bool CheckCalleeContextForInlining(FunctionProxy* calleeFunctionProxy);
  1995. #if DBG
  1996. bool HasValidSourceInfo();
  1997. #endif
  1998. #if DYNAMIC_INTERPRETER_THUNK
  1999. JavascriptMethod EnsureDynamicInterpreterThunk(FunctionEntryPointInfo* entryPointInfo);
  2000. #endif
  2001. void SetCheckCodeGenEntryPoint(FunctionEntryPointInfo* entryPointInfo, JavascriptMethod entryPoint);
  2002. #if ENABLE_NATIVE_CODEGEN
  2003. typedef void (*SetNativeEntryPointFuncType)(FunctionEntryPointInfo* entryPointInfo, Js::FunctionBody * functionBody, Js::JavascriptMethod entryPoint);
  2004. static void DefaultSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2005. static void ProfileSetNativeEntryPoint(FunctionEntryPointInfo* entryPointInfo, FunctionBody * functionBody, JavascriptMethod entryPoint);
  2006. bool GetNativeEntryPointUsed() const { return m_nativeEntryPointUsed; }
  2007. void SetNativeEntryPointUsed(bool nativeEntryPointUsed) { this->m_nativeEntryPointUsed = nativeEntryPointUsed; }
  2008. #endif
  2009. bool GetIsFuncRegistered() { return m_isFuncRegistered; }
  2010. void SetIsFuncRegistered(bool isRegistered) { m_isFuncRegistered = isRegistered; }
  2011. bool GetHasLoops() const { return loopCount != 0; }
  2012. uint IncrLoopCount() { return this->loopCount++; }
  2013. uint GetLoopCount() const { return this->loopCount; }
  2014. bool AllocProfiledDivOrRem(ProfileId* profileId) { if (this->profiledDivOrRemCount != Constants::NoProfileId) { *profileId = this->profiledDivOrRemCount++; return true; } return false; }
  2015. ProfileId GetProfiledDivOrRemCount() { return this->profiledDivOrRemCount; }
  2016. bool AllocProfiledSwitch(ProfileId* profileId) { if (this->profiledSwitchCount != Constants::NoProfileId) { *profileId = this->profiledSwitchCount++; return true; } return false; }
  2017. ProfileId GetProfiledSwitchCount() { return this->profiledSwitchCount; }
  2018. bool AllocProfiledCallSiteId(ProfileId* profileId) { if (this->profiledCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledCallSiteCount++; return true; } return false; }
  2019. ProfileId GetProfiledCallSiteCount() const { return this->profiledCallSiteCount; }
  2020. void SetProfiledCallSiteCount(ProfileId callSiteId) { this->profiledCallSiteCount = callSiteId; }
  2021. bool AllocProfiledArrayCallSiteId(ProfileId* profileId) { if (this->profiledArrayCallSiteCount != Constants::NoProfileId) { *profileId = this->profiledArrayCallSiteCount++; return true; } return false; }
  2022. ProfileId GetProfiledArrayCallSiteCount() const { return this->profiledArrayCallSiteCount; }
  2023. bool AllocProfiledReturnTypeId(ProfileId* profileId) { if (this->profiledReturnTypeCount != Constants::NoProfileId) { *profileId = this->profiledReturnTypeCount++; return true; } return false; }
  2024. ProfileId GetProfiledReturnTypeCount() const { return this->profiledReturnTypeCount; }
  2025. bool AllocProfiledSlotId(ProfileId* profileId) { if (this->profiledSlotCount != Constants::NoProfileId) { *profileId = this->profiledSlotCount++; return true; } return false; }
  2026. ProfileId GetProfiledSlotCount() const { return this->profiledSlotCount; }
  2027. ProfileId AllocProfiledLdElemId(ProfileId* profileId) { if (this->profiledLdElemCount != Constants::NoProfileId) { *profileId = this->profiledLdElemCount++; return true; } return false; }
  2028. ProfileId GetProfiledLdElemCount() const { return this->profiledLdElemCount; }
  2029. bool AllocProfiledStElemId(ProfileId* profileId) { if (this->profiledStElemCount != Constants::NoProfileId) { *profileId = this->profiledStElemCount++; return true; } return false; }
  2030. ProfileId GetProfiledStElemCount() const { return this->profiledStElemCount; }
  2031. uint GetProfiledFldCount() const { return this->GetInlineCacheCount(); }
  2032. ArgSlot GetProfiledInParamsCount() const { return this->GetInParamsCount() > 1? this->GetInParamsCount() - 1 : 0; }
  2033. bool IsPartialDeserializedFunction() { return this->m_isPartialDeserializedFunction; }
  2034. #ifdef PERF_COUNTERS
  2035. bool IsDeserializedFunction() { return this->m_isDeserializedFunction; }
  2036. #endif
  2037. #ifdef IR_VIEWER
  2038. bool IsIRDumpEnabled() const { return this->m_isIRDumpEnabled; }
  2039. void SetIRDumpEnabled(bool enabled) { this->m_isIRDumpEnabled = enabled; }
  2040. Js::DynamicObject * GetIRDumpBaseObject();
  2041. #endif /* IR_VIEWER */
  2042. #if ENABLE_NATIVE_CODEGEN
  2043. void SetPolymorphicCallSiteInfoHead(PolymorphicCallSiteInfo *polyCallSiteInfo) { this->polymorphicCallSiteInfoHead = polyCallSiteInfo;}
  2044. PolymorphicCallSiteInfo * GetPolymorphicCallSiteInfoHead() { return this->polymorphicCallSiteInfoHead;}
  2045. #endif
  2046. PolymorphicInlineCache * GetPolymorphicInlineCachesHead() { return this->polymorphicInlineCachesHead; }
  2047. void SetPolymorphicInlineCachesHead(PolymorphicInlineCache * cache) { this->polymorphicInlineCachesHead = cache; }
  2048. bool PolyInliningUsingFixedMethodsAllowedByConfigFlags(FunctionBody* topFunctionBody)
  2049. {
  2050. return !PHASE_OFF(Js::InlinePhase, this) && !PHASE_OFF(Js::InlinePhase, topFunctionBody) &&
  2051. !PHASE_OFF(Js::PolymorphicInlinePhase, this) && !PHASE_OFF(Js::PolymorphicInlinePhase, topFunctionBody) &&
  2052. !PHASE_OFF(Js::FixedMethodsPhase, this) && !PHASE_OFF(Js::FixedMethodsPhase, topFunctionBody) &&
  2053. !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, this) && !PHASE_OFF(Js::PolymorphicInlineFixedMethodsPhase, topFunctionBody);
  2054. }
  2055. Js::PropertyId * GetPropertyIdsForScopeSlotArray() const
  2056. {
  2057. return this->propertyIdsForScopeSlotArray;
  2058. }
  2059. void SetPropertyIdsForScopeSlotArray(Js::PropertyId * propertyIdsForScopeSlotArray, uint scopeSlotCount)
  2060. {
  2061. this->scopeSlotArraySize = scopeSlotCount;
  2062. this->propertyIdsForScopeSlotArray = propertyIdsForScopeSlotArray;
  2063. }
  2064. Js::PropertyIdOnRegSlotsContainer * GetPropertyIdOnRegSlotsContainer() const
  2065. {
  2066. return this->propertyIdOnRegSlotsContainer;
  2067. }
  2068. private:
  2069. void ResetProfileIds();
  2070. void SetFlags(bool does, FunctionBodyFlags newFlags)
  2071. {
  2072. if (does)
  2073. {
  2074. flags = (FunctionBodyFlags)(flags | newFlags);
  2075. }
  2076. else
  2077. {
  2078. flags = (FunctionBodyFlags)(flags & ~newFlags);
  2079. }
  2080. }
  2081. public:
  2082. bool GetHasThis() const { return (flags & Flags_HasThis) != 0; }
  2083. void SetHasThis(bool has) { SetFlags(has, Flags_HasThis); }
  2084. bool GetHasTry() const { return (flags & Flags_HasTry) != 0; }
  2085. void SetHasTry(bool has) { SetFlags(has, Flags_HasTry); }
  2086. bool GetHasFinally() const { return m_hasFinally; }
  2087. void SetHasFinally(bool has){ m_hasFinally = has; }
  2088. bool GetFuncEscapes() const { return funcEscapes; }
  2089. void SetFuncEscapes(bool does) { funcEscapes = does; }
  2090. bool GetHasOrParentHasArguments() const { return (flags & Flags_HasOrParentHasArguments) != 0; }
  2091. void SetHasOrParentHasArguments(bool has) { SetFlags(has, Flags_HasOrParentHasArguments); }
  2092. bool DoStackNestedFunc() const { return (flags & Flags_StackNestedFunc) != 0; }
  2093. void SetStackNestedFunc(bool does) { SetFlags(does, Flags_StackNestedFunc); }
  2094. #if DBG
  2095. bool CanDoStackNestedFunc() const { return m_canDoStackNestedFunc; }
  2096. void SetCanDoStackNestedFunc() { m_canDoStackNestedFunc = true; }
  2097. #endif
  2098. FunctionBody * GetStackNestedFuncParent();
  2099. FunctionBody * GetAndClearStackNestedFuncParent();
  2100. void ClearStackNestedFuncParent();
  2101. void SetStackNestedFuncParent(FunctionBody * parentFunctionBody);
  2102. #if defined(_M_IX86) || defined(_M_X64)
  2103. bool DoStackClosure() const
  2104. {
  2105. return DoStackNestedFunc() && GetNestedCount() != 0 && !PHASE_OFF(StackClosurePhase, this) && scopeSlotArraySize != 0 && GetEnvDepth() != (uint16)-1;
  2106. }
  2107. #else
  2108. bool DoStackClosure() const
  2109. {
  2110. return false;
  2111. }
  2112. #endif
  2113. bool DoStackFrameDisplay() const { return DoStackClosure(); }
  2114. bool DoStackScopeSlots() const { return DoStackClosure(); }
  2115. bool IsNonUserCode() const { return (flags & Flags_NonUserCode) != 0; }
  2116. void SetIsNonUserCode(bool set);
  2117. bool GetHasNoExplicitReturnValue() { return (flags & Flags_HasNoExplicitReturnValue) != 0; }
  2118. void SetHasNoExplicitReturnValue(bool has) { SetFlags(has, Flags_HasNoExplicitReturnValue); }
  2119. bool GetHasOnlyThisStmts() const { return (flags & Flags_HasOnlyThisStatements) != 0; }
  2120. void SetHasOnlyThisStmts(bool has) { SetFlags(has, Flags_HasOnlyThisStatements); }
  2121. bool GetIsFirstFunctionObject() const { return m_firstFunctionObject; }
  2122. void SetIsNotFirstFunctionObject() { m_firstFunctionObject = false; }
  2123. bool GetInlineCachesOnFunctionObject() { return m_inlineCachesOnFunctionObject; }
  2124. void SetInlineCachesOnFunctionObject(bool has) { m_inlineCachesOnFunctionObject = has; }
  2125. bool GetHasRestParameter() const { return (flags & Flags_HasRestParameter) != 0; }
  2126. void SetHasRestParameter() { SetFlags(true, Flags_HasRestParameter); }
  2127. uint GetNumberOfRecursiveCallSites();
  2128. bool CanInlineRecursively(uint depth, bool tryAggressive = true);
  2129. public:
  2130. bool CanInlineAgain() const
  2131. {
  2132. // Block excessive recursive inlining of the same function
  2133. return inlineDepth < static_cast<byte>(max(1, min(0xff, CONFIG_FLAG(MaxFuncInlineDepth))));
  2134. }
  2135. void OnBeginInlineInto()
  2136. {
  2137. ++inlineDepth;
  2138. }
  2139. void OnEndInlineInto()
  2140. {
  2141. --inlineDepth;
  2142. }
  2143. uint8 IncrementBailOnMisingProfileCount() { return ++bailOnMisingProfileCount; }
  2144. void ResetBailOnMisingProfileCount() { bailOnMisingProfileCount = 0; }
  2145. uint8 IncrementBailOnMisingProfileRejitCount() { return ++bailOnMisingProfileRejitCount; }
  2146. uint32 GetFrameHeight(EntryPointInfo* entryPointInfo) const;
  2147. void SetFrameHeight(EntryPointInfo* entryPointInfo, uint32 frameHeight);
  2148. RegSlot GetLocalsCount();
  2149. RegSlot GetConstantCount() const { return m_constCount; }
  2150. void SetConstantCount(RegSlot cNewConstants);
  2151. RegSlot GetVarCount();
  2152. void SetVarCount(RegSlot cNewVars);
  2153. RegSlot MapRegSlot(RegSlot reg)
  2154. {
  2155. if (this->RegIsConst(reg))
  2156. {
  2157. reg = CONSTREG_TO_REGSLOT(reg);
  2158. Assert(reg < this->GetConstantCount());
  2159. }
  2160. else
  2161. {
  2162. reg += this->GetConstantCount();
  2163. }
  2164. return reg;
  2165. }
  2166. bool RegIsConst(RegSlot reg) { return reg > REGSLOT_TO_CONSTREG(this->GetConstantCount()); }
  2167. uint32 GetNonTempLocalVarCount();
  2168. uint32 GetFirstNonTempLocalIndex();
  2169. uint32 GetEndNonTempLocalIndex();
  2170. bool IsNonTempLocalVar(uint32 varIndex);
  2171. bool GetSlotOffset(RegSlot slotId, int32 * slotOffset, bool allowTemp = false);
  2172. RegSlot GetOutParamsDepth();
  2173. void SetOutParamDepth(RegSlot cOutParamsDepth);
  2174. RegSlot GetYieldRegister();
  2175. RegSlot GetFirstTmpReg();
  2176. void SetFirstTmpReg(RegSlot firstTmpReg);
  2177. RegSlot GetTempCount();
  2178. Js::ModuleID GetModuleID() const;
  2179. void CreateConstantTable();
  2180. void RecordNullObject(RegSlot location);
  2181. void RecordUndefinedObject(RegSlot location);
  2182. void RecordTrueObject(RegSlot location);
  2183. void RecordFalseObject(RegSlot location);
  2184. void RecordIntConstant(RegSlot location, unsigned int val);
  2185. void RecordStrConstant(RegSlot location, LPCOLESTR psz, ulong cch);
  2186. void RecordFloatConstant(RegSlot location, double d);
  2187. void RecordNullDisplayConstant(RegSlot location);
  2188. void RecordStrictNullDisplayConstant(RegSlot location);
  2189. void InitConstantSlots(Var *dstSlots);
  2190. Var GetConstantVar(RegSlot location);
  2191. void* GetConstTable() const{return m_constTable;}
  2192. void CloneConstantTable(FunctionBody *newFunc);
  2193. void MarkScript(ByteBlock * pblkByteCode, ByteBlock * pblkAuxiliaryData, ByteBlock* auxContextBlock,
  2194. uint byteCodeCount, uint byteCodeInLoopCount, uint byteCodeWithoutLDACount);
  2195. void BeginExecution();
  2196. void EndExecution();
  2197. SourceInfo * GetSourceInfo() { return &this->m_sourceInfo; }
  2198. bool InstallProbe(int offset);
  2199. bool UninstallProbe(int offset);
  2200. bool ProbeAtOffset(int offsest, OpCode* pOriginalOpcode);
  2201. FunctionBody * Clone(ScriptContext *scriptContext, uint sourceIndex = Js::Constants::InvalidSourceIndex);
  2202. static bool ShouldShareInlineCaches() { return CONFIG_FLAG(ShareInlineCaches); }
  2203. uint GetInlineCacheCount() const { return inlineCacheCount; }
  2204. uint GetRootObjectLoadInlineCacheStart() const { return rootObjectLoadInlineCacheStart; }
  2205. uint GetRootObjectLoadMethodInlineCacheStart() const { return rootObjectLoadMethodInlineCacheStart; }
  2206. uint GetRootObjectStoreInlineCacheStart() const { return rootObjectStoreInlineCacheStart; }
  2207. uint GetIsInstInlineCacheCount() const { return isInstInlineCacheCount; }
  2208. uint GetReferencedPropertyIdCount() const { return referencedPropertyIdCount; }
  2209. void AllocateInlineCache();
  2210. InlineCache * GetInlineCache(uint index);
  2211. bool CanFunctionObjectHaveInlineCaches();
  2212. void** GetInlineCaches();
  2213. #if DBG
  2214. byte* GetInlineCacheTypes();
  2215. #endif
  2216. InlineCache * GetRootObjectInlineCache(uint index);
  2217. IsInstInlineCache * GetIsInstInlineCache(uint index);
  2218. PolymorphicInlineCache * GetPolymorphicInlineCache(uint index);
  2219. PolymorphicInlineCache * CreateNewPolymorphicInlineCache(uint index, PropertyId propertyId, InlineCache * inlineCache);
  2220. PolymorphicInlineCache * CreateBiggerPolymorphicInlineCache(uint index, PropertyId propertyId);
  2221. private:
  2222. void ResetInlineCaches();
  2223. PolymorphicInlineCache * CreatePolymorphicInlineCache(uint index, uint16 size);
  2224. uint32 m_asmJsTotalLoopCount;
  2225. public:
  2226. void CreateCacheIdToPropertyIdMap();
  2227. void CreateCacheIdToPropertyIdMap(uint rootObjectLoadInlineCacheStart, uint rootObjectLoadMethodInlineCacheStart, uint rootObjectStoreInlineCacheStart,
  2228. uint totalFieldAccessInlineCacheCount, uint isInstInlineCacheCount);
  2229. void SetPropertyIdForCacheId(uint cacheId, PropertyId propertyId);
  2230. PropertyId GetPropertyIdFromCacheId(uint cacheId)
  2231. {
  2232. Assert(this->cacheIdToPropertyIdMap);
  2233. Assert(cacheId < this->GetInlineCacheCount());
  2234. return this->cacheIdToPropertyIdMap[cacheId];
  2235. }
  2236. #if DBG
  2237. void VerifyCacheIdToPropertyIdMap();
  2238. #endif
  2239. void CreateReferencedPropertyIdMap(uint referencedPropertyIdCount);
  2240. void CreateReferencedPropertyIdMap();
  2241. PropertyId GetReferencedPropertyIdWithMapIndex(uint mapIndex);
  2242. void SetReferencedPropertyIdWithMapIndex(uint mapIndex, PropertyId propertyId);
  2243. PropertyId GetReferencedPropertyId(uint index);
  2244. #if DBG
  2245. void VerifyReferencedPropertyIdMap();
  2246. #endif
  2247. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2248. void DumpFullFunctionName();
  2249. void DumpFunctionId(bool pad);
  2250. uint GetTraceFunctionNumber() const;
  2251. #endif
  2252. public:
  2253. uint NewObjectLiteral();
  2254. void AllocateObjectLiteralTypeArray();
  2255. DynamicType ** GetObjectLiteralTypeRef(uint index);
  2256. uint NewLiteralRegex();
  2257. uint GetLiteralRegexCount() const;
  2258. void AllocateLiteralRegexArray();
  2259. UnifiedRegex::RegexPattern *GetLiteralRegex(const uint index);
  2260. #ifndef TEMP_DISABLE_ASMJS
  2261. AsmJsFunctionInfo* GetAsmJsFunctionInfo()const {return asmJsFunctionInfo; }
  2262. AsmJsFunctionInfo* AllocateAsmJsFunctionInfo();
  2263. AsmJsModuleInfo* GetAsmJsModuleInfo()const{ return asmJsModuleInfo; }
  2264. void ResetAsmJsInfo()
  2265. {
  2266. asmJsFunctionInfo = nullptr;
  2267. asmJsModuleInfo = nullptr;
  2268. }
  2269. bool IsAsmJSModule()const{ if (asmJsModuleInfo) return true; return false; }
  2270. AsmJsModuleInfo* AllocateAsmJsModuleInfo();
  2271. #endif
  2272. void SetLiteralRegex(const uint index, UnifiedRegex::RegexPattern *const pattern);
  2273. private:
  2274. void ResetLiteralRegexes();
  2275. void ResetObjectLiteralTypes();
  2276. public:
  2277. void ResetByteCodeGenState();
  2278. void ResetByteCodeGenVisitState();
  2279. void FindClosestStatements(long characterOffset, StatementLocation *firstStatementLocation, StatementLocation *secondStatementLocation);
  2280. #if ENABLE_NATIVE_CODEGEN
  2281. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeData(const ProfileId profiledCallSiteId) const;
  2282. const FunctionCodeGenRuntimeData *GetInlineeCodeGenRuntimeDataForTargetInlinee(const ProfileId profiledCallSiteId, FunctionBody *inlineeFuncBody) const;
  2283. FunctionCodeGenRuntimeData *EnsureInlineeCodeGenRuntimeData(
  2284. Recycler *const recycler,
  2285. __in_range(0, profiledCallSiteCount - 1) const ProfileId profiledCallSiteId,
  2286. FunctionBody *const inlinee);
  2287. const FunctionCodeGenRuntimeData *GetLdFldInlineeCodeGenRuntimeData(const InlineCacheIndex inlineCacheIndex) const;
  2288. FunctionCodeGenRuntimeData *EnsureLdFldInlineeCodeGenRuntimeData(
  2289. Recycler *const recycler,
  2290. __in_range(0, this->inlineCacheCount - 1) const InlineCacheIndex inlineCacheIndex,
  2291. FunctionBody *const inlinee);
  2292. void LoadDynamicProfileInfo();
  2293. bool HasExecutionDynamicProfileInfo() const { return hasExecutionDynamicProfileInfo; }
  2294. bool HasDynamicProfileInfo() const { return dynamicProfileInfo != nullptr; }
  2295. bool NeedEnsureDynamicProfileInfo() const;
  2296. DynamicProfileInfo * GetDynamicProfileInfo() const { Assert(HasExecutionDynamicProfileInfo()); return dynamicProfileInfo; }
  2297. DynamicProfileInfo * GetAnyDynamicProfileInfo() const { Assert(HasDynamicProfileInfo()); return dynamicProfileInfo; }
  2298. DynamicProfileInfo * EnsureDynamicProfileInfo();
  2299. DynamicProfileInfo * AllocateDynamicProfile();
  2300. BYTE GetSavedInlinerVersion() const;
  2301. uint32 GetSavedPolymorphicCacheState() const;
  2302. ImplicitCallFlags GetSavedImplicitCallsFlags() const;
  2303. bool HasNonBuiltInCallee();
  2304. bool HasFunctionBailOutRecord() const { return functionBailOutRecord != nullptr; }
  2305. FunctionBailOutRecord * GetFunctionBailOutRecord() const { Assert(HasFunctionBailOutRecord()); return functionBailOutRecord; }
  2306. void SetFunctionBailOutRecord(FunctionBailOutRecord * record) { Assert(!HasFunctionBailOutRecord()); functionBailOutRecord = record; }
  2307. void RecordNativeThrowMap(SmallSpanSequenceIter& iter, uint32 offset, uint32 statementIndex, EntryPointInfo* entryPoint, uint loopNum);
  2308. void RecordNativeBaseAddress(BYTE* baseAddress, ptrdiff_t codeSizeS, NativeCodeData * data, NativeCodeData * transferData, CodeGenNumberChunk * numberChunks,
  2309. EntryPointInfo* info, uint loopNum);
  2310. void SetNativeThrowSpanSequence(SmallSpanSequence *seq, uint loopNum, LoopEntryPointInfo* entryPoint);
  2311. BOOL GetMatchingStatementMapFromNativeAddress(DWORD_PTR codeAddress, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2312. BOOL GetMatchingStatementMapFromNativeOffset(DWORD_PTR codeAddress, uint32 offset, StatementData &data, uint loopNum, FunctionBody *inlinee = nullptr);
  2313. FunctionEntryPointInfo * GetEntryPointFromNativeAddress(DWORD_PTR codeAddress);
  2314. LoopEntryPointInfo * GetLoopEntryPointInfoFromNativeAddress(DWORD_PTR codeAddress, uint loopNum) const;
  2315. #endif
  2316. void InsertSymbolToRegSlotList(JsUtil::CharacterBuffer<WCHAR> const& propName, RegSlot reg, RegSlot totalRegsCount);
  2317. void InsertSymbolToRegSlotList(RegSlot reg, PropertyId propertyId, RegSlot totalRegsCount);
  2318. void SetPropertyIdsOfFormals(PropertyIdArray * formalArgs);
  2319. bool DontRethunkAfterBailout() const { return dontRethunkAfterBailout; }
  2320. void SetDontRethunkAfterBailout() { dontRethunkAfterBailout = true; }
  2321. void ClearDontRethunkAfterBailout() { dontRethunkAfterBailout = false; }
  2322. void SaveState(ParseNodePtr pnode);
  2323. void RestoreState(ParseNodePtr pnode);
  2324. // 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.
  2325. // 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.
  2326. bool HasAllNonLocalReferenced() const { return m_hasAllNonLocalReferenced; }
  2327. void SetAllNonLocalReferenced(bool set) { m_hasAllNonLocalReferenced = set; }
  2328. bool HasSetIsObject() const { return m_hasSetIsObject; }
  2329. void SetHasSetIsObject(bool set) { m_hasSetIsObject = set; }
  2330. bool HasFuncExprNameReference() const { return m_hasFunExprNameReference; }
  2331. void SetFuncExprNameReference(bool value) { m_hasFunExprNameReference = value; }
  2332. bool GetChildCallsEval() const { return m_ChildCallsEval; }
  2333. void SetChildCallsEval(bool value) { m_ChildCallsEval = value; }
  2334. bool GetCallsEval() const { return m_CallsEval; }
  2335. void SetCallsEval(bool set) { m_CallsEval = set; }
  2336. bool HasReferenceableBuiltInArguments() const { return m_hasReferenceableBuiltInArguments; }
  2337. void SetHasReferenceableBuiltInArguments(bool value) { m_hasReferenceableBuiltInArguments = value; }
  2338. // Used for the debug purpose. This is to avoid setting all locals to non-local-referenced, multiple time for each child function.
  2339. bool HasDoneAllNonLocalReferenced() const { return m_hasDoneAllNonLocalReferenced; }
  2340. void SetHasDoneAllNonLocalReferenced(bool set) { m_hasDoneAllNonLocalReferenced = set; }
  2341. // 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.
  2342. bool HasFunctionCompiledSent() const { return m_hasFunctionCompiledSent; }
  2343. void SetHasFunctionCompiledSent(bool set) { m_hasFunctionCompiledSent = set; }
  2344. #if DBG_DUMP
  2345. void DumpStatementMaps();
  2346. void Dump();
  2347. void PrintStatementSourceLine(uint statementIndex);
  2348. void PrintStatementSourceLineFromStartOffset(uint cchStartOffset);
  2349. void DumpScopes();
  2350. #endif
  2351. uint GetStatementStartOffset(const uint statementIndex);
  2352. #ifdef IR_VIEWER
  2353. void GetSourceLineFromStartOffset(const uint startOffset, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2354. ULONG * line, LONG * col);
  2355. void GetStatementSourceInfo(const uint statementIndex, LPCUTF8 *sourceBegin, LPCUTF8 *sourceEnd,
  2356. ULONG * line, LONG * col);
  2357. #endif
  2358. HRESULT RegisterFunction(BOOL fChangeMode, BOOL fOnlyCurrent = FALSE);
  2359. HRESULT ReportScriptCompiled();
  2360. HRESULT ReportFunctionCompiled();
  2361. void SetEntryToProfileMode();
  2362. void CheckAndRegisterFuncToDiag(ScriptContext *scriptContext);
  2363. void SetEntryToDeferParseForDebugger();
  2364. void ResetEntryPoint();
  2365. void CleanupToReparse();
  2366. void AddDeferParseAttribute();
  2367. void RemoveDeferParseAttribute();
  2368. #if DBG
  2369. void MustBeInDebugMode();
  2370. #endif
  2371. static bool IsDummyGlobalRetStatement(const regex::Interval *sourceSpan)
  2372. {
  2373. Assert(sourceSpan != nullptr);
  2374. return sourceSpan->begin == 0 && sourceSpan->end == 0;
  2375. }
  2376. static void GetShortNameFromUrl(__in LPCWSTR pchUrl, _Out_writes_z_(cchBuffer) LPWSTR pchShortName, __in size_t cchBuffer);
  2377. template<class Fn>
  2378. void MapLoopHeaders(Fn fn) const
  2379. {
  2380. if(this->loopHeaderArray)
  2381. {
  2382. for(uint i = 0; i < loopCount; i++)
  2383. {
  2384. fn(i , &this->loopHeaderArray[i]);
  2385. }
  2386. }
  2387. }
  2388. template <class Fn>
  2389. void MapEntryPoints(Fn fn) const
  2390. {
  2391. if (this->entryPoints)
  2392. {
  2393. this->entryPoints->Map([&fn] (int index, RecyclerWeakReference<FunctionEntryPointInfo>* entryPoint) {
  2394. FunctionEntryPointInfo* strongRef = entryPoint->Get();
  2395. if (strongRef)
  2396. {
  2397. fn(index, strongRef);
  2398. }
  2399. });
  2400. }
  2401. }
  2402. bool DoJITLoopBody() const
  2403. {
  2404. return IsJitLoopBodyPhaseEnabled() && this->loopHeaderArray != nullptr;
  2405. }
  2406. bool ForceJITLoopBody() const
  2407. {
  2408. return IsJitLoopBodyPhaseForced() && !this->GetHasTry();
  2409. }
  2410. bool IsGeneratorAndJitIsDisabled()
  2411. {
  2412. return this->IsGenerator() && !(CONFIG_ISENABLED(Js::JitES6GeneratorsFlag) && !this->GetHasTry());
  2413. }
  2414. FunctionBodyFlags * GetAddressOfFlags() { return &this->flags; }
  2415. Js::RegSlot GetRestParamRegSlot();
  2416. public:
  2417. void RecordConstant(RegSlot location, Var var);
  2418. private:
  2419. inline void CheckEmpty();
  2420. inline void CheckNotExecuting();
  2421. SmallSpanSequence *GetThrowSpanSequence(DWORD_PTR codeAddress, uint loopNum);
  2422. BOOL GetMatchingStatementMap(StatementData &data, int statementIndex, FunctionBody *inlinee);
  2423. #if ENABLE_NATIVE_CODEGEN
  2424. int GetStatementIndexFromNativeOffset(SmallSpanSequence *pThrowSpanSequence, uint32 nativeOffset);
  2425. int GetStatementIndexFromNativeAddress(SmallSpanSequence *pThrowSpanSequence, DWORD_PTR codeAddress, DWORD_PTR nativeBaseAddress);
  2426. #endif
  2427. void EnsureAuxStatementData();
  2428. StatementAdjustmentRecordList* GetStatementAdjustmentRecords();
  2429. #ifdef DYNAMIC_PROFILE_MUTATOR
  2430. friend class DynamicProfileMutator;
  2431. friend class DynamicProfileMutatorImpl;
  2432. #endif
  2433. friend class RemoteFunctionBody;
  2434. };
  2435. typedef SynchronizableList<FunctionBody*, JsUtil::List<FunctionBody*, ArenaAllocator, false, Js::FreeListedRemovePolicy> > FunctionBodyList;
  2436. struct ScopeSlots
  2437. {
  2438. public:
  2439. static uint const MaxEncodedSlotCount = USHORT_MAX;
  2440. // The slot index is at the same location as the vtable, so that we can distinguish between scope slot and frame display
  2441. static uint const EncodedSlotCountSlotIndex = 0;
  2442. static uint const ScopeMetadataSlotIndex = 1; // Either a FunctionBody* or DebuggerScope*
  2443. static uint const FirstSlotIndex = 2;
  2444. public:
  2445. ScopeSlots(Var* slotArray) : slotArray(slotArray)
  2446. {
  2447. }
  2448. bool IsFunctionScopeSlotArray()
  2449. {
  2450. return FunctionBody::Is(slotArray[ScopeMetadataSlotIndex]);
  2451. }
  2452. FunctionBody* GetFunctionBody()
  2453. {
  2454. Assert(IsFunctionScopeSlotArray());
  2455. return (FunctionBody*)(slotArray[ScopeMetadataSlotIndex]);
  2456. }
  2457. DebuggerScope* GetDebuggerScope()
  2458. {
  2459. Assert(!IsFunctionScopeSlotArray());
  2460. return (DebuggerScope*)(slotArray[ScopeMetadataSlotIndex]);
  2461. }
  2462. Var GetScopeMetadataRaw() const
  2463. {
  2464. return slotArray[ScopeMetadataSlotIndex];
  2465. }
  2466. void SetScopeMetadata(Var scopeMetadataObj)
  2467. {
  2468. slotArray[ScopeMetadataSlotIndex] = scopeMetadataObj;
  2469. }
  2470. uint GetCount() const
  2471. {
  2472. return ::Math::PointerCastToIntegralTruncate<uint>(slotArray[EncodedSlotCountSlotIndex]);
  2473. }
  2474. void SetCount(uint count)
  2475. {
  2476. slotArray[EncodedSlotCountSlotIndex] = (Var)min<uint>(count, ScopeSlots::MaxEncodedSlotCount);
  2477. }
  2478. Var Get(uint i) const
  2479. {
  2480. Assert(i < GetCount());
  2481. return slotArray[i + FirstSlotIndex];
  2482. }
  2483. void Set(uint i, Var value)
  2484. {
  2485. Assert(i < GetCount());
  2486. slotArray[i + FirstSlotIndex] = value;
  2487. }
  2488. template<class Fn>
  2489. void Map(Fn fn)
  2490. {
  2491. uint count = GetCount();
  2492. for(uint i = 0; i < count; i++)
  2493. {
  2494. fn(GetSlot[i]);
  2495. }
  2496. }
  2497. // The first pointer sized value in the object for scope slots is the count, while it is a vtable
  2498. // for Activation object or with scope (a recyclable object)
  2499. // VTable values are always > 64K because they are a pointer, hence anything less than that implies
  2500. // a slot array.
  2501. // CONSIDER: Use TaggedInt instead of range of slot count to distinguish slot array with others.
  2502. static bool Is(void* object)
  2503. {
  2504. size_t slotCount = *((size_t*)object);
  2505. if(slotCount <= MaxEncodedSlotCount)
  2506. {
  2507. return true;
  2508. }
  2509. return false;
  2510. }
  2511. private:
  2512. Var* slotArray;
  2513. };
  2514. enum ScopeType
  2515. {
  2516. ScopeType_ActivationObject,
  2517. ScopeType_SlotArray,
  2518. ScopeType_WithScope
  2519. };
  2520. // A FrameDisplay encodes a FunctionObject's scope chain. It is an array of scopes, where each scope can be either an inline slot array
  2521. // or a RecyclableObject. A FrameDisplay for a given FunctionObject will consist of the FrameDisplay from it's enclosing scope, with any additional
  2522. // scopes prepended. Due to with statements etc. a function may introduce multiple scopes to the FrameDisplay.
  2523. struct FrameDisplay
  2524. {
  2525. FrameDisplay(uint16 len, bool strictMode = false) :
  2526. tag(true),
  2527. length(len),
  2528. strictMode(strictMode)
  2529. #if _M_X64
  2530. , unused(0)
  2531. #endif
  2532. {
  2533. }
  2534. void SetTag(bool tag) { this->tag = tag; }
  2535. void SetItem(uint index, void* item);
  2536. void *GetItem(uint index);
  2537. uint16 GetLength() const { return length; }
  2538. void SetLength(uint16 len) { this->length = len; }
  2539. bool GetStrictMode() const { return strictMode; }
  2540. void SetStrictMode(bool flag) { this->strictMode = flag; }
  2541. void** GetDataAddress() { return (void**)&this->scopes; }
  2542. static uint32 GetOffsetOfStrictMode() { return offsetof(FrameDisplay, strictMode); }
  2543. static uint32 GetOffsetOfLength() { return offsetof(FrameDisplay, length); }
  2544. static uint32 GetOffsetOfScopes() { return offsetof(FrameDisplay, scopes); }
  2545. static ScopeType GetScopeType(void* scope);
  2546. private:
  2547. bool tag; // Tag it so that the NativeCodeGenerator::IsValidVar would not think this is var
  2548. bool strictMode;
  2549. uint16 length;
  2550. #if defined(_M_X64_OR_ARM64)
  2551. uint32 unused;
  2552. #endif
  2553. void* scopes[];
  2554. };
  2555. #pragma region Function Body helper classes
  2556. #pragma region Debugging related source classes
  2557. // Contains only the beginning part of the statement. This will mainly used in SmallSpanSequence which will further be compressed
  2558. // and stored in the buffer
  2559. struct StatementData
  2560. {
  2561. StatementData()
  2562. : sourceBegin(0),
  2563. bytecodeBegin(0)
  2564. {
  2565. }
  2566. int sourceBegin;
  2567. int bytecodeBegin;
  2568. };
  2569. struct StatementLocation
  2570. {
  2571. Js::FunctionBody* function;
  2572. regex::Interval statement;
  2573. regex::Interval bytecodeSpan;
  2574. };
  2575. // Small span in the Statement buffer of the SmallSpanSequence
  2576. struct SmallSpan
  2577. {
  2578. ushort sourceBegin;
  2579. ushort bytecodeBegin;
  2580. SmallSpan(uint32 val)
  2581. {
  2582. sourceBegin = (ushort)(val >> 16);
  2583. bytecodeBegin = (ushort)(val & 0x0000FFFF);
  2584. }
  2585. operator unsigned int()
  2586. {
  2587. return (uint32)sourceBegin << 16 | bytecodeBegin;
  2588. }
  2589. };
  2590. // Iterator which contains the state at particular index. These values will used when fetching next item from
  2591. // SmallSpanSequence
  2592. class SmallSpanSequenceIter
  2593. {
  2594. friend class SmallSpanSequence;
  2595. public:
  2596. SmallSpanSequenceIter()
  2597. : accumulatedIndex(-1),
  2598. accumulatedSourceBegin(0),
  2599. accumulatedBytecodeBegin(0),
  2600. indexOfActualOffset(0)
  2601. {
  2602. }
  2603. // Below are used for fast access when the last access happened nearby.
  2604. // so the actual index would be accumulatedIndex / 2 + (remainder for which byte).
  2605. int accumulatedIndex;
  2606. int accumulatedSourceBegin;
  2607. int accumulatedBytecodeBegin;
  2608. int indexOfActualOffset;
  2609. };
  2610. // This class compacts the range of the statement to BYTEs instead of ints.
  2611. // Instead of having start and end as int32s we will have them stored in bytes, and they will be
  2612. // treated as start offset and end offset.
  2613. // For simplicity, this class should be heap allocated, since it can be allocated from either the background
  2614. // or main thread.
  2615. class SmallSpanSequence
  2616. {
  2617. friend class SmallSpanSequenceIter;
  2618. friend class ByteCodeBufferBuilder;
  2619. friend class ByteCodeBufferReader;
  2620. private:
  2621. // Each item in the list contains two set of begins (one for bytecode and for sourcespan).
  2622. // The allowed valued for source and bytecode span is in between SHORT_MAX - 1 to SHORT_MIN (inclusive).
  2623. // otherwise its a miss
  2624. JsUtil::GrowingUint32HeapArray * pStatementBuffer;
  2625. // Contains list of values which are missed in StatementBuffer.
  2626. JsUtil::GrowingUint32HeapArray * pActualOffsetList;
  2627. // The first value of the sequence
  2628. int baseValue;
  2629. BOOL GetRangeAt(int index, SmallSpanSequenceIter &iter, int * pCountOfMissed, StatementData & data);
  2630. ushort GetDiff(int current, int prev);
  2631. public:
  2632. SmallSpanSequence();
  2633. ~SmallSpanSequence()
  2634. {
  2635. Cleanup();
  2636. }
  2637. void Cleanup()
  2638. {
  2639. if (pStatementBuffer != nullptr)
  2640. {
  2641. HeapDelete(pStatementBuffer);
  2642. }
  2643. if (pActualOffsetList != nullptr)
  2644. {
  2645. HeapDelete(pActualOffsetList);
  2646. }
  2647. }
  2648. // Trys to match passed bytecode in the statement, and returns the statement which includes that.
  2649. BOOL GetMatchingStatementFromBytecode(int bytecode, SmallSpanSequenceIter &iter, StatementData & data);
  2650. // Record the statement data in the statement buffer in the compressed manner.
  2651. BOOL RecordARange(SmallSpanSequenceIter &iter, StatementData * data);
  2652. // Reset the accumulator's state and value.
  2653. void Reset(SmallSpanSequenceIter &iter);
  2654. uint32 Count() const { return pStatementBuffer ? pStatementBuffer->Count() : 0; }
  2655. BOOL Item(int index, SmallSpanSequenceIter &iter, StatementData &data);
  2656. // Below function will not change any state, so it will not alter accumulated index and value
  2657. BOOL Seek(int index, StatementData & data);
  2658. SmallSpanSequence * Clone();
  2659. };
  2660. #pragma endregion
  2661. // This container represent the property ids for the locals which are placed at direct slot
  2662. // and list of formals args if user has not used the arguments object in the script for the current function
  2663. struct PropertyIdOnRegSlotsContainer
  2664. {
  2665. PropertyId * propertyIdsForRegSlots;
  2666. uint length;
  2667. PropertyIdArray * propertyIdsForFormalArgs;
  2668. PropertyIdOnRegSlotsContainer();
  2669. static PropertyIdOnRegSlotsContainer * New(Recycler * recycler);
  2670. void CreateRegSlotsArray(Recycler * recycler, uint _length);
  2671. void SetFormalArgs(PropertyIdArray * formalArgs);
  2672. // Helper methods
  2673. void Insert(RegSlot reg, PropertyId propId);
  2674. void FetchItemAt(uint index, FunctionBody *pFuncBody, __out PropertyId *pPropId, __out RegSlot *pRegSlot);
  2675. // Whether reg belongs to non-temp locals
  2676. bool IsRegSlotFormal(RegSlot reg);
  2677. };
  2678. // Flags for the DebuggerScopeProperty object.
  2679. typedef int DebuggerScopePropertyFlags;
  2680. const int DebuggerScopePropertyFlags_None = 0x000000000;
  2681. const int DebuggerScopePropertyFlags_Const = 0x000000001;
  2682. const int DebuggerScopePropertyFlags_CatchObject = 0x000000002;
  2683. const int DebuggerScopePropertyFlags_WithObject = 0x000000004;
  2684. const int DebuggerScopePropertyFlags_ForInOrOfCollection = 0x000000008;
  2685. // Used to store local property info for with/catch objects, lets, or consts
  2686. // that are needed for the debugger.
  2687. class DebuggerScopeProperty
  2688. {
  2689. public:
  2690. Js::PropertyId propId; // The property ID of the scope variable.
  2691. RegSlot location; // Contains the location of the scope variable (regslot, slotarray, direct).
  2692. int byteCodeInitializationOffset; // The byte code offset used when comparing let/const variables for dead zone exclusion debugger side.
  2693. DebuggerScopePropertyFlags flags; // Flags for the property.
  2694. bool IsConst() const { return (flags & DebuggerScopePropertyFlags_Const) != 0; }
  2695. bool IsCatchObject() const { return (flags & DebuggerScopePropertyFlags_CatchObject) != 0; }
  2696. bool IsWithObject() const { return (flags & DebuggerScopePropertyFlags_WithObject) != 0; }
  2697. bool IsForInOrForOfCollectionScope() const { return (flags & DebuggerScopePropertyFlags_ForInOrOfCollection) != 0; }
  2698. public:
  2699. // Determines if the current property is in a dead zone. Note that the property makes
  2700. // no assumptions about what scope it's in, that is determined by DebuggerScope.
  2701. // byteCodeOffset - The current offset in bytecode that the debugger is at.
  2702. bool IsInDeadZone(int byteCodeOffset) const
  2703. {
  2704. if (IsForInOrForOfCollectionScope())
  2705. {
  2706. // These are let/const loop variables of a for-in or for-of loop
  2707. // in the scope for the collection expression. They are always
  2708. // in TDZ in this scope, never initialized by the bytecode.
  2709. return true;
  2710. }
  2711. if (this->byteCodeInitializationOffset == Constants::InvalidByteCodeOffset && !(IsCatchObject() || IsWithObject()))
  2712. {
  2713. 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.");
  2714. return false;
  2715. }
  2716. return byteCodeOffset < this->byteCodeInitializationOffset;
  2717. }
  2718. };
  2719. // Used to track with, catch, and block scopes for the debugger to determine context.
  2720. class DebuggerScope
  2721. {
  2722. public:
  2723. typedef JsUtil::List<DebuggerScopeProperty> DebuggerScopePropertyList;
  2724. DebuggerScope(Recycler* recycler, DiagExtraScopesType scopeType, RegSlot scopeLocation, int rangeBegin)
  2725. : scopeType(scopeType),
  2726. scopeProperties(nullptr),
  2727. parentScope(nullptr),
  2728. siblingScope(nullptr),
  2729. scopeLocation(scopeLocation),
  2730. recycler(recycler)
  2731. {
  2732. this->range.begin = rangeBegin;
  2733. this->range.end = -1;
  2734. }
  2735. DebuggerScope * GetSiblingScope(RegSlot location, FunctionBody *functionBody);
  2736. void AddProperty(RegSlot location, Js::PropertyId propertyId, DebuggerScopePropertyFlags flags);
  2737. bool GetPropertyIndex(Js::PropertyId propertyId, int& i);
  2738. bool IsOffsetInScope(int offset) const;
  2739. bool Contains(Js::PropertyId propertyId, RegSlot location) const;
  2740. bool IsBlockScope() const;
  2741. bool IsBlockObjectScope() const
  2742. {
  2743. return this->scopeType == Js::DiagBlockScopeInObject;
  2744. }
  2745. bool IsCatchScope() const;
  2746. bool IsWithScope() const;
  2747. bool IsSlotScope() const;
  2748. bool HasProperties() const;
  2749. bool IsAncestorOf(const DebuggerScope* potentialChildScope);
  2750. bool AreAllPropertiesInDeadZone(int byteCodeOffset) const;
  2751. RegSlot GetLocation() const { Assert(IsOwnScope()); return scopeLocation; }
  2752. bool IsOwnScope() const { return scopeLocation != Js::Constants::NoRegister; }
  2753. bool TryGetProperty(Js::PropertyId propertyId, RegSlot location, DebuggerScopeProperty* outScopeProperty) const;
  2754. bool TryGetValidProperty(Js::PropertyId propertyId, RegSlot location, int offset, DebuggerScopeProperty* outScopeProperty, bool* isInDeadZone) const;
  2755. bool UpdatePropertyInitializationOffset(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  2756. void UpdateDueToByteCodeRegeneration(DiagExtraScopesType scopeType, int start, RegSlot scopeLocation);
  2757. void UpdatePropertiesInForInOrOfCollectionScope();
  2758. void SetParentScope(DebuggerScope* parentScope) { this->parentScope = parentScope; }
  2759. DebuggerScope* GetParentScope() const { return parentScope; }
  2760. DebuggerScope* FindCommonAncestor(DebuggerScope* debuggerScope);
  2761. int GetEnd() const { return range.end; }
  2762. int GetStart() const { return range.begin; }
  2763. void SetScopeLocation(RegSlot scopeLocation) { this->scopeLocation = scopeLocation; }
  2764. void SetBegin(int begin);
  2765. void SetEnd(int end);
  2766. #if DBG
  2767. void Dump();
  2768. PCWSTR GetDebuggerScopeTypeString(DiagExtraScopesType scopeType);
  2769. #endif
  2770. public:
  2771. // The list of scope properties in this scope object.
  2772. // For with scope: Has 1 property that represents the scoped object.
  2773. // For catch scope: Has 1 property that represents the exception object.
  2774. // For block scope: Has 0-n properties that represent let/const variables in that scope.
  2775. DebuggerScopePropertyList* scopeProperties;
  2776. DiagExtraScopesType scopeType; // The type of scope being represented (With, Catch, or Block scope).
  2777. DebuggerScope* siblingScope; // Valid only when current scope is slot/activationobject and symbols are on direct regslot
  2778. static const int InvalidScopeIndex = -1;
  2779. private:
  2780. int GetScopeDepth() const;
  2781. bool UpdatePropertyInitializationOffsetInternal(RegSlot location, Js::PropertyId propertyId, int byteCodeOffset, bool isFunctionDeclaration = false);
  2782. void EnsurePropertyListIsAllocated();
  2783. private:
  2784. DebuggerScope* parentScope;
  2785. regex::Interval range; // The start and end byte code writer offsets used when comparing where the debugger is currently stopped at (breakpoint location).
  2786. RegSlot scopeLocation;
  2787. Recycler* recycler;
  2788. };
  2789. class ScopeObjectChain
  2790. {
  2791. public:
  2792. typedef JsUtil::List<DebuggerScope*> ScopeObjectChainList;
  2793. ScopeObjectChain(Recycler* recycler)
  2794. : pScopeChain(nullptr)
  2795. {
  2796. pScopeChain = RecyclerNew(recycler, ScopeObjectChainList, recycler);
  2797. }
  2798. // This function will return DebuggerScopeProperty when the property is found and correctly in the range.
  2799. // 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,
  2800. // and isConst will be updated.
  2801. // If the property is not found at all, it will return false, and isPropertyInDebuggerScope will be false.
  2802. bool TryGetDebuggerScopePropertyInfo(PropertyId propertyId, RegSlot location, int offset, bool* isPropertyInDebuggerScope, bool *isConst, bool* isInDeadZone);
  2803. // List of all Scope Objects in a function. Scopes are added to this list as when they are created in bytecode gen part.
  2804. ScopeObjectChainList* pScopeChain;
  2805. };
  2806. #pragma endregion
  2807. } // namespace Js