-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathGlobOpt.cpp
17730 lines (15874 loc) · 650 KB
/
GlobOpt.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
#if DBG_DUMP
#define DO_MEMOP_TRACE() (PHASE_TRACE(Js::MemOpPhase, this->func) ||\
PHASE_TRACE(Js::MemSetPhase, this->func) ||\
PHASE_TRACE(Js::MemCopyPhase, this->func))
#define DO_MEMOP_TRACE_PHASE(phase) (PHASE_TRACE(Js::MemOpPhase, this->func) || PHASE_TRACE(Js::phase ## Phase, this->func))
#define OUTPUT_MEMOP_TRACE(loop, instr, ...) {\
char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];\
Output::Print(15, _u("Function: %s%s, Loop: %u: "), this->func->GetJITFunctionBody()->GetDisplayName(), this->func->GetDebugNumberSet(debugStringBuffer), loop->GetLoopNumber());\
Output::Print(__VA_ARGS__);\
IR::Instr* __instr__ = instr;\
if(__instr__) __instr__->DumpByteCodeOffset();\
if(__instr__) Output::Print(_u(" (%s)"), Js::OpCodeUtil::GetOpCodeName(__instr__->m_opcode));\
Output::Print(_u("\n"));\
Output::Flush(); \
}
#define TRACE_MEMOP(loop, instr, ...) \
if (DO_MEMOP_TRACE()) {\
Output::Print(_u("TRACE MemOp:"));\
OUTPUT_MEMOP_TRACE(loop, instr, __VA_ARGS__)\
}
#define TRACE_MEMOP_VERBOSE(loop, instr, ...) if(CONFIG_FLAG(Verbose)) {TRACE_MEMOP(loop, instr, __VA_ARGS__)}
#define TRACE_MEMOP_PHASE(phase, loop, instr, ...) \
if (DO_MEMOP_TRACE_PHASE(phase))\
{\
Output::Print(_u("TRACE ") _u(#phase) _u(":"));\
OUTPUT_MEMOP_TRACE(loop, instr, __VA_ARGS__)\
}
#define TRACE_MEMOP_PHASE_VERBOSE(phase, loop, instr, ...) if(CONFIG_FLAG(Verbose)) {TRACE_MEMOP_PHASE(phase, loop, instr, __VA_ARGS__)}
#else
#define DO_MEMOP_TRACE()
#define DO_MEMOP_TRACE_PHASE(phase)
#define OUTPUT_MEMOP_TRACE(loop, instr, ...)
#define TRACE_MEMOP(loop, instr, ...)
#define TRACE_MEMOP_VERBOSE(loop, instr, ...)
#define TRACE_MEMOP_PHASE(phase, loop, instr, ...)
#define TRACE_MEMOP_PHASE_VERBOSE(phase, loop, instr, ...)
#endif
class AutoRestoreVal
{
private:
Value *const originalValue;
Value *const tempValue;
Value * *const valueRef;
public:
AutoRestoreVal(Value *const originalValue, Value * *const tempValueRef)
: originalValue(originalValue), tempValue(*tempValueRef), valueRef(tempValueRef)
{
}
~AutoRestoreVal()
{
if(*valueRef == tempValue)
{
*valueRef = originalValue;
}
}
PREVENT_COPY(AutoRestoreVal);
};
GlobOpt::GlobOpt(Func * func)
: func(func),
intConstantToStackSymMap(nullptr),
intConstantToValueMap(nullptr),
currentValue(FirstNewValueNumber),
prePassLoop(nullptr),
alloc(nullptr),
isCallHelper(false),
inInlinedBuiltIn(false),
rootLoopPrePass(nullptr),
noImplicitCallUsesToInsert(nullptr),
valuesCreatedForClone(nullptr),
valuesCreatedForMerge(nullptr),
instrCountSinceLastCleanUp(0),
isRecursiveCallOnLandingPad(false),
updateInductionVariableValueNumber(false),
isPerformingLoopBackEdgeCompensation(false),
currentRegion(nullptr),
auxSlotPtrSyms(nullptr),
changedSymsAfterIncBailoutCandidate(nullptr),
doTypeSpec(
!IsTypeSpecPhaseOff(func)),
doAggressiveIntTypeSpec(
doTypeSpec &&
DoAggressiveIntTypeSpec(func)),
doAggressiveMulIntTypeSpec(
doTypeSpec &&
!PHASE_OFF(Js::AggressiveMulIntTypeSpecPhase, func) &&
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsAggressiveMulIntTypeSpecDisabled(func->IsLoopBody()))),
doDivIntTypeSpec(
doAggressiveIntTypeSpec &&
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsDivIntTypeSpecDisabled(func->IsLoopBody()))),
doLossyIntTypeSpec(
doTypeSpec &&
DoLossyIntTypeSpec(func)),
doFloatTypeSpec(
doTypeSpec &&
DoFloatTypeSpec(func)),
doArrayCheckHoist(
DoArrayCheckHoist(func)),
doArrayMissingValueCheckHoist(
doArrayCheckHoist &&
DoArrayMissingValueCheckHoist(func)),
doArraySegmentHoist(
doArrayCheckHoist &&
DoArraySegmentHoist(ValueType::GetObject(ObjectType::Int32Array), func)),
doJsArraySegmentHoist(
doArraySegmentHoist &&
DoArraySegmentHoist(ValueType::GetObject(ObjectType::Array), func)),
doArrayLengthHoist(
doArrayCheckHoist &&
DoArrayLengthHoist(func)),
doEliminateArrayAccessHelperCall(
doArrayCheckHoist &&
!PHASE_OFF(Js::EliminateArrayAccessHelperCallPhase, func)),
doTrackRelativeIntBounds(
doAggressiveIntTypeSpec &&
DoPathDependentValues() &&
!PHASE_OFF(Js::Phase::TrackRelativeIntBoundsPhase, func)),
doBoundCheckElimination(
doTrackRelativeIntBounds &&
!PHASE_OFF(Js::Phase::BoundCheckEliminationPhase, func)),
doBoundCheckHoist(
doEliminateArrayAccessHelperCall &&
doBoundCheckElimination &&
DoConstFold() &&
!PHASE_OFF(Js::Phase::BoundCheckHoistPhase, func) &&
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsBoundCheckHoistDisabled(func->IsLoopBody()))),
doLoopCountBasedBoundCheckHoist(
doBoundCheckHoist &&
!PHASE_OFF(Js::Phase::LoopCountBasedBoundCheckHoistPhase, func) &&
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsLoopCountBasedBoundCheckHoistDisabled(func->IsLoopBody()))),
doPowIntIntTypeSpec(
doAggressiveIntTypeSpec &&
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsPowIntIntTypeSpecDisabled())),
doTagChecks(
(!func->HasProfileInfo() || !func->GetReadOnlyProfileInfo()->IsTagCheckDisabled())),
isAsmJSFunc(func->GetJITFunctionBody()->IsAsmJsMode())
{
}
void
GlobOpt::BackwardPass(Js::Phase tag)
{
BEGIN_CODEGEN_PHASE(this->func, tag);
::BackwardPass backwardPass(this->func, this, tag);
backwardPass.Optimize();
END_CODEGEN_PHASE(this->func, tag);
}
void
GlobOpt::Optimize()
{
this->objectTypeSyms = nullptr;
this->func->argInsCount = this->func->GetInParamsCount() - 1; //Don't include "this" pointer in the count.
if (!func->DoGlobOpt())
{
this->lengthEquivBv = nullptr;
this->argumentsEquivBv = nullptr;
this->callerEquivBv = nullptr;
// Still need to run the dead store phase to calculate the live reg on back edge
this->BackwardPass(Js::DeadStorePhase);
CannotAllocateArgumentsObjectOnStack(nullptr);
return;
}
{
this->lengthEquivBv = this->func->m_symTable->m_propertyEquivBvMap->Lookup(Js::PropertyIds::length, nullptr); // Used to kill live "length" properties
this->argumentsEquivBv = func->m_symTable->m_propertyEquivBvMap->Lookup(Js::PropertyIds::arguments, nullptr); // Used to kill live "arguments" properties
this->callerEquivBv = func->m_symTable->m_propertyEquivBvMap->Lookup(Js::PropertyIds::caller, nullptr); // Used to kill live "caller" properties
// The backward phase needs the glob opt's allocator to allocate the propertyTypeValueMap
// in GlobOpt::EnsurePropertyTypeValue and ranges of instructions where int overflow may be ignored.
// (see BackwardPass::TrackIntUsage)
PageAllocator * pageAllocator = this->func->m_alloc->GetPageAllocator();
NoRecoverMemoryJitArenaAllocator localAlloc(_u("BE-GlobOpt"), pageAllocator, Js::Throw::OutOfMemory);
this->alloc = &localAlloc;
NoRecoverMemoryJitArenaAllocator localTempAlloc(_u("BE-GlobOpt temp"), pageAllocator, Js::Throw::OutOfMemory);
this->tempAlloc = &localTempAlloc;
// The forward passes use info (upwardExposedUses) from the backward pass. This info
// isn't available for some of the symbols created during the backward pass, or the forward pass.
// Keep track of the last symbol for which we're guaranteed to have data.
this->maxInitialSymID = this->func->m_symTable->GetMaxSymID();
#if DBG
this->BackwardPass(Js::CaptureByteCodeRegUsePhase);
#endif
this->BackwardPass(Js::BackwardPhase);
this->ForwardPass();
this->BackwardPass(Js::DeadStorePhase);
}
this->TailDupPass();
}
bool GlobOpt::ShouldExpectConventionalArrayIndexValue(IR::IndirOpnd *const indirOpnd)
{
Assert(indirOpnd);
if(!indirOpnd->GetIndexOpnd())
{
return indirOpnd->GetOffset() >= 0;
}
IR::RegOpnd *const indexOpnd = indirOpnd->GetIndexOpnd();
if(indexOpnd->m_sym->m_isNotNumber)
{
// Typically, single-def or any sym-specific information for type-specialized syms should not be used because all of
// their defs will not have been accounted for until after the forward pass. But m_isNotNumber is only ever changed from
// false to true, so it's okay in this case.
return false;
}
StackSym *indexVarSym = indexOpnd->m_sym;
if(indexVarSym->IsTypeSpec())
{
indexVarSym = indexVarSym->GetVarEquivSym(nullptr);
Assert(indexVarSym);
}
else if(!IsLoopPrePass())
{
// Don't use single-def info or const flags for type-specialized syms, as all of their defs will not have been accounted
// for until after the forward pass. Also, don't use the const flags in a loop prepass because the const flags may not
// be up-to-date.
if (indexOpnd->IsNotInt())
{
return false;
}
StackSym *const indexSym = indexOpnd->m_sym;
if(indexSym->IsIntConst())
{
return indexSym->GetIntConstValue() >= 0;
}
}
Value *const indexValue = CurrentBlockData()->FindValue(indexVarSym);
if(!indexValue)
{
// Treat it as Uninitialized, assume it's going to be valid
return true;
}
ValueInfo *const indexValueInfo = indexValue->GetValueInfo();
int32 indexConstantValue;
if(indexValueInfo->TryGetIntConstantValue(&indexConstantValue))
{
return indexConstantValue >= 0;
}
if(indexValueInfo->IsUninitialized())
{
// Assume it's going to be valid
return true;
}
return indexValueInfo->HasBeenNumber() && !indexValueInfo->HasBeenFloat();
}
//
// Either result is float or 1/x or cst1/cst2 where cst1%cst2 != 0
//
ValueType GlobOpt::GetDivValueType(IR::Instr* instr, Value* src1Val, Value* src2Val, bool specialize)
{
ValueInfo *src1ValueInfo = (src1Val ? src1Val->GetValueInfo() : nullptr);
ValueInfo *src2ValueInfo = (src2Val ? src2Val->GetValueInfo() : nullptr);
if (instr->IsProfiledInstr() && instr->m_func->HasProfileInfo())
{
ValueType resultType = instr->m_func->GetReadOnlyProfileInfo()->GetDivProfileInfo(static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId));
if (resultType.IsLikelyInt())
{
if (specialize && src1ValueInfo && src2ValueInfo
&& ((src1ValueInfo->IsInt() && src2ValueInfo->IsInt()) ||
(this->DoDivIntTypeSpec() && src1ValueInfo->IsLikelyInt() && src2ValueInfo->IsLikelyInt())))
{
return ValueType::GetInt(true);
}
return resultType;
}
// Consider: Checking that the sources are numbers.
if (resultType.IsLikelyFloat())
{
return ValueType::Float;
}
return resultType;
}
int32 src1IntConstantValue;
if(!src1ValueInfo || !src1ValueInfo->TryGetIntConstantValue(&src1IntConstantValue))
{
return ValueType::Number;
}
if (src1IntConstantValue == 1)
{
return ValueType::Float;
}
int32 src2IntConstantValue;
if(!src2Val || !src2ValueInfo->TryGetIntConstantValue(&src2IntConstantValue))
{
return ValueType::Number;
}
if (src2IntConstantValue // Avoid divide by zero
&& !(src1IntConstantValue == 0x80000000 && src2IntConstantValue == -1) // Avoid integer overflow
&& (src1IntConstantValue % src2IntConstantValue) != 0)
{
return ValueType::Float;
}
return ValueType::Number;
}
void
GlobOpt::ForwardPass()
{
BEGIN_CODEGEN_PHASE(this->func, Js::ForwardPhase);
#if DBG_DUMP
if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::GlobOptPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()))
{
this->func->DumpHeader();
}
if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::GlobOptPhase))
{
this->TraceSettings();
}
#endif
// GetConstantCount() gives us the right size to pick for the SparseArray, but we may need more if we've inlined
// functions with constants. There will be a gap in the symbol numbering between the main constants and
// the inlined ones, so we'll most likely need a new array chunk. Make the min size of the array chunks be 64
// in case we have a main function with very few constants and a bunch of constants from inlined functions.
this->byteCodeConstantValueArray = SparseArray<Value>::New(this->alloc, max(this->func->GetJITFunctionBody()->GetConstCount(), 64U));
this->byteCodeConstantValueNumbersBv = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
this->tempBv = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
this->prePassCopyPropSym = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
this->slotSyms = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
this->byteCodeUses = nullptr;
this->propertySymUse = nullptr;
// changedSymsAfterIncBailoutCandidate helps track building incremental bailout in ForwardPass
this->changedSymsAfterIncBailoutCandidate = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
this->auxSlotPtrSyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
#if DBG
this->byteCodeUsesBeforeOpt = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldCopyPropPhase) && this->DoFunctionFieldCopyProp())
{
Output::Print(_u("TRACE: CanDoFieldCopyProp Func: "));
this->func->DumpFullFunctionName();
Output::Print(_u("\n"));
}
#endif
OpndList localNoImplicitCallUsesToInsert(alloc);
this->noImplicitCallUsesToInsert = &localNoImplicitCallUsesToInsert;
IntConstantToStackSymMap localIntConstantToStackSymMap(alloc);
this->intConstantToStackSymMap = &localIntConstantToStackSymMap;
IntConstantToValueMap localIntConstantToValueMap(alloc);
this->intConstantToValueMap = &localIntConstantToValueMap;
Int64ConstantToValueMap localInt64ConstantToValueMap(alloc);
this->int64ConstantToValueMap = &localInt64ConstantToValueMap;
AddrConstantToValueMap localAddrConstantToValueMap(alloc);
this->addrConstantToValueMap = &localAddrConstantToValueMap;
StringConstantToValueMap localStringConstantToValueMap(alloc);
this->stringConstantToValueMap = &localStringConstantToValueMap;
SymIdToInstrMap localPrePassInstrMap(alloc);
this->prePassInstrMap = &localPrePassInstrMap;
ValueSetByValueNumber localValuesCreatedForClone(alloc, 64);
this->valuesCreatedForClone = &localValuesCreatedForClone;
ValueNumberPairToValueMap localValuesCreatedForMerge(alloc, 64);
this->valuesCreatedForMerge = &localValuesCreatedForMerge;
#if DBG
BVSparse<JitArenaAllocator> localFinishedStackLiteralInitFld(alloc);
this->finishedStackLiteralInitFld = &localFinishedStackLiteralInitFld;
#endif
FOREACH_BLOCK_IN_FUNC_EDITING(block, this->func)
{
this->OptBlock(block);
} NEXT_BLOCK_IN_FUNC_EDITING;
if (!PHASE_OFF(Js::MemOpPhase, this->func))
{
ProcessMemOp();
}
this->noImplicitCallUsesToInsert = nullptr;
this->intConstantToStackSymMap = nullptr;
this->intConstantToValueMap = nullptr;
this->int64ConstantToValueMap = nullptr;
this->addrConstantToValueMap = nullptr;
this->stringConstantToValueMap = nullptr;
#if DBG
this->finishedStackLiteralInitFld = nullptr;
uint freedCount = 0;
uint spilledCount = 0;
#endif
FOREACH_BLOCK_IN_FUNC(block, this->func)
{
#if DBG
if (block->GetDataUseCount() == 0)
{
freedCount++;
}
else
{
spilledCount++;
}
#endif
block->SetDataUseCount(0);
if (block->cloneStrCandidates)
{
JitAdelete(this->alloc, block->cloneStrCandidates);
block->cloneStrCandidates = nullptr;
}
} NEXT_BLOCK_IN_FUNC;
// Make sure we free most of them.
Assert(freedCount >= spilledCount);
// this->alloc will be freed right after return, no need to free it here
this->changedSymsAfterIncBailoutCandidate = nullptr;
this->auxSlotPtrSyms = nullptr;
END_CODEGEN_PHASE(this->func, Js::ForwardPhase);
}
void
GlobOpt::OptBlock(BasicBlock *block)
{
if (this->func->m_fg->RemoveUnreachableBlock(block, this))
{
GOPT_TRACE(_u("Removing unreachable block #%d\n"), block->GetBlockNum());
return;
}
Loop * loop = block->loop;
if (loop && block->isLoopHeader)
{
if (loop != this->prePassLoop)
{
OptLoops(loop);
if (!IsLoopPrePass() && loop->parent)
{
loop->fieldPRESymStores->Or(loop->parent->fieldPRESymStores);
}
if (!this->IsLoopPrePass() && DoFieldPRE(loop))
{
// Note: !IsLoopPrePass means this was a root loop pre-pass. FieldPre() is called once per loop.
this->FieldPRE(loop);
// Re-optimize the landing pad
BasicBlock *landingPad = loop->landingPad;
this->isRecursiveCallOnLandingPad = true;
this->OptBlock(landingPad);
this->isRecursiveCallOnLandingPad = false;
}
}
}
this->currentBlock = block;
PrepareLoopArrayCheckHoist();
block->MergePredBlocksValueMaps(this);
this->intOverflowCurrentlyMattersInRange = true;
this->intOverflowDoesNotMatterRange = this->currentBlock->intOverflowDoesNotMatterRange;
if (!DoFieldCopyProp() && !DoFieldRefOpts())
{
this->KillAllFields(CurrentBlockData()->liveFields);
}
this->tempAlloc->Reset();
if(loop && block->isLoopHeader)
{
loop->firstValueNumberInLoop = this->currentValue;
}
GOPT_TRACE_BLOCK(block, true);
FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrNext, block)
{
GOPT_TRACE_INSTRTRACE(instr);
BailOutInfo* oldBailOutInfo = nullptr;
bool isCheckAuxBailoutNeeded = this->func->IsJitInDebugMode() && !this->IsLoopPrePass();
if (isCheckAuxBailoutNeeded && instr->HasAuxBailOut() && !instr->HasBailOutInfo())
{
oldBailOutInfo = instr->GetBailOutInfo();
Assert(oldBailOutInfo);
}
bool isInstrRemoved = false;
instrNext = this->OptInstr(instr, &isInstrRemoved);
// If we still have instrs with only aux bail out, convert aux bail out back to regular bail out and fill it.
// During OptInstr some instr can be moved out to a different block, in this case bailout info is going to be replaced
// with e.g. loop bailout info which is filled as part of processing that block, thus we don't need to fill it here.
if (isCheckAuxBailoutNeeded && !isInstrRemoved && instr->HasAuxBailOut() && !instr->HasBailOutInfo())
{
if (instr->GetBailOutInfo() == oldBailOutInfo)
{
instr->PromoteAuxBailOut();
FillBailOutInfo(block, instr);
}
else
{
AssertMsg(instr->GetBailOutInfo(), "With aux bailout, the bailout info should not be removed by OptInstr.");
}
}
} NEXT_INSTR_IN_BLOCK_EDITING;
GOPT_TRACE_BLOCK(block, false);
if (block->loop)
{
if (IsLoopPrePass())
{
if (DoBoundCheckHoist())
{
DetectUnknownChangesToInductionVariables(&block->globOptData);
}
}
else
{
isPerformingLoopBackEdgeCompensation = true;
Assert(this->tempBv->IsEmpty());
BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
// On loop back-edges, we need to restore the state of the type specialized
// symbols to that of the loop header.
FOREACH_SUCCESSOR_BLOCK(succ, block)
{
if (succ->isLoopHeader && succ->loop->IsDescendentOrSelf(block->loop))
{
BVSparse<JitArenaAllocator> *liveOnBackEdge = block->loop->regAlloc.liveOnBackEdgeSyms;
liveOnBackEdge->Or(block->loop->fieldPRESymStores);
this->tempBv->Minus(block->loop->varSymsOnEntry, block->globOptData.liveVarSyms);
this->tempBv->And(liveOnBackEdge);
this->ToVar(this->tempBv, block);
// Lossy int in the loop header, and no int on the back-edge - need a lossy conversion to int
this->tempBv->Minus(block->loop->lossyInt32SymsOnEntry, block->globOptData.liveInt32Syms);
this->tempBv->And(liveOnBackEdge);
this->ToInt32(this->tempBv, block, true /* lossy */);
// Lossless int in the loop header, and no lossless int on the back-edge - need a lossless conversion to int
this->tempBv->Minus(block->loop->int32SymsOnEntry, block->loop->lossyInt32SymsOnEntry);
tempBv2.Minus(block->globOptData.liveInt32Syms, block->globOptData.liveLossyInt32Syms);
this->tempBv->Minus(&tempBv2);
this->tempBv->And(liveOnBackEdge);
this->ToInt32(this->tempBv, block, false /* lossy */);
this->tempBv->Minus(block->loop->float64SymsOnEntry, block->globOptData.liveFloat64Syms);
this->tempBv->And(liveOnBackEdge);
this->ToFloat64(this->tempBv, block);
// For ints and floats, go aggressive and type specialize in the landing pad any symbol which was specialized on
// entry to the loop body (in the loop header), and is still specialized on this tail, but wasn't specialized in
// the landing pad.
// Lossy int in the loop header and no int in the landing pad - need a lossy conversion to int
// (entry.lossyInt32 - landingPad.int32)
this->tempBv->Minus(block->loop->lossyInt32SymsOnEntry, block->loop->landingPad->globOptData.liveInt32Syms);
this->tempBv->And(liveOnBackEdge);
this->ToInt32(this->tempBv, block->loop->landingPad, true /* lossy */);
// Lossless int in the loop header, and no lossless int in the landing pad - need a lossless conversion to int
// ((entry.int32 - entry.lossyInt32) - (landingPad.int32 - landingPad.lossyInt32))
this->tempBv->Minus(block->loop->int32SymsOnEntry, block->loop->lossyInt32SymsOnEntry);
tempBv2.Minus(
block->loop->landingPad->globOptData.liveInt32Syms,
block->loop->landingPad->globOptData.liveLossyInt32Syms);
this->tempBv->Minus(&tempBv2);
this->tempBv->And(liveOnBackEdge);
this->ToInt32(this->tempBv, block->loop->landingPad, false /* lossy */);
// ((entry.float64 - landingPad.float64) & block.float64)
this->tempBv->Minus(block->loop->float64SymsOnEntry, block->loop->landingPad->globOptData.liveFloat64Syms);
this->tempBv->And(block->globOptData.liveFloat64Syms);
this->tempBv->And(liveOnBackEdge);
this->ToFloat64(this->tempBv, block->loop->landingPad);
// Now that we're done with the liveFields within this loop, trim the set to those syms
// that the backward pass told us were live out of the loop.
// This assumes we have no further need of the liveFields within the loop.
if (block->loop->liveOutFields)
{
block->globOptData.liveFields->And(block->loop->liveOutFields);
}
}
} NEXT_SUCCESSOR_BLOCK;
this->tempBv->ClearAll();
isPerformingLoopBackEdgeCompensation = false;
}
}
block->PathDepBranchFolding(this);
#if DBG
// The set of live lossy int32 syms should be a subset of all live int32 syms
this->tempBv->And(block->globOptData.liveInt32Syms, block->globOptData.liveLossyInt32Syms);
Assert(this->tempBv->Count() == block->globOptData.liveLossyInt32Syms->Count());
// The set of live lossy int32 syms should be a subset of live var or float syms (var or float sym containing the lossless
// value of the sym should be live)
this->tempBv->Or(block->globOptData.liveVarSyms, block->globOptData.liveFloat64Syms);
this->tempBv->And(block->globOptData.liveLossyInt32Syms);
Assert(this->tempBv->Count() == block->globOptData.liveLossyInt32Syms->Count());
this->tempBv->ClearAll();
Assert(this->currentBlock == block);
#endif
}
void
GlobOpt::OptLoops(Loop *loop)
{
Assert(loop != nullptr);
#if DBG
if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldCopyPropPhase) &&
!DoFunctionFieldCopyProp() && DoFieldCopyProp(loop))
{
Output::Print(_u("TRACE: CanDoFieldCopyProp Loop: "));
this->func->DumpFullFunctionName();
uint loopNumber = loop->GetLoopNumber();
Assert(loopNumber != Js::LoopHeader::NoLoop);
Output::Print(_u(" Loop: %d\n"), loopNumber);
}
#endif
Loop *previousLoop = this->prePassLoop;
this->prePassLoop = loop;
if (previousLoop == nullptr)
{
Assert(this->rootLoopPrePass == nullptr);
this->rootLoopPrePass = loop;
this->prePassInstrMap->Clear();
if (loop->parent == nullptr)
{
// Outer most loop...
this->prePassCopyPropSym->ClearAll();
}
}
Assert(loop->symsAssignedToInLoop != nullptr);
if (loop->symsUsedBeforeDefined == nullptr)
{
loop->symsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->likelyIntSymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->likelyNumberSymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->forceFloat64SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->symsDefInLoop = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->fieldKilled = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->fieldPRESymStores = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
loop->allFieldsKilled = false;
}
else
{
loop->symsUsedBeforeDefined->ClearAll();
loop->likelyIntSymsUsedBeforeDefined->ClearAll();
loop->likelyNumberSymsUsedBeforeDefined->ClearAll();
loop->forceFloat64SymsOnEntry->ClearAll();
loop->symsDefInLoop->ClearAll();
loop->fieldKilled->ClearAll();
loop->allFieldsKilled = false;
loop->initialValueFieldMap.Reset();
}
FOREACH_BLOCK_IN_LOOP(block, loop)
{
block->SetDataUseCount(block->GetSuccList()->Count());
OptBlock(block);
} NEXT_BLOCK_IN_LOOP;
if (previousLoop == nullptr)
{
Assert(this->rootLoopPrePass == loop);
this->rootLoopPrePass = nullptr;
}
this->prePassLoop = previousLoop;
}
void
GlobOpt::TailDupPass()
{
FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
{
BasicBlock* header = loop->GetHeadBlock();
BasicBlock* loopTail = nullptr;
FOREACH_PREDECESSOR_BLOCK(pred, header)
{
if (loop->IsDescendentOrSelf(pred->loop))
{
loopTail = pred;
break;
}
} NEXT_PREDECESSOR_BLOCK;
if (loopTail)
{
AssertMsg(loopTail->GetLastInstr()->IsBranchInstr(), "LastInstr of loop should always be a branch no?");
if (!loopTail->GetPredList()->HasOne())
{
TryTailDup(loopTail->GetLastInstr()->AsBranchInstr());
}
}
} NEXT_LOOP_IN_FUNC_EDITING;
}
bool
GlobOpt::TryTailDup(IR::BranchInstr *tailBranch)
{
if (PHASE_OFF(Js::TailDupPhase, tailBranch->m_func->GetTopFunc()))
{
return false;
}
if (tailBranch->IsConditional())
{
return false;
}
IR::Instr *instr;
uint instrCount = 0;
for (instr = tailBranch->GetPrevRealInstrOrLabel(); !instr->IsLabelInstr(); instr = instr->GetPrevRealInstrOrLabel())
{
if (instr->HasBailOutInfo())
{
break;
}
if (!OpCodeAttr::CanCSE(instr->m_opcode))
{
// Consider: We could be more aggressive here
break;
}
instrCount++;
if (instrCount > 1)
{
// Consider: If copy handled single-def tmps renaming, we could do more instrs
break;
}
}
if (!instr->IsLabelInstr())
{
return false;
}
IR::LabelInstr *mergeLabel = instr->AsLabelInstr();
IR::Instr *mergeLabelPrev = mergeLabel->m_prev;
// Skip unreferenced labels
while (mergeLabelPrev->IsLabelInstr() && mergeLabelPrev->AsLabelInstr()->labelRefs.Empty())
{
mergeLabelPrev = mergeLabelPrev->m_prev;
}
BasicBlock* labelBlock = mergeLabel->GetBasicBlock();
uint origPredCount = labelBlock->GetPredList()->Count();
uint dupCount = 0;
// We are good to go. Let's do the tail duplication.
FOREACH_SLISTCOUNTED_ENTRY_EDITING(IR::BranchInstr*, branchEntry, &mergeLabel->labelRefs, iter)
{
if (branchEntry->IsUnconditional() && !branchEntry->IsMultiBranch() && branchEntry != mergeLabelPrev && branchEntry != tailBranch)
{
for (instr = mergeLabel->m_next; instr != tailBranch; instr = instr->m_next)
{
branchEntry->InsertBefore(instr->Copy());
}
instr = branchEntry;
branchEntry->ReplaceTarget(mergeLabel, tailBranch->GetTarget());
while(!instr->IsLabelInstr())
{
instr = instr->m_prev;
}
BasicBlock* branchBlock = instr->AsLabelInstr()->GetBasicBlock();
labelBlock->RemovePred(branchBlock, func->m_fg);
func->m_fg->AddEdge(branchBlock, tailBranch->GetTarget()->GetBasicBlock());
dupCount++;
}
} NEXT_SLISTCOUNTED_ENTRY_EDITING;
// If we've duplicated everywhere, tail block is dead and should be removed.
if (dupCount == origPredCount)
{
AssertMsg(mergeLabel->labelRefs.Empty(), "Should not remove block with referenced label.");
func->m_fg->RemoveBlock(labelBlock, nullptr, true);
}
return true;
}
void
GlobOpt::ToVar(BVSparse<JitArenaAllocator> *bv, BasicBlock *block)
{
FOREACH_BITSET_IN_SPARSEBV(id, bv)
{
StackSym *stackSym = this->func->m_symTable->FindStackSym(id);
IR::RegOpnd *newOpnd = IR::RegOpnd::New(stackSym, TyVar, this->func);
IR::Instr *lastInstr = block->GetLastInstr();
if (lastInstr->IsBranchInstr() || lastInstr->m_opcode == Js::OpCode::BailTarget)
{
// If branch is using this symbol, hoist the operand as the ToVar load will get
// inserted right before the branch.
IR::Opnd *src1 = lastInstr->GetSrc1();
if (src1)
{
if (src1->IsRegOpnd() && src1->AsRegOpnd()->m_sym == stackSym)
{
lastInstr->HoistSrc1(Js::OpCode::Ld_A);
}
IR::Opnd *src2 = lastInstr->GetSrc2();
if (src2)
{
if (src2->IsRegOpnd() && src2->AsRegOpnd()->m_sym == stackSym)
{
lastInstr->HoistSrc2(Js::OpCode::Ld_A);
}
}
}
this->ToVar(lastInstr, newOpnd, block, nullptr, false);
}
else
{
IR::Instr *lastNextInstr = lastInstr->m_next;
this->ToVar(lastNextInstr, newOpnd, block, nullptr, false);
}
} NEXT_BITSET_IN_SPARSEBV;
}
void
GlobOpt::ToInt32(BVSparse<JitArenaAllocator> *bv, BasicBlock *block, bool lossy, IR::Instr *insertBeforeInstr)
{
return this->ToTypeSpec(bv, block, TyInt32, IR::BailOutIntOnly, lossy, insertBeforeInstr);
}
void
GlobOpt::ToFloat64(BVSparse<JitArenaAllocator> *bv, BasicBlock *block)
{
return this->ToTypeSpec(bv, block, TyFloat64, IR::BailOutNumberOnly);
}
void
GlobOpt::ToTypeSpec(BVSparse<JitArenaAllocator> *bv, BasicBlock *block, IRType toType, IR::BailOutKind bailOutKind, bool lossy, IR::Instr *insertBeforeInstr)
{
FOREACH_BITSET_IN_SPARSEBV(id, bv)
{
StackSym *stackSym = this->func->m_symTable->FindStackSym(id);
IRType fromType = TyIllegal;
// Win8 bug: 757126. If we are trying to type specialize the arguments object,
// let's make sure stack args optimization is not enabled. This is a problem, particularly,
// if the instruction comes from an unreachable block. In other cases, the pass on the
// instruction itself should disable arguments object optimization.
if(block->globOptData.argObjSyms && block->globOptData.IsArgumentsSymID(id))
{
CannotAllocateArgumentsObjectOnStack(nullptr);
}
if (block->globOptData.liveVarSyms->Test(id))
{
fromType = TyVar;
}
else if (block->globOptData.liveInt32Syms->Test(id) && !block->globOptData.liveLossyInt32Syms->Test(id))
{
fromType = TyInt32;
stackSym = stackSym->GetInt32EquivSym(this->func);
}
else if (block->globOptData.liveFloat64Syms->Test(id))
{
fromType = TyFloat64;
stackSym = stackSym->GetFloat64EquivSym(this->func);
}
else
{
Assert(UNREACHED);
}
IR::RegOpnd *newOpnd = IR::RegOpnd::New(stackSym, fromType, this->func);
this->ToTypeSpecUse(nullptr, newOpnd, block, nullptr, nullptr, toType, bailOutKind, lossy, insertBeforeInstr);
} NEXT_BITSET_IN_SPARSEBV;
}
void GlobOpt::PRE::FindPossiblePRECandidates(Loop *loop, JitArenaAllocator *alloc)
{
// Find the set of PRE candidates
BasicBlock *loopHeader = loop->GetHeadBlock();
PRECandidates *candidates = nullptr;
bool firstBackEdge = true;
FOREACH_PREDECESSOR_BLOCK(blockPred, loopHeader)
{
if (!loop->IsDescendentOrSelf(blockPred->loop))
{
// Not a loop back-edge
continue;
}
if (firstBackEdge)
{
candidates = this->globOpt->FindBackEdgePRECandidates(blockPred, alloc);
}
else
{
blockPred->globOptData.RemoveUnavailableCandidates(candidates);
}
} NEXT_PREDECESSOR_BLOCK;
this->candidates = candidates;
}
BOOL GlobOpt::PRE::PreloadPRECandidate(Loop *loop, GlobHashBucket* candidate)
{
// Insert a load for each field PRE candidate.
PropertySym *propertySym = candidate->value->AsPropertySym();
if (!candidates->candidatesToProcess->TestAndClear(propertySym->m_id))
{
return false;
}
Value * propSymValueOnBackEdge = candidate->element;
StackSym *objPtrSym = propertySym->m_stackSym;
Sym * objPtrCopyPropSym = nullptr;
if (!loop->landingPad->globOptData.IsLive(objPtrSym))
{
if (PHASE_OFF(Js::MakeObjSymLiveInLandingPadPhase, this->globOpt->func))
{
return false;
}
if (objPtrSym->IsSingleDef())
{
// We can still try to do PRE if the object sym is single def, even if its not live in the landing pad.
// We'll have to add a def instruction for the object sym in the landing pad, and then we can continue
// pre-loading the current PRE candidate.
// Case in point:
// $L1
// value|symStore
// t1 = o.x (v1|t3)
// t2 = t1.y (v2|t4) <-- t1 is not live in the loop landing pad
// jmp $L1
if (!InsertSymDefinitionInLandingPad(objPtrSym, loop, &objPtrCopyPropSym))
{
#if DBG_DUMP
TraceFailedPreloadInLandingPad(loop, propertySym, _u("Failed to insert load of object sym in landing pad"));
#endif
return false;
}
}
else
{
#if DBG_DUMP
TraceFailedPreloadInLandingPad(loop, propertySym, _u("Object sym not live in landing pad and not single-def"));
#endif
return false;
}
}
Assert(loop->landingPad->globOptData.IsLive(objPtrSym));
BasicBlock *landingPad = loop->landingPad;
Sym *symStore = propSymValueOnBackEdge->GetValueInfo()->GetSymStore();