JavascriptArray.inl 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. namespace Js
  7. {
  8. //
  9. // Walks all the nodes in this BTree in sorted order.
  10. //
  11. template<typename Func>
  12. void SegmentBTree::Walk(Func& func) const
  13. {
  14. if (!IsLeaf())
  15. {
  16. children[0].Walk(func);
  17. }
  18. for (unsigned int i = 0; i < segmentCount; i++)
  19. {
  20. Assert(keys[i] == segments[i]->left);
  21. func(segments[i]);
  22. if (!IsLeaf())
  23. {
  24. children[i + 1].Walk(func);
  25. }
  26. }
  27. }
  28. template <typename Fn>
  29. SparseArraySegmentBase *
  30. JavascriptArray::ForEachSegment(Fn fn) const
  31. {
  32. return ForEachSegment(this->head, fn);
  33. }
  34. template <typename Fn>
  35. SparseArraySegmentBase *
  36. JavascriptArray::ForEachSegment(SparseArraySegmentBase * segment, Fn fn)
  37. {
  38. DebugOnly(uint32 lastindex = segment? segment->left : 0);
  39. SparseArraySegmentBase * current = segment;
  40. while (current)
  41. {
  42. // Verify that all the segment are sorted
  43. Assert(current->left >= lastindex);
  44. if (fn(current))
  45. {
  46. break;
  47. }
  48. DebugOnly(lastindex = current->left + current->length);
  49. current = current->next;
  50. }
  51. return current;
  52. }
  53. //
  54. // Link prev and current. If prev is NULL, make current the head segment.
  55. //
  56. template<>
  57. inline void JavascriptArray::LinkSegments(SparseArraySegment<int>* prev, SparseArraySegment<int>* current)
  58. {
  59. if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
  60. {
  61. prev = this->ReallocNonLeafSegment(prev, current);
  62. }
  63. else
  64. {
  65. LinkSegmentsCommon(prev, current);
  66. }
  67. }
  68. template<>
  69. inline void JavascriptArray::LinkSegments(SparseArraySegment<double>* prev, SparseArraySegment<double>* current)
  70. {
  71. if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
  72. {
  73. prev = this->ReallocNonLeafSegment(prev, current);
  74. }
  75. else
  76. {
  77. LinkSegmentsCommon(prev, current);
  78. }
  79. }
  80. template<typename T>
  81. inline void JavascriptArray::LinkSegments(SparseArraySegment<T>* prev, SparseArraySegment<T>* current)
  82. {
  83. LinkSegmentsCommon(prev, current);
  84. }
  85. template<typename T>
  86. inline SparseArraySegment<T>* JavascriptArray::ReallocNonLeafSegment(SparseArraySegment<T> *seg, SparseArraySegmentBase* nextSeg)
  87. {
  88. // Find the segment prior to seg.
  89. SparseArraySegmentBase *prior = nullptr;
  90. if (seg != this->head)
  91. {
  92. for (prior = this->head; prior->next != seg; prior = prior->next)
  93. {
  94. Assert(prior->next);
  95. }
  96. }
  97. Recycler *recycler = this->GetScriptContext()->GetRecycler();
  98. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, seg->left, seg->length, nextSeg);
  99. js_memcpy_s(newSeg->elements, sizeof(T) * seg->length, seg->elements, sizeof(T) * seg->length);
  100. LinkSegmentsCommon(prior, newSeg);
  101. LinkSegmentsCommon(newSeg, nextSeg);
  102. if (GetLastUsedSegment() == seg)
  103. {
  104. SetLastUsedSegment(newSeg);
  105. }
  106. SegmentBTree * segmentMap = GetSegmentMap();
  107. if (segmentMap)
  108. {
  109. segmentMap->SwapSegment(seg->left, seg, newSeg);
  110. }
  111. return newSeg;
  112. }
  113. /*static*/
  114. template<typename T, uint InlinePropertySlots>
  115. __inline SparseArraySegment<typename T::TElement> *JavascriptArray::InitArrayAndHeadSegment(
  116. T *const array,
  117. const uint32 length,
  118. const uint32 size,
  119. const bool wasZeroAllocated)
  120. {
  121. Assert(!array->HasSegmentMap());
  122. SparseArraySegment<typename T::TElement>* head =
  123. DetermineInlineHeadSegmentPointer<T, InlinePropertySlots, false>(array);
  124. if(wasZeroAllocated)
  125. {
  126. if(length != 0)
  127. {
  128. head->length = length;
  129. }
  130. head->size = size;
  131. }
  132. else
  133. {
  134. new(head) SparseArraySegment<typename T::TElement>(0, length, size);
  135. }
  136. array->SetHeadAndLastUsedSegment(head);
  137. array->SetHasNoMissingValues();
  138. return head;
  139. }
  140. template<typename unitType, typename className>
  141. __inline className * JavascriptArray::New(Recycler * recycler, DynamicType * type)
  142. {
  143. size_t allocationPlusSize;
  144. uint alignedInlineElementSlots;
  145. DetermineAllocationSize<className, 0>(
  146. SparseArraySegmentBase::SMALL_CHUNK_SIZE,
  147. &allocationPlusSize,
  148. &alignedInlineElementSlots);
  149. return RecyclerNewPlusZ(recycler, allocationPlusSize, className, type, alignedInlineElementSlots);
  150. }
  151. /*static*/
  152. template<typename unitType, typename className, uint inlineSlots>
  153. className* JavascriptArray::New(uint32 length, DynamicType* arrayType, Recycler* recycler)
  154. {
  155. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  156. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  157. if(length > SparseArraySegmentBase::HEAD_CHUNK_SIZE)
  158. {
  159. // Use empty segment until we try to store something. Call AllocateHead() at that point.
  160. return RecyclerNew(recycler, className, length, arrayType);
  161. }
  162. size_t allocationPlusSize;
  163. uint alignedInlineElementSlots;
  164. className* array;
  165. if (!length) // zero length - use default head chunk size
  166. {
  167. DetermineAllocationSize<className, inlineSlots>(
  168. SparseArraySegmentBase::HEAD_CHUNK_SIZE,
  169. &allocationPlusSize,
  170. &alignedInlineElementSlots);
  171. }
  172. else //Small array
  173. {
  174. Assert(length <= SparseArraySegmentBase::HEAD_CHUNK_SIZE);
  175. DetermineAllocationSize<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
  176. }
  177. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  178. SparseArraySegment<unitType> *head =
  179. InitArrayAndHeadSegment<className, inlineSlots>(array, 0, alignedInlineElementSlots, true);
  180. head->FillSegmentBuffer(0, alignedInlineElementSlots);
  181. return array;
  182. }
  183. //
  184. // Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
  185. // inline is that the segment space will never get freed unless the Array is collected.
  186. //
  187. /*static*/
  188. template<typename unitType, typename className, uint inlineSlots>
  189. className* JavascriptArray::NewLiteral(uint32 length, DynamicType* arrayType, Recycler* recycler)
  190. {
  191. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  192. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  193. className* array;
  194. if(HasInlineHeadSegment(length))
  195. {
  196. size_t allocationPlusSize;
  197. uint alignedInlineElementSlots;
  198. if(!length)
  199. {
  200. DetermineAllocationSize<className, inlineSlots>(
  201. SparseArraySegmentBase::SMALL_CHUNK_SIZE,
  202. &allocationPlusSize,
  203. &alignedInlineElementSlots);
  204. }
  205. else
  206. {
  207. DetermineAllocationSize<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
  208. }
  209. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  210. // An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
  211. // doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
  212. // the values and don't update the length, so update the length here.
  213. //
  214. // An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
  215. // missing values (after this update to length), it won't have missing values once the initialization is complete, so
  216. // maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
  217. // a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
  218. // values.
  219. SparseArraySegment<unitType> *head =
  220. InitArrayAndHeadSegment<className, inlineSlots>(array, length, alignedInlineElementSlots, true);
  221. head->FillSegmentBuffer(length, alignedInlineElementSlots);
  222. Assert(array->HasNoMissingValues());
  223. return array;
  224. }
  225. size_t allocationPlusSize;
  226. DetermineAllocationSize<className, inlineSlots>(0, &allocationPlusSize);
  227. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  228. SparseArraySegment<unitType> *seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, length);
  229. array->SetHeadAndLastUsedSegment(seg);
  230. array->SetHasNoMissingValues();
  231. // An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
  232. // doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
  233. // the values and don't update the length, so update the length here.
  234. //
  235. // An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
  236. // missing values (after this update to length), it won't have missing values once the initialization is complete, so
  237. // maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
  238. // a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
  239. // values.
  240. array->head->length = length;
  241. return array;
  242. }
  243. #if ENABLE_COPYONACCESS_ARRAY
  244. //
  245. // Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
  246. // inline is that the segment space will never get freed unless the Array is collected.
  247. //
  248. /*static*/
  249. template<typename unitType, typename className, uint inlineSlots>
  250. className* JavascriptArray::NewCopyOnAccessLiteral(DynamicType* arrayType, ArrayCallSiteInfo *arrayInfo, FunctionBody *functionBody, const Js::AuxArray<int32> *ints, Recycler* recycler)
  251. {
  252. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  253. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  254. Assert(arrayInfo->IsNativeIntArray());
  255. className* array = RecyclerNewZ(recycler, JavascriptCopyOnAccessNativeIntArray, ints->count, arrayType);
  256. JavascriptLibrary *lib = functionBody->GetScriptContext()->GetLibrary();
  257. SparseArraySegment<unitType> *seg;
  258. if (JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(functionBody->GetScriptContext()->GetLibrary() , arrayInfo))
  259. {
  260. seg = lib->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(arrayInfo->copyOnAccessArrayCacheIndex);
  261. }
  262. else
  263. {
  264. seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, ints->count);
  265. }
  266. if (!JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(lib, arrayInfo))
  267. {
  268. JavascriptOperators::AddIntsToArraySegment(seg, ints);
  269. arrayInfo->copyOnAccessArrayCacheIndex = lib->cacheForCopyOnAccessArraySegments->AddSegment(seg);
  270. }
  271. array->SetHeadAndLastUsedSegment(reinterpret_cast<SparseArraySegmentBase *>(arrayInfo->copyOnAccessArrayCacheIndex)); // storing index in head on purpose: expect AV if treated as other array objects
  272. #if ENABLE_DEBUG_CONFIG_OPTIONS
  273. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  274. {
  275. Output::Print(L"Create copy-on-access array: func(#%2d) index(%d) length(%d)\n",
  276. functionBody->GetFunctionNumber(), lib->cacheForCopyOnAccessArraySegments->GetCount(), ints->count);
  277. Output::Flush();
  278. }
  279. #endif
  280. return array;
  281. }
  282. #endif
  283. template<class T, uint InlinePropertySlots>
  284. __inline T *JavascriptArray::New(
  285. void *const stackAllocationPointer,
  286. const uint32 length,
  287. DynamicType *const arrayType)
  288. {
  289. Assert(arrayType);
  290. if(stackAllocationPointer)
  291. {
  292. bool isSufficientSpaceForInlinePropertySlots;
  293. const uint availableInlineElementSlots =
  294. DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
  295. T::StackAllocationSize,
  296. &isSufficientSpaceForInlinePropertySlots);
  297. if(isSufficientSpaceForInlinePropertySlots)
  298. {
  299. T *const array = new(stackAllocationPointer) T(length, arrayType);
  300. if(length <= availableInlineElementSlots)
  301. {
  302. SparseArraySegment<typename T::TElement> *const head =
  303. InitArrayAndHeadSegment<T, InlinePropertySlots>(array, 0, availableInlineElementSlots, false);
  304. head->FillSegmentBuffer(0, availableInlineElementSlots);
  305. }
  306. else
  307. {
  308. // Not enough room to allocate all required element slots inline. Leave the head segment as the empty
  309. // segment and let it be allocated as necessary.
  310. }
  311. Assert(array->HasNoMissingValues());
  312. return array;
  313. }
  314. }
  315. return New<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
  316. }
  317. template<class T, uint InlinePropertySlots>
  318. __inline T *JavascriptArray::NewLiteral(
  319. void *const stackAllocationPointer,
  320. const uint32 length,
  321. DynamicType *const arrayType)
  322. {
  323. Assert(arrayType);
  324. if(stackAllocationPointer)
  325. {
  326. bool isSufficientSpaceForInlinePropertySlots;
  327. const uint availableInlineElementSlots =
  328. DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
  329. T::StackAllocationSize,
  330. &isSufficientSpaceForInlinePropertySlots);
  331. if(isSufficientSpaceForInlinePropertySlots)
  332. {
  333. T *const array = new(stackAllocationPointer) T(length, arrayType);
  334. if(length <= availableInlineElementSlots)
  335. {
  336. SparseArraySegment<typename T::TElement> *const head =
  337. InitArrayAndHeadSegment<T, InlinePropertySlots>(array, length, availableInlineElementSlots, false);
  338. head->FillSegmentBuffer(length, availableInlineElementSlots);
  339. Assert(array->HasNoMissingValues());
  340. return array;
  341. }
  342. // Not enough room to allocate all required element slots inline. Allocate the head segment separately.
  343. SparseArraySegment<typename T::TElement> *const head =
  344. SparseArraySegment<typename T::TElement>::AllocateLiteralHeadSegment(arrayType->GetRecycler(), length);
  345. array->SetHeadAndLastUsedSegment(head);
  346. array->SetHasNoMissingValues();
  347. return array;
  348. }
  349. }
  350. return NewLiteral<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
  351. }
  352. template<typename T>
  353. __inline void JavascriptArray::DirectSetItemAt(uint32 itemIndex, T newValue)
  354. {
  355. Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
  356. SparseArraySegment<T> *seg = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  357. uint32 offset = itemIndex - seg->left;
  358. if(itemIndex >= seg->left && offset < seg->size)
  359. {
  360. DirectSetItemInLastUsedSegmentAt(offset, newValue);
  361. return;
  362. }
  363. DirectSetItem_Full(itemIndex, newValue);
  364. }
  365. template<typename T>
  366. __inline void JavascriptArray::DirectSetItemInLastUsedSegmentAt(const uint32 offset, const T newValue)
  367. {
  368. SparseArraySegment<T> *const seg = (SparseArraySegment<T>*)GetLastUsedSegment();
  369. Assert(seg);
  370. Assert(offset < seg->size);
  371. Assert(!(HasNoMissingValues() &&
  372. offset < seg->length &&
  373. SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]) &&
  374. seg == head));
  375. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
  376. DebugOnly(VerifyNotNeedMarshal(newValue));
  377. seg->elements[offset] = newValue;
  378. if (offset >= seg->length)
  379. {
  380. if(offset > seg->length && seg == head)
  381. {
  382. SetHasNoMissingValues(false);
  383. }
  384. seg->length = offset + 1;
  385. const uint32 itemIndex = seg->left + offset;
  386. if (this->length <= itemIndex)
  387. {
  388. this->length = itemIndex + 1;
  389. }
  390. }
  391. else if(scanForMissingValues)
  392. {
  393. ScanForMissingValues<T>();
  394. }
  395. }
  396. #if ENABLE_PROFILE_INFO
  397. template<typename T>
  398. __inline void JavascriptArray::DirectProfiledSetItemInHeadSegmentAt(
  399. const uint32 offset,
  400. const T newValue,
  401. StElemInfo *const stElemInfo)
  402. {
  403. SparseArraySegment<T> *const seg = (SparseArraySegment<T>*)head;
  404. Assert(seg);
  405. Assert(offset < seg->size);
  406. Assert(!(HasNoMissingValues() &&
  407. offset < seg->length &&
  408. SparseArraySegment<T>::IsMissingItem(&seg->elements[offset])));
  409. Assert(stElemInfo);
  410. stElemInfo->filledMissingValue = offset < seg->length && SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]);
  411. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
  412. DebugOnly(VerifyNotNeedMarshal(newValue));
  413. seg->elements[offset] = newValue;
  414. if (offset >= seg->length)
  415. {
  416. if(offset > seg->length)
  417. {
  418. SetHasNoMissingValues(false);
  419. }
  420. seg->length = offset + 1;
  421. const uint32 itemIndex = seg->left + offset;
  422. if (this->length <= itemIndex)
  423. {
  424. this->length = itemIndex + 1;
  425. }
  426. }
  427. else if(scanForMissingValues)
  428. {
  429. ScanForMissingValues<T>();
  430. }
  431. }
  432. #endif
  433. template<typename T>
  434. inline BOOL JavascriptArray::DirectGetItemAt(uint32 index, T* outVal)
  435. {
  436. #ifdef VALIDATE_ARRAY
  437. ValidateArray();
  438. #endif
  439. if (index >= length)
  440. {
  441. return false;
  442. }
  443. #ifdef VALIDATE_ARRAY
  444. T v_btree = NULL;
  445. SparseArraySegmentBase* seg_btree = nullptr;
  446. bool first_pass = true;
  447. #endif
  448. SparseArraySegmentBase* nextSeg;
  449. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  450. if (segmentMap)
  451. {
  452. SparseArraySegmentBase* matchOrNextSeg;
  453. segmentMap->Find(index, nextSeg, matchOrNextSeg);
  454. if (!nextSeg)
  455. {
  456. nextSeg = matchOrNextSeg;
  457. }
  458. }
  459. else
  460. {
  461. #ifdef VALIDATE_ARRAY
  462. SECOND_PASS:
  463. #endif
  464. nextSeg = this->GetBeginLookupSegment(index, false);
  465. }
  466. uint probeCost = 0;
  467. while (nextSeg != nullptr && nextSeg->left <= index)
  468. {
  469. uint32 limit = nextSeg->left + nextSeg->length;
  470. if (index < limit)
  471. {
  472. T* v = &((SparseArraySegment<T>*)nextSeg)->elements[index - nextSeg->left];
  473. this->SetLastUsedSegment(nextSeg);
  474. #ifdef VALIDATE_ARRAY
  475. Assert(segmentMap == GetSegmentMap());
  476. if (segmentMap && first_pass)
  477. {
  478. v_btree = *v;
  479. seg_btree= nextSeg;
  480. first_pass = false;
  481. goto SECOND_PASS;
  482. }
  483. else if (segmentMap && !first_pass)
  484. {
  485. Assert(seg_btree == nextSeg);
  486. }
  487. #endif
  488. if (SparseArraySegment<T>::IsMissingItem(v))
  489. {
  490. Assert(!(HasNoMissingValues() && nextSeg == head));
  491. return false;
  492. }
  493. *outVal = *v;
  494. return true;
  495. }
  496. nextSeg = nextSeg->next;
  497. Assert(segmentMap == GetSegmentMap());
  498. if (!segmentMap)
  499. {
  500. probeCost++;
  501. if (probeCost > SegmentBTree::GetLazyCrossOverLimit() && this->head != EmptySegment)
  502. {
  503. // Build a SegmentMap
  504. segmentMap = BuildSegmentMap();
  505. // Find the right segment
  506. SparseArraySegmentBase* matchOrNextSeg;
  507. segmentMap->Find(index, nextSeg, matchOrNextSeg);
  508. if (!nextSeg)
  509. {
  510. nextSeg = matchOrNextSeg;
  511. }
  512. }
  513. }
  514. }
  515. #ifdef VALIDATE_ARRAY
  516. Assert(segmentMap == GetSegmentMap());
  517. if (segmentMap && first_pass)
  518. {
  519. v_btree = NULL;
  520. seg_btree= nullptr;
  521. first_pass = false;
  522. goto SECOND_PASS;
  523. }
  524. else if (segmentMap && !first_pass)
  525. {
  526. Assert(v_btree == NULL && seg_btree == nullptr);
  527. }
  528. #endif
  529. return false;
  530. }
  531. template<typename T>
  532. void JavascriptArray::EnsureHead()
  533. {
  534. if (this->head == EmptySegment)
  535. {
  536. this->AllocateHead<T>();
  537. }
  538. }
  539. template<typename T>
  540. void JavascriptArray::AllocateHead()
  541. {
  542. Recycler* recycler = GetRecycler();
  543. uint32 allocLength;
  544. Assert(this->head == EmptySegment);
  545. if (this->length)
  546. {
  547. allocLength = this->length <= MaxInitialDenseLength ? this->length : SparseArraySegmentBase::HEAD_CHUNK_SIZE;
  548. this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
  549. }
  550. else
  551. {
  552. allocLength = SparseArraySegmentBase::HEAD_CHUNK_SIZE;
  553. this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
  554. }
  555. this->SetLastUsedSegment(this->head);
  556. SetHasNoMissingValues();
  557. }
  558. template<typename T>
  559. SparseArraySegment<T>* JavascriptArray::PrepareSegmentForMemOp(uint32 startIndex, uint32 length)
  560. {
  561. uint32 endIndex;
  562. if(UInt32Math::Add(startIndex, length - 1, &endIndex))
  563. {
  564. return nullptr;
  565. }
  566. if (endIndex >= this->length)
  567. {
  568. if (endIndex < JavascriptArray::InvalidIndex)
  569. {
  570. this->length = endIndex + 1;
  571. }
  572. else
  573. {
  574. return nullptr;
  575. }
  576. }
  577. this->EnsureHead<T>();
  578. Recycler* recycler = GetRecycler();
  579. //Find the segment where itemIndex is present or is at the boundary
  580. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(startIndex, false);
  581. SparseArraySegmentBase* prev = nullptr;
  582. SparseArraySegmentBase* startSeg = nullptr;
  583. SparseArraySegmentBase* endSeg = nullptr;
  584. SparseArraySegmentBase* startPrev = nullptr;
  585. uint32 growby, startOffset, endOffset;
  586. const auto FindStartAndEndSegment = [&]()
  587. {
  588. if (endIndex >= current->left + current->size)
  589. {
  590. current = (SparseArraySegment<T>*)head;
  591. }
  592. else
  593. {
  594. startSeg = endSeg = current;
  595. current = nullptr;
  596. }
  597. while (current != nullptr)
  598. {
  599. startOffset = startIndex - current->left;
  600. endOffset = endIndex - current->left;
  601. if (!startSeg)
  602. {
  603. if (startIndex <= current->left)
  604. {
  605. startPrev = prev;
  606. startSeg = current;
  607. }
  608. else if (startOffset <= current->size)
  609. {
  610. if ((nullptr == current->next) || (startIndex < current->next->left))
  611. {
  612. startPrev = prev;
  613. startSeg = current;
  614. }
  615. }
  616. }
  617. if (!endSeg)
  618. {
  619. if (endIndex <= current->left)
  620. {
  621. endSeg = current;
  622. break;
  623. }
  624. else if (endOffset <= current->size)
  625. {
  626. if ((nullptr == current->next) || (endIndex < current->next->left))
  627. {
  628. endSeg = current;
  629. break;
  630. }
  631. }
  632. }
  633. prev = current;
  634. current = (SparseArraySegment<T>*)current->next;
  635. }
  636. if (!startSeg && !endSeg)
  637. {
  638. startPrev = prev;
  639. }
  640. };
  641. const auto ResizeArrayIfStartIsOutsideArrayLength = [&]()
  642. {
  643. Assert(endSeg == nullptr);
  644. Assert(startIndex >= head->size);
  645. // Reallocate head if it meets a heuristics
  646. if (startPrev == head // prev segment is the head segment
  647. && !head->next // There is only one head segment in the array
  648. && startIndex - head->size <= MergeSegmentsLengthHeuristics // Distance to next index is relatively small
  649. )
  650. {
  651. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, startIndex + length - head->size);
  652. current->length = endIndex + 1;
  653. head = current;
  654. SetHasNoMissingValues(false);
  655. }
  656. else
  657. {
  658. //itemIndex is greater than the (left + size) of last segment in the linked list
  659. current = SparseArraySegment<T>::AllocateSegment(recycler, startIndex, length, (SparseArraySegment<T> *)nullptr);
  660. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  661. current->length = length;
  662. if (current == head)
  663. {
  664. Assert(startIndex == 0);
  665. Assert(current->length == length);
  666. SetHasNoMissingValues();
  667. }
  668. }
  669. };
  670. const auto ExtendStartSegmentForMemOp = [&]()
  671. {
  672. startOffset = startIndex - startSeg->left;
  673. if ((startIndex >= startSeg->left) && (startOffset < startSeg->size))
  674. {
  675. // startIndex is within startSeg
  676. if ((startOffset + length) > startSeg->size)
  677. {
  678. // if we don't have enough space in startSeg
  679. growby = length - (startSeg->size - startOffset);
  680. current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, growby);
  681. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  682. if (current == head)
  683. {
  684. if (startIndex > current->length)
  685. {
  686. // if it's the head segment and memset starts after the segment length, missing value is introduced
  687. SetHasNoMissingValues(false);
  688. }
  689. else if (!HasNoMissingValues())
  690. {
  691. // Have we overwritten all the missing values?
  692. if (!ScanForMissingValues<T>(0, startOffset))
  693. {
  694. SetHasNoMissingValues();
  695. }
  696. }
  697. }
  698. current->length = startOffset + length;
  699. }
  700. else
  701. {
  702. // if we have enough space in the startseg
  703. current = (Js::SparseArraySegment<T>*)startSeg;
  704. if (current == head)
  705. {
  706. if (startIndex > current->length)
  707. {
  708. // if it's the head segment and memset starts after the segment length, missing value is introduced
  709. SetHasNoMissingValues(false);
  710. }
  711. else if (!HasNoMissingValues())
  712. {
  713. // Have we overwritten all the missing values?
  714. if (!ScanForMissingValues<T>(0, startOffset))
  715. {
  716. SetHasNoMissingValues();
  717. }
  718. }
  719. }
  720. current->length = current->length > (startOffset + length) ? current->length : (startOffset + length);
  721. }
  722. }
  723. else if ((startIndex + 1) <= startSeg->left)
  724. {
  725. if (startIndex + 1 == startSeg->left && startPrev == head)
  726. {
  727. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, startIndex + length - head->size);
  728. current->length = endIndex + 1;
  729. head = current;
  730. }
  731. else
  732. {
  733. // startIndex is in between prev and startIndex
  734. current = SparseArraySegment<T>::AllocateSegment(recycler, startIndex, length, (SparseArraySegment<T> *)nullptr);
  735. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  736. if (current == head)
  737. {
  738. SetHasNoMissingValues();
  739. }
  740. current->length = length;
  741. }
  742. }
  743. else
  744. {
  745. Assert(startIndex == startSeg->left + startSeg->size);
  746. current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, length);
  747. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  748. if (current == head)
  749. {
  750. if (startIndex > current->length)
  751. {
  752. // if it's the head segment and memset starts after the segment length, missing value is introduced
  753. SetHasNoMissingValues(false);
  754. }
  755. }
  756. current->length = startOffset + length;
  757. }
  758. startSeg = current;
  759. };
  760. const auto AppendLeftOverItemsFromEndSegment = [&]()
  761. {
  762. if (!endSeg)
  763. {
  764. // end is beyond the length of the array
  765. Assert(endIndex == this->length - 1);
  766. current->next = nullptr;
  767. }
  768. else
  769. {
  770. endOffset = endIndex - endSeg->left;
  771. startOffset = startIndex - current->left;
  772. if ((endIndex >= endSeg->left) && (endOffset < endSeg->size))
  773. {
  774. // endIndex is within endSeg
  775. if (endSeg->length - 1 > endOffset)
  776. {
  777. if (startSeg != endSeg)
  778. {
  779. // we have some leftover items on endseg
  780. growby = (endSeg->length - endOffset - 1);
  781. current = ((Js::SparseArraySegment<T>*)current)->GrowByMin(recycler, growby);
  782. js_memcpy_s(((Js::SparseArraySegment<T>*)current)->elements + startOffset + length, sizeof(T)* growby, ((Js::SparseArraySegment<T>*)endSeg)->elements + endOffset + 1, sizeof(T)* growby);
  783. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  784. current->length = startOffset + length + growby;
  785. }
  786. if (current == head && HasNoMissingValues())
  787. {
  788. if (ScanForMissingValues<T>(startOffset + length, current->length))
  789. {
  790. SetHasNoMissingValues(false);
  791. }
  792. }
  793. }
  794. current->next = endSeg->next;
  795. }
  796. else if ((endIndex + 1) <= endSeg->left)
  797. {
  798. // endIndex is between endSeg and the segment before
  799. if (endIndex + 1 == endSeg->left && current == head)
  800. {
  801. // extend current to hold endSeg
  802. growby = endSeg->length;
  803. current = ((Js::SparseArraySegment<T>*)current)->GrowByMin(recycler, growby);
  804. js_memcpy_s(((Js::SparseArraySegment<T>*)current)->elements + endIndex + 1, sizeof(T)* endSeg->length, ((Js::SparseArraySegment<T>*)endSeg)->elements, sizeof(T)* endSeg->length);
  805. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  806. if (HasNoMissingValues())
  807. {
  808. if (ScanForMissingValues<T>(endIndex + 1, endIndex + growby))
  809. {
  810. SetHasNoMissingValues(false);
  811. }
  812. }
  813. current->length = endIndex + growby + 1;
  814. current->next = endSeg->next;
  815. }
  816. else
  817. {
  818. current->next = endSeg;
  819. }
  820. }
  821. else
  822. {
  823. //endIndex is at the boundary of endSeg segment at the left + size
  824. Assert(endIndex == endSeg->left + endSeg->size);
  825. current->next = endSeg->next;
  826. }
  827. }
  828. };
  829. FindStartAndEndSegment();
  830. if (startSeg == nullptr)
  831. {
  832. // if start index is greater than array length then we can add a new segment (or extend the last segment based on some heuristics)
  833. ResizeArrayIfStartIsOutsideArrayLength();
  834. }
  835. else
  836. {
  837. // once we found the start segment we extend the start segment until startIndex+length . We don't care about what was there
  838. // as they will be overwritten by the memset/ memcopy. Then we need to append items from the (startIndex+length) to array.length
  839. // from the end segment to the new array
  840. ExtendStartSegmentForMemOp();
  841. AppendLeftOverItemsFromEndSegment();
  842. }
  843. Assert(current);
  844. Assert(current->left <= startIndex);
  845. Assert((startIndex - current->left) < current->size);
  846. return current;
  847. }
  848. template<typename T>
  849. bool JavascriptArray::DirectSetItemAtRangeFromArray(uint32 toStartIndex, uint32 length, JavascriptArray *fromArray, uint32 fromStartIndex)
  850. {
  851. if (length == 0)
  852. {
  853. return true;
  854. }
  855. bool isBtree = false;
  856. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  857. isBtree = Js::Configuration::Global.flags.ForceArrayBTree;
  858. #endif
  859. if (GetSegmentMap() || fromArray->GetSegmentMap() || isBtree)
  860. {
  861. for (uint i = 0; i < length; i++)
  862. {
  863. T val;
  864. if (fromArray->DirectGetItemAt(fromStartIndex + i, &val))
  865. {
  866. DirectSetItem_Full(toStartIndex + i, val);
  867. }
  868. }
  869. return true;
  870. }
  871. SparseArraySegment<T> *toSegment = PrepareSegmentForMemOp<T>(toStartIndex, length);
  872. if (toSegment == nullptr)
  873. {
  874. return false;
  875. }
  876. Assert(fromArray->head);
  877. Assert(fromArray->length >= (fromStartIndex + length));
  878. //Find the segment where itemIndex is present or is at the boundary
  879. SparseArraySegmentBase* current = fromArray->GetBeginLookupSegment(fromStartIndex, false);
  880. Assert(current);
  881. Assert(GetSegmentMap() == nullptr && fromArray->GetSegmentMap() == nullptr);
  882. while (current && length)
  883. {
  884. int memcopySize = length;
  885. int startOffset;
  886. if (fromStartIndex >= current->left && fromStartIndex < (current->left + current->length))
  887. {
  888. startOffset = fromStartIndex - current->left;
  889. if ((startOffset + length) > current->length)
  890. {
  891. memcopySize = current->length - startOffset;
  892. }
  893. js_memcpy_s(toSegment->elements + toStartIndex, memcopySize * sizeof(T), (((Js::SparseArraySegment<T>*)current)->elements + startOffset), memcopySize * sizeof(T));
  894. fromArray->SetLastUsedSegment(current);
  895. fromStartIndex = fromStartIndex + memcopySize;
  896. toStartIndex = toStartIndex + memcopySize;
  897. length = length - memcopySize;
  898. }
  899. current = current->next;
  900. }
  901. Assert(length == 0);
  902. this->SetLastUsedSegment(toSegment);
  903. #if DBG
  904. if (Js::Configuration::Global.flags.MemOpMissingValueValidate)
  905. {
  906. if (toSegment == head)
  907. {
  908. Assert(ScanForMissingValues<T>(0, this->length) != HasNoMissingValues());
  909. }
  910. }
  911. #endif
  912. return true;
  913. }
  914. template<typename T>
  915. bool JavascriptArray::DirectSetItemAtRange(uint32 startIndex, uint32 length, T newValue)
  916. {
  917. if (startIndex == 0 && head != EmptySegment && length < head->size)
  918. {
  919. if (newValue == (T)0 || newValue == (T)(-1))
  920. {
  921. memset(((Js::SparseArraySegment<T>*)head)->elements, ((int)(intptr_t)newValue), sizeof(T)* length);
  922. }
  923. else
  924. {
  925. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)head);
  926. for (uint32 i = 0; i < length; i++)
  927. {
  928. headSegment->elements[i] = newValue;
  929. }
  930. }
  931. if (length > this->length)
  932. {
  933. this->length = length;
  934. }
  935. if (length > head->length)
  936. {
  937. head->length = length;
  938. }
  939. if (!HasNoMissingValues())
  940. {
  941. if (ScanForMissingValues<T>(length, head->length) == false)
  942. {
  943. SetHasNoMissingValues(true);
  944. }
  945. }
  946. this->SetLastUsedSegment(head);
  947. }
  948. else if (startIndex == 0 && length > this->length && (head == EmptySegment || length > head->size))
  949. {
  950. Recycler *recycler = GetRecycler();
  951. this->length = length;
  952. this->EnsureHead<T>();
  953. SparseArraySegmentBase* current = nullptr;
  954. Assert(head->size < length);
  955. current = SparseArraySegment<T>::AllocateSegment(recycler, 0, length, (SparseArraySegment<T> *)nullptr);
  956. this->SetHeadAndLastUsedSegment(current);
  957. Assert(!HasSegmentMap());
  958. SetHasNoMissingValues(true);
  959. if (newValue == (T)0 || newValue == (T)(-1))
  960. {
  961. memset(((Js::SparseArraySegment<T>*)current)->elements, ((int)(intptr_t)newValue), sizeof(T)* length);
  962. }
  963. else
  964. {
  965. for (uint32 i = 0; i < length; i++)
  966. {
  967. ((Js::SparseArraySegment<T>*)current)->elements[i] = newValue;
  968. }
  969. }
  970. this->SetLastUsedSegment(current);
  971. }
  972. else
  973. {
  974. DirectSetItemAtRangeFull<T>(startIndex, length, newValue);
  975. }
  976. return true;
  977. }
  978. template<typename T>
  979. bool JavascriptArray::DirectSetItemAtRangeFull(uint32 startIndex, uint32 length, T newValue)
  980. {
  981. if (length == 0)
  982. {
  983. return true;
  984. }
  985. bool isBtree = false;
  986. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  987. isBtree = Js::Configuration::Global.flags.ForceArrayBTree;
  988. #endif
  989. if (GetSegmentMap() || isBtree)
  990. {
  991. for (uint i = startIndex; i < startIndex + length; i++)
  992. {
  993. DirectSetItem_Full<T>(i, newValue);
  994. }
  995. return true;
  996. }
  997. SparseArraySegment<T> *current = PrepareSegmentForMemOp<T>(startIndex, length);
  998. if (current == nullptr)
  999. {
  1000. return false;
  1001. }
  1002. if (newValue == (T)0 || newValue == (T)(-1))
  1003. {
  1004. memset((((Js::SparseArraySegment<T>*)current)->elements + (startIndex - current->left)), ((int)(intptr_t)newValue), sizeof(T)* length);
  1005. }
  1006. else
  1007. {
  1008. for (uint32 i = 0; i < length; i++)
  1009. {
  1010. ((Js::SparseArraySegment<T>*)current)->elements[startIndex - current->left + i] = newValue;
  1011. }
  1012. }
  1013. this->SetLastUsedSegment(current);
  1014. #if DBG
  1015. if (Js::Configuration::Global.flags.MemOpMissingValueValidate)
  1016. {
  1017. if (current == head)
  1018. {
  1019. Assert(ScanForMissingValues<T>(0, this->length) != HasNoMissingValues());
  1020. }
  1021. }
  1022. #endif
  1023. return true;
  1024. }
  1025. template<typename T>
  1026. void JavascriptArray::DirectSetItem_Full(uint32 itemIndex, T newValue)
  1027. {
  1028. DebugOnly(VerifyNotNeedMarshal(newValue));
  1029. this->EnsureHead<T>();
  1030. AnalysisAssert(head);
  1031. #ifdef VALIDATE_ARRAY
  1032. ValidateArray();
  1033. #endif
  1034. if (itemIndex >= this->length)
  1035. {
  1036. if (itemIndex != JavascriptArray::InvalidIndex)
  1037. {
  1038. this->length = itemIndex + 1;
  1039. }
  1040. else
  1041. {
  1042. JavascriptError::ThrowRangeError(this->GetScriptContext(), JSERR_ArrayLengthAssignIncorrect);
  1043. }
  1044. }
  1045. Recycler* recycler = GetRecycler();
  1046. //Find the segment where itemIndex is present or is at the boundary
  1047. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(itemIndex, false);
  1048. // If it doesn't fit in current chunk (watch for overflow), start from beginning as we'll
  1049. // need the prev
  1050. if (current->left + current->size > current->left || itemIndex >= current->left + current->size)
  1051. {
  1052. current = (SparseArraySegment<T>*)head;
  1053. }
  1054. SparseArraySegmentBase* prev = nullptr;
  1055. #ifdef VALIDATE_ARRAY
  1056. SparseArraySegmentBase* current_btree = nullptr;
  1057. SparseArraySegmentBase* prev_btree = nullptr;
  1058. bool first_pass = true;
  1059. #endif
  1060. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  1061. if (segmentMap)
  1062. {
  1063. SparseArraySegmentBase* prevSeg = nullptr;
  1064. SparseArraySegmentBase* currentBase = current;
  1065. segmentMap->Find(itemIndex, prevSeg, currentBase);
  1066. current = (SparseArraySegment<T>*)currentBase;
  1067. Assert(!prevSeg || prevSeg->next == current);
  1068. if (prevSeg)
  1069. {
  1070. bool noExactMatch = !current || itemIndex < current->left;
  1071. Assert(prevSeg->left + prevSeg->size >= prevSeg->left);
  1072. bool extendPrevSeg = itemIndex <= prevSeg->left + prevSeg->size;
  1073. if (noExactMatch && extendPrevSeg)
  1074. {
  1075. current = (SparseArraySegment<T>*)head;
  1076. prev = nullptr;
  1077. if (prevSeg != head)
  1078. {
  1079. // Since we are going to extend prevSeg we need the
  1080. // address of it's left neighbor's next pointer
  1081. currentBase = current;
  1082. segmentMap->Find(prevSeg->left, prevSeg, currentBase);
  1083. current = (SparseArraySegment<T>*)currentBase;
  1084. Assert(prevSeg && prevSeg->next == current);
  1085. prev = prevSeg;
  1086. }
  1087. }
  1088. else
  1089. {
  1090. prev = prevSeg;
  1091. }
  1092. }
  1093. else
  1094. {
  1095. Assert(current == head);
  1096. }
  1097. #ifdef VALIDATE_ARRAY
  1098. SECOND_PASS:
  1099. if (!first_pass)
  1100. {
  1101. current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(itemIndex, false);
  1102. // If it doesn't fit in current chunk (watch for overflow), start from beginning as we'll
  1103. // need the prev
  1104. if (current->left + current->size > current->left || itemIndex >= current->left + current->size)
  1105. {
  1106. current = (SparseArraySegment<T>*)head;
  1107. }
  1108. prev = nullptr;
  1109. }
  1110. #endif
  1111. }
  1112. uint probeCost = 0;
  1113. while(current != nullptr)
  1114. {
  1115. uint32 offset = itemIndex - current->left;
  1116. if (itemIndex < current->left)
  1117. {
  1118. break;
  1119. }
  1120. else if (offset <= current->size)
  1121. {
  1122. if ((nullptr == current->next) || (itemIndex < current->next->left))
  1123. {
  1124. break;
  1125. }
  1126. }
  1127. prev = current;
  1128. current = (SparseArraySegment<T>*)current->next;
  1129. Assert(segmentMap == GetSegmentMap());
  1130. if (!segmentMap)
  1131. {
  1132. probeCost++;
  1133. if (probeCost > SegmentBTree::GetLazyCrossOverLimit())
  1134. {
  1135. // Build a SegmentMap
  1136. segmentMap = BuildSegmentMap();
  1137. SparseArraySegmentBase* prevSeg = nullptr;
  1138. SparseArraySegmentBase* currentBase = current;
  1139. segmentMap->Find(itemIndex, prevSeg, currentBase);
  1140. current = (SparseArraySegment<T>*)currentBase;
  1141. Assert(prevSeg->next == current);
  1142. if (prevSeg)
  1143. {
  1144. bool noExactMatch = !current || itemIndex < current->left;
  1145. Assert(prevSeg->left + prevSeg->size >= prevSeg->left);
  1146. bool extendPrevSeg = itemIndex <= prevSeg->left + prevSeg->size;
  1147. if (noExactMatch && extendPrevSeg)
  1148. {
  1149. current = (SparseArraySegment<T>*)head;
  1150. prev = nullptr;
  1151. if (prevSeg != head)
  1152. {
  1153. // Since we are going to extend prevSeg we need the
  1154. // address of its left neighbor's next pointer
  1155. currentBase = current;
  1156. segmentMap->Find(prevSeg->left, prevSeg, currentBase);
  1157. current = (SparseArraySegment<T>*)currentBase;
  1158. Assert(prevSeg->next == current);
  1159. prev = prevSeg;
  1160. }
  1161. }
  1162. else
  1163. {
  1164. prev = prevSeg;
  1165. }
  1166. }
  1167. else
  1168. {
  1169. Assert(current == head);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. #ifdef VALIDATE_ARRAY
  1175. Assert(segmentMap == GetSegmentMap());
  1176. if (segmentMap && first_pass)
  1177. {
  1178. current_btree = current;
  1179. prev_btree = prev;
  1180. first_pass = false;
  1181. goto SECOND_PASS;
  1182. }
  1183. else if (segmentMap)
  1184. {
  1185. Assert(current_btree == current && prev_btree == prev);
  1186. }
  1187. #endif
  1188. if (current != nullptr)
  1189. {
  1190. uint32 offset = itemIndex - current->left;
  1191. if ((itemIndex >= current->left) && (offset < current->size))
  1192. {
  1193. //itemIndex lies in the segment
  1194. Assert(!(HasNoMissingValues() &&
  1195. offset < current->length &&
  1196. SparseArraySegment<T>::IsMissingItem(&current->elements[offset]) &&
  1197. current == head));
  1198. if(offset > current->length && current == head)
  1199. {
  1200. SetHasNoMissingValues(false);
  1201. }
  1202. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(current, offset);
  1203. ((SparseArraySegment<T>*)current)->SetElement(recycler, itemIndex, newValue);
  1204. if(scanForMissingValues)
  1205. {
  1206. ScanForMissingValues<T>();
  1207. }
  1208. }
  1209. else if ((itemIndex + 1) < current->left)
  1210. {
  1211. //itemIndex lies in between current and previous segment
  1212. SparseArraySegment<T>* newSeg = SparseArraySegment<T>::AllocateSegment(recycler, prev, itemIndex);
  1213. newSeg->SetElement(recycler, itemIndex, newValue);
  1214. newSeg->next = current;
  1215. LinkSegments((SparseArraySegment<T>*)prev, newSeg);
  1216. current = newSeg;
  1217. TryAddToSegmentMap(recycler, newSeg);
  1218. Assert(current != head);
  1219. }
  1220. else
  1221. {
  1222. //itemIndex is at boundary of current segment either at the left + size or at left - 1;
  1223. Assert((itemIndex == current->left + current->size) || (itemIndex + 1 == current->left));
  1224. SparseArraySegment<T>* next = (SparseArraySegment<T>*)current->next;
  1225. Assert(segmentMap == GetSegmentMap());
  1226. if (!segmentMap && next != nullptr && (itemIndex + 1) == next->left)
  1227. {
  1228. // Don't merge segments if we are using a segmentMap
  1229. //Special case where we need to merge two segments. itemIndex is on the size boundary
  1230. //of the current segment & left boundary of the next
  1231. const bool currentWasFull = current->length == current->size;
  1232. Assert(itemIndex == current->left + current->size);
  1233. current = SparseArraySegment<T>::CopySegment(recycler, (SparseArraySegment<T>*)current, next->left, next, next->left, next->length);
  1234. current->next = next->next;
  1235. current->SetElement(recycler, itemIndex, newValue);
  1236. LinkSegments((SparseArraySegment<T>*)prev, current);
  1237. if(HasNoMissingValues() && current == head)
  1238. {
  1239. // We just merged the head segment and its next segment and filled the only missing value in-between the
  1240. // two segments. We already know that the previous head segment does not have any missing values. If the
  1241. // previous head segment was full, scan the new head segment starting from the merge point for missing
  1242. // values. If the previous head segment was not full, then merging the segments would have created
  1243. // missing values.
  1244. SetHasNoMissingValues(false);
  1245. if(currentWasFull)
  1246. {
  1247. ScanForMissingValues<T>(offset + 1);
  1248. }
  1249. }
  1250. }
  1251. else
  1252. {
  1253. if(offset > current->length && current == head)
  1254. {
  1255. SetHasNoMissingValues(false);
  1256. }
  1257. const bool currentWasHead = current == head;
  1258. SparseArraySegmentBase* oldSegment = current;
  1259. uint originalKey = oldSegment->left;
  1260. current = current->SetElementGrow(recycler, prev, itemIndex, newValue);
  1261. Assert(segmentMap == GetSegmentMap());
  1262. if (segmentMap)
  1263. {
  1264. segmentMap->SwapSegment(originalKey, oldSegment, current);
  1265. }
  1266. LinkSegments((SparseArraySegment<T>*)prev, current);
  1267. // Scan for missing values when the current segment was grown at the beginning and made the head segment
  1268. if(!currentWasHead && current == head)
  1269. {
  1270. ScanForMissingValues<T>();
  1271. }
  1272. }
  1273. }
  1274. }
  1275. else
  1276. {
  1277. // Reallocate head if need it meets a heuristics
  1278. Assert(itemIndex >= head->size);
  1279. if (prev == head // prev segment is the head segment
  1280. && !head->next // There is only one head segment in the array
  1281. && !segmentMap // There is no segmentMap which makes sure that array is not highly fragmented.
  1282. && itemIndex - head->size <= MergeSegmentsLengthHeuristics // Distance to next index is relatively small
  1283. )
  1284. {
  1285. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, itemIndex + 1 - head->size);
  1286. current->elements[itemIndex] = newValue;
  1287. current->length = itemIndex + 1;
  1288. head = current;
  1289. SetHasNoMissingValues(false);
  1290. }
  1291. else
  1292. {
  1293. //itemIndex is greater than the (left + size) of last segment in the linked list
  1294. current = SparseArraySegment<T>::AllocateSegment(recycler, itemIndex, 1, (SparseArraySegment<T> *)nullptr);
  1295. current->SetElement(recycler, itemIndex, newValue);
  1296. LinkSegments((SparseArraySegment<T>*)prev, current);
  1297. TryAddToSegmentMap(recycler, current);
  1298. if(current == head)
  1299. {
  1300. Assert(itemIndex == 0);
  1301. Assert(current->length == 1);
  1302. SetHasNoMissingValues();
  1303. }
  1304. }
  1305. }
  1306. this->SetLastUsedSegment(current);
  1307. #ifdef VALIDATE_ARRAY
  1308. ValidateArray();
  1309. #endif
  1310. }
  1311. template<typename T>
  1312. bool JavascriptArray::NeedScanForMissingValuesUponSetItem(SparseArraySegment<T> *const segment, const uint32 offset) const
  1313. {
  1314. Assert(segment);
  1315. // Scan for missing values upon SetItem when a missing value is being filled and the surrounding values are not missing,
  1316. // as this could be the last missing value that is being filled
  1317. return
  1318. offset < segment->length &&
  1319. SparseArraySegment<T>::IsMissingItem(&segment->elements[offset]) &&
  1320. (offset == 0 || !SparseArraySegment<T>::IsMissingItem(&segment->elements[offset - 1])) &&
  1321. (offset == segment->length - 1 || !SparseArraySegment<T>::IsMissingItem(&segment->elements[offset + 1])) &&
  1322. segment == head;
  1323. }
  1324. template<typename T>
  1325. void JavascriptArray::ScanForMissingValues(const uint startIndex)
  1326. {
  1327. Assert(head);
  1328. Assert(!HasNoMissingValues());
  1329. SparseArraySegment<T> *const segment = (SparseArraySegment<T>*)head;
  1330. const uint segmentLength = segment->length;
  1331. const T *const segmentElements = segment->elements;
  1332. for(uint i = startIndex; i < segmentLength; ++i)
  1333. {
  1334. if(SparseArraySegment<T>::IsMissingItem(&segmentElements[i]))
  1335. {
  1336. return;
  1337. }
  1338. }
  1339. SetHasNoMissingValues();
  1340. }
  1341. template<typename T>
  1342. bool JavascriptArray::ScanForMissingValues(const uint startIndex, const uint endIndex)
  1343. {
  1344. Assert(head);
  1345. //Assert(!HasNoMissingValues());
  1346. SparseArraySegment<T> *const segment = (SparseArraySegment<T>*)head;
  1347. const T *const segmentElements = segment->elements;
  1348. for (uint i = startIndex; i < endIndex; ++i)
  1349. {
  1350. if (SparseArraySegment<T>::IsMissingItem(&segmentElements[i]))
  1351. {
  1352. return true;
  1353. }
  1354. }
  1355. return false;
  1356. }
  1357. inline void JavascriptArray::DirectSetItemIfNotExist(uint32 index, Var newValue)
  1358. {
  1359. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(this));
  1360. Var oldValue;
  1361. if (!DirectGetItemAt(index, &oldValue))
  1362. {
  1363. DirectSetItemAt(index, newValue);
  1364. }
  1365. }
  1366. //Grow the array head and try to set at the boundary
  1367. template<typename unitType, typename classname>
  1368. inline BOOL JavascriptArray::TryGrowHeadSegmentAndSetItem(uint32 indexInt, unitType iValue)
  1369. {
  1370. SparseArraySegment<unitType> *current = (SparseArraySegment<unitType> *)this->head;
  1371. if (indexInt == current->length // index is at the boundary of size & length
  1372. && current->size // Make sure its not empty segment.
  1373. && !current->next // There is only head segment.
  1374. && current->length == current->size // Why did we miss the fastpath?
  1375. && !SparseArraySegment<unitType>::IsMissingItem(&iValue)) // value to set is not a missing value.
  1376. {
  1377. current= current->GrowByMin(this->GetRecycler(), indexInt + 1);
  1378. DebugOnly(VerifyNotNeedMarshal(iValue));
  1379. current->elements[indexInt] = iValue;
  1380. current->length = indexInt + 1;
  1381. // There is only a head segment in this condition A segment map is not necessary
  1382. // and most likely invalid at this point. Also we are setting the head and lastUsedSegment
  1383. // to the same segment. Precedent in the rest of the code base dictates the use of
  1384. // SetHeadAndLastUsedSegment which asserts if a segment map exists.
  1385. ClearSegmentMap();
  1386. SetHeadAndLastUsedSegment(current);
  1387. if (this->length <= indexInt)
  1388. {
  1389. this->length = indexInt + 1;
  1390. }
  1391. #ifdef VALIDATE_ARRAY
  1392. ValidateArray();
  1393. #endif
  1394. return true;
  1395. }
  1396. return false;
  1397. }
  1398. //
  1399. // JavascriptArray::IndexTrace specialized on uint32 (small index)
  1400. //
  1401. template<>
  1402. inline Var JavascriptArray::IndexTrace<uint32>::ToNumber(const uint32& index, ScriptContext* scriptContext)
  1403. {
  1404. return JavascriptNumber::ToVar(index, scriptContext);
  1405. }
  1406. template<>
  1407. inline BOOL JavascriptArray::IndexTrace<uint32>::GetItem(JavascriptArray* arr, const uint32& index, Var* outVal)
  1408. {
  1409. return arr->DirectGetItemAt(index, outVal);
  1410. }
  1411. template<>
  1412. inline BOOL JavascriptArray::IndexTrace<uint32>::SetItem(JavascriptArray* arr, const uint32& index, Var newValue)
  1413. {
  1414. return arr->SetItem(index, newValue, PropertyOperation_None);
  1415. }
  1416. template<>
  1417. inline void JavascriptArray::IndexTrace<uint32>::SetItemIfNotExist(JavascriptArray* arr, const uint32& index, Var newValue)
  1418. {
  1419. arr->DirectSetItemIfNotExist(index, newValue);
  1420. }
  1421. template<>
  1422. inline BOOL JavascriptArray::IndexTrace<uint32>::DeleteItem(JavascriptArray* arr, const uint32& index)
  1423. {
  1424. switch (arr->GetTypeId())
  1425. {
  1426. case TypeIds_Array:
  1427. return arr->DirectDeleteItemAt<Var>(index);
  1428. case TypeIds_NativeIntArray:
  1429. return arr->DirectDeleteItemAt<int32>(index);
  1430. case TypeIds_NativeFloatArray:
  1431. return arr->DirectDeleteItemAt<double>(index);
  1432. default:
  1433. Assert(FALSE);
  1434. return FALSE;
  1435. }
  1436. }
  1437. template<>
  1438. inline BOOL JavascriptArray::IndexTrace<uint32>::SetItem(RecyclableObject* obj, const uint32& index, Var newValue, PropertyOperationFlags flags)
  1439. {
  1440. ScriptContext* requestContext = obj->GetScriptContext();
  1441. return JavascriptOperators::SetItem(obj, obj, index, newValue, requestContext, flags);
  1442. }
  1443. template<>
  1444. inline BOOL JavascriptArray::IndexTrace<uint32>::DeleteItem(RecyclableObject* obj, const uint32& index, PropertyOperationFlags flags)
  1445. {
  1446. return JavascriptOperators::DeleteItem(obj, index, flags);
  1447. }
  1448. //
  1449. // JavascriptArray::IndexTrace specialized on BigIndex
  1450. //
  1451. template<>
  1452. inline Var JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::ToNumber(const JavascriptArray::BigIndex& index, ScriptContext* scriptContext)
  1453. {
  1454. return index.ToNumber(scriptContext);
  1455. }
  1456. template<>
  1457. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::GetItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var* outVal)
  1458. {
  1459. return index.GetItem(arr, outVal);
  1460. }
  1461. template<>
  1462. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var newValue)
  1463. {
  1464. return index.SetItem(arr, newValue);
  1465. }
  1466. template<>
  1467. inline void JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItemIfNotExist(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var newValue)
  1468. {
  1469. index.SetItemIfNotExist(arr, newValue);
  1470. }
  1471. template<>
  1472. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::DeleteItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index)
  1473. {
  1474. return index.DeleteItem(arr);
  1475. }
  1476. template<>
  1477. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItem(RecyclableObject* obj, const JavascriptArray::BigIndex& index, Var newValue, PropertyOperationFlags flags)
  1478. {
  1479. return index.SetItem(obj, newValue, flags);
  1480. }
  1481. template<>
  1482. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::DeleteItem(RecyclableObject* obj, const JavascriptArray::BigIndex& index, PropertyOperationFlags flags)
  1483. {
  1484. return index.DeleteItem(obj, flags);
  1485. }
  1486. template<class T, uint InlinePropertySlots>
  1487. __inline size_t JavascriptArray::DetermineAllocationSize(
  1488. const uint inlineElementSlots,
  1489. size_t *const allocationPlusSizeRef,
  1490. uint *const alignedInlineElementSlotsRef)
  1491. {
  1492. CompileAssert(static_cast<PropertyIndex>(InlinePropertySlots) == InlinePropertySlots);
  1493. Assert(
  1494. DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(InlinePropertySlots)) ==
  1495. InlinePropertySlots);
  1496. CompileAssert(
  1497. InlinePropertySlots <=
  1498. (UINT_MAX - (sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>))) / sizeof(Var));
  1499. const uint objectSize =
  1500. sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>) + InlinePropertySlots * sizeof(Var);
  1501. size_t totalSize = UInt32Math::MulAdd<sizeof(typename T::TElement), objectSize>(inlineElementSlots);
  1502. #if defined(_M_X64_OR_ARM64)
  1503. // On x64, the total size won't be anywhere near AllocSizeMath::MaxMemory on x64, so no need to check
  1504. totalSize = HeapInfo::GetAlignedSizeNoCheck(totalSize);
  1505. #else
  1506. totalSize = HeapInfo::GetAlignedSize(totalSize);
  1507. #endif
  1508. if(allocationPlusSizeRef)
  1509. {
  1510. *allocationPlusSizeRef = totalSize - sizeof(T);
  1511. }
  1512. if(alignedInlineElementSlotsRef)
  1513. {
  1514. const size_t alignedInlineElementSlots = (totalSize - objectSize) / sizeof(typename T::TElement);
  1515. *alignedInlineElementSlotsRef = static_cast<uint>(alignedInlineElementSlots);
  1516. Assert(*alignedInlineElementSlotsRef == alignedInlineElementSlots); // ensure no truncation above
  1517. }
  1518. return totalSize;
  1519. }
  1520. template<class T, uint InlinePropertySlots>
  1521. __inline uint JavascriptArray::DetermineAvailableInlineElementSlots(
  1522. const size_t allocationSize,
  1523. bool *const isSufficientSpaceForInlinePropertySlotsRef)
  1524. {
  1525. CompileAssert(static_cast<PropertyIndex>(InlinePropertySlots) == InlinePropertySlots);
  1526. Assert(
  1527. DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(InlinePropertySlots)) ==
  1528. InlinePropertySlots);
  1529. Assert(isSufficientSpaceForInlinePropertySlotsRef);
  1530. CompileAssert(
  1531. InlinePropertySlots <=
  1532. (UINT_MAX - (sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>))) / sizeof(Var));
  1533. *isSufficientSpaceForInlinePropertySlotsRef =
  1534. sizeof(T) + InlinePropertySlots * sizeof(Var) + sizeof(SparseArraySegment<typename T::TElement>) <= allocationSize;
  1535. const size_t availableInlineElementSlots =
  1536. (
  1537. allocationSize -
  1538. (sizeof(T) + InlinePropertySlots * sizeof(Var) + sizeof(SparseArraySegment<typename T::TElement>))
  1539. ) / sizeof(typename T::TElement);
  1540. const uint availableInlineElementSlotsUint = static_cast<uint>(availableInlineElementSlots);
  1541. Assert(availableInlineElementSlotsUint == availableInlineElementSlots); // ensure no truncation above
  1542. return availableInlineElementSlotsUint;
  1543. }
  1544. template<class T, uint ConstInlinePropertySlots, bool UseDynamicInlinePropertySlots>
  1545. __inline SparseArraySegment<typename T::TElement> *JavascriptArray::DetermineInlineHeadSegmentPointer(T *const array)
  1546. {
  1547. Assert(array);
  1548. Assert(VirtualTableInfo<T>::HasVirtualTable(array) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(array));
  1549. Assert(!UseDynamicInlinePropertySlots || ConstInlinePropertySlots == 0);
  1550. Assert(
  1551. UseDynamicInlinePropertySlots ||
  1552. ConstInlinePropertySlots == array->GetTypeHandler()->GetInlineSlotCapacity());
  1553. const uint inlinePropertySlots =
  1554. UseDynamicInlinePropertySlots ? array->GetTypeHandler()->GetInlineSlotCapacity() : ConstInlinePropertySlots;
  1555. Assert(inlinePropertySlots == 0 || array->GetTypeHandler()->GetOffsetOfInlineSlots() == sizeof(T));
  1556. return
  1557. reinterpret_cast<SparseArraySegment<typename T::TElement> *>(
  1558. reinterpret_cast<Var *>(array + 1) + inlinePropertySlots);
  1559. }
  1560. //
  1561. // ItemTrace<T> specializations
  1562. //
  1563. template<>
  1564. inline uint32 JavascriptArray::ItemTrace<JavascriptArray>::GetLength(JavascriptArray* obj, ScriptContext* scriptContext)
  1565. {
  1566. return obj->GetLength();
  1567. }
  1568. template<>
  1569. inline BOOL JavascriptArray::ItemTrace<JavascriptArray>::GetItem(JavascriptArray* obj, uint32 index, Var* outVal, ScriptContext* scriptContext)
  1570. {
  1571. Assert(JavascriptArray::IsDirectAccessArray(obj));
  1572. return obj->DirectGetItemAtFull(index, outVal); // Note this does prototype lookup
  1573. }
  1574. template<>
  1575. inline uint32 JavascriptArray::ItemTrace<RecyclableObject>::GetLength(RecyclableObject* obj, ScriptContext* scriptContext)
  1576. {
  1577. return JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  1578. }
  1579. template<>
  1580. inline BOOL JavascriptArray::ItemTrace<RecyclableObject>::GetItem(RecyclableObject* obj, uint32 index, Var* outVal, ScriptContext* scriptContext)
  1581. {
  1582. return JavascriptOperators::GetItem(obj, index, outVal, scriptContext);
  1583. }
  1584. } // namespace Js