-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
LinearScan.cpp
5270 lines (4633 loc) · 193 KB
/
LinearScan.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"
#include "SccLiveness.h"
#if DBG_DUMP || ENABLE_DEBUG_CONFIG_OPTIONS
char const * const RegNames[RegNumCount] =
{
#define REGDAT(Name, ListName, ...) "" STRINGIZE(ListName) "",
#include "RegList.h"
#undef REGDAT
};
char16 const * const RegNamesW[RegNumCount] =
{
#define REGDAT(Name, ListName, ...) _u("") STRINGIZEW(ListName) _u(""),
#include "RegList.h"
#undef REGDAT
};
#endif
static const uint8 RegAttribs[RegNumCount] =
{
#define REGDAT(Name, ListName, Encode, Type, Attribs) Attribs,
#include "RegList.h"
#undef REGDAT
};
extern const IRType RegTypes[RegNumCount] =
{
#define REGDAT(Name, ListName, Encode, Type, Attribs) Type,
#include "RegList.h"
#undef REGDAT
};
LoweredBasicBlock* LoweredBasicBlock::New(JitArenaAllocator* allocator)
{
return JitAnew(allocator, LoweredBasicBlock, allocator);
}
void LoweredBasicBlock::Delete(JitArenaAllocator* allocator)
{
JitAdelete(allocator, this);
}
void LoweredBasicBlock::Copy(LoweredBasicBlock* block)
{
this->inlineeFrameLifetimes.Copy(&block->inlineeFrameLifetimes);
this->inlineeStack.Copy(&block->inlineeStack);
this->inlineeFrameSyms.Copy(&block->inlineeFrameSyms);
}
bool LoweredBasicBlock::HasData()
{
return this->inlineeFrameLifetimes.Count() > 0 || this->inlineeStack.Count() > 0;
}
LoweredBasicBlock* LoweredBasicBlock::Clone(JitArenaAllocator* allocator)
{
if (this->HasData())
{
LoweredBasicBlock* clone = LoweredBasicBlock::New(allocator);
clone->Copy(this);
return clone;
}
return nullptr;
}
bool LoweredBasicBlock::Equals(LoweredBasicBlock* otherBlock)
{
if(this->HasData() != otherBlock->HasData())
{
return false;
}
if (!this->inlineeFrameLifetimes.Equals(&otherBlock->inlineeFrameLifetimes))
{
return false;
}
if (!this->inlineeStack.Equals(&otherBlock->inlineeStack))
{
return false;
}
return true;
}
// LinearScan::RegAlloc
// This register allocator is based on the 1999 linear scan register allocation paper
// by Poletto and Sarkar. This code however walks the IR while doing the lifetime
// allocations, and assigns the regs to all the RegOpnd as it goes. It assumes
// the IR is in R-DFO, and that the lifetime list is sorted in starting order.
// Lifetimes are allocated as they become live, and retired as they go dead. RegOpnd
// are assigned their register. If a lifetime becomes active and there are no free
// registers left, a lifetime is picked to be spilled.
// When we spill, the whole lifetime is spilled. All the loads and stores are done
// through memory for that lifetime, even the ones allocated before the current instruction.
// We do optimize this slightly by not reloading the previous loads that were not in loops.
void
LinearScan::RegAlloc()
{
NoRecoverMemoryJitArenaAllocator tempAlloc(_u("BE-LinearScan"), this->func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
this->tempAlloc = &tempAlloc;
this->opHelperSpilledLiveranges = JitAnew(&tempAlloc, SList<Lifetime *>, &tempAlloc);
this->activeLiveranges = JitAnew(&tempAlloc, SList<Lifetime *>, &tempAlloc);
this->liveOnBackEdgeSyms = JitAnew(&tempAlloc, BVSparse<JitArenaAllocator>, &tempAlloc);
this->stackPackInUseLiveRanges = JitAnew(&tempAlloc, SList<Lifetime *>, &tempAlloc);
this->stackSlotsFreeList = JitAnew(&tempAlloc, SList<StackSlot *>, &tempAlloc);
this->currentBlock = LoweredBasicBlock::New(&tempAlloc);
IR::Instr *currentInstr = this->func->m_headInstr;
SCCLiveness liveness(this->func, this->tempAlloc);
BEGIN_CODEGEN_PHASE(this->func, Js::LivenessPhase);
// Build the lifetime list
liveness.Build();
END_CODEGEN_PHASE(this->func, Js::LivenessPhase);
this->lifetimeList = &liveness.lifetimeList;
this->opHelperBlockList = &liveness.opHelperBlockList;
this->opHelperBlockIter = SList<OpHelperBlock>::Iterator(this->opHelperBlockList);
this->opHelperBlockIter.Next();
this->Init();
NativeCodeData::Allocator * nativeAllocator = this->func->GetNativeCodeDataAllocator();
if (func->hasBailout)
{
this->globalBailOutRecordTables = NativeCodeDataNewArrayZ(nativeAllocator, GlobalBailOutRecordDataTable *, func->m_inlineeId + 1);
this->lastUpdatedRowIndices = JitAnewArrayZ(this->tempAlloc, uint *, func->m_inlineeId + 1);
#ifdef PROFILE_BAILOUT_RECORD_MEMORY
if (Js::Configuration::Global.flags.ProfileBailOutRecordMemory)
{
this->func->GetScriptContext()->bailOutOffsetBytes += (sizeof(GlobalBailOutRecordDataTable *) * (func->m_inlineeId + 1));
this->func->GetScriptContext()->bailOutRecordBytes += (sizeof(GlobalBailOutRecordDataTable *) * (func->m_inlineeId + 1));
}
#endif
}
m_bailOutRecordCount = 0;
IR::Instr * insertBailInAfter = nullptr;
BailOutInfo * bailOutInfoForBailIn = nullptr;
bool endOfBasicBlock = true;
FOREACH_INSTR_EDITING(instr, instrNext, currentInstr)
{
if (instr->GetNumber() == 0)
{
AssertMsg(LowererMD::IsAssign(instr), "Only expect spill code here");
continue;
}
#if DBG_DUMP && defined(ENABLE_DEBUG_CONFIG_OPTIONS)
if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::LinearScanPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()))
{
instr->Dump();
}
#endif // DBG
this->currentInstr = instr;
if (instr->StartsBasicBlock() || endOfBasicBlock)
{
endOfBasicBlock = false;
++currentBlockNumber;
}
bool isLoopBackEdge = false;
if (instr->IsLabelInstr())
{
this->lastLabel = instr->AsLabelInstr();
if (this->lastLabel->m_loweredBasicBlock)
{
IR::Instr *const prevInstr = instr->GetPrevRealInstrOrLabel();
Assert(prevInstr);
if (prevInstr->HasFallThrough())
{
this->currentBlock->Delete(&tempAlloc);
}
this->currentBlock = this->lastLabel->m_loweredBasicBlock;
}
else if (currentBlock->HasData())
{
// Check if the previous block has fall-through. If so, retain the block info. If not, create empty info.
IR::Instr *const prevInstr = instr->GetPrevRealInstrOrLabel();
Assert(prevInstr);
if (!prevInstr->HasFallThrough())
{
currentBlock = LoweredBasicBlock::New(&tempAlloc);
}
}
this->currentRegion = this->lastLabel->GetRegion();
}
else if (instr->IsBranchInstr())
{
if (this->func->HasTry() && this->func->DoOptimizeTry())
{
this->ProcessEHRegionBoundary(instr);
}
isLoopBackEdge = this->IsInLoop() && instr->GetNumber() >= this->curLoop->regAlloc.loopEnd;
}
if (this->RemoveDeadStores(instr))
{
continue;
}
#if DBG
// Since not all call instructions are forwarded to ChangeToHelperCall, we might have
// missed allocating bailout records for them. Additionally, some instructions might
// end up being lowered differently, so the lazy bailout is not on a CALL instruction
// anymore. Use this opportunity to detect them.
// Note that the dump for the instruction will also be printed with -ForcePostLowerGlobOptInstrString
if (instr->HasBailOutInfo() && instr->GetBailOutInfo()->bailOutRecord == nullptr)
{
if (CONFIG_FLAG(ForcePostLowerGlobOptInstrString))
{
// The instruction has already been lowered, find the start to get the globopt dump
IR::Instr *curr = instr;
while (curr->globOptInstrString == nullptr)
{
curr = curr->m_prev;
}
instr->Dump();
curr->DumpGlobOptInstrString();
}
AssertMsg(false, "Lazy bailout: bailOutRecord not allocated");
}
#endif
if (instr->HasBailOutInfo() && !instr->HasLazyBailOut())
{
if (this->currentRegion)
{
RegionType curRegType = this->currentRegion->GetType();
if (curRegType == RegionTypeTry || curRegType == RegionTypeCatch || curRegType == RegionTypeFinally)
{
this->func->hasBailoutInEHRegion = true;
}
}
this->FillBailOutRecord(instr);
if (instr->GetBailOutKind() == IR::BailOutForGeneratorYield)
{
Assert(insertBailInAfter == nullptr);
bailOutInfoForBailIn = instr->GetBailOutInfo();
insertBailInAfter = instr->m_next;
// Insert right after the GeneratorBailInLabel
// The register allocator might insert some compensation code between
// the BailOutForGeneratorYield and the GeneratorBailInLabel, so our
// bail-in insertion point is not necessarily always the next instruction.
while (insertBailInAfter != nullptr && insertBailInAfter->m_opcode != Js::OpCode::GeneratorBailInLabel)
{
insertBailInAfter = insertBailInAfter->m_next;
}
}
}
this->SetSrcRegs(instr);
this->EndDeadLifetimes(instr, isLoopBackEdge);
if (instr->IsBranchInstr())
{
this->ProcessSecondChanceBoundary(instr->AsBranchInstr());
}
this->CheckIfInLoop(instr);
if (isLoopBackEdge)
{
this->EndDeadLifetimes(instr, false);
}
this->CheckOpHelper(instr);
this->KillImplicitRegs(instr);
this->ProcessLazyBailOut(instr);
this->AllocateNewLifetimes(instr);
this->SetDstReg(instr);
this->EndDeadOpHelperLifetimes(instr);
if (instr->IsLabelInstr())
{
this->ProcessSecondChanceBoundary(instr->AsLabelInstr());
}
#if DBG
this->CheckInvariants();
#endif // DBG
if(instr->EndsBasicBlock())
{
endOfBasicBlock = true;
}
if (insertBailInAfter == instr)
{
instrNext = this->bailIn.GenerateBailIn(instr, bailOutInfoForBailIn);
insertBailInAfter = nullptr;
bailOutInfoForBailIn = nullptr;
}
} NEXT_INSTR_EDITING;
if (func->hasBailout)
{
for (uint i = 0; i <= func->m_inlineeId; i++)
{
if (globalBailOutRecordTables[i] != nullptr)
{
globalBailOutRecordTables[i]->Finalize(nativeAllocator, &tempAlloc);
#ifdef PROFILE_BAILOUT_RECORD_MEMORY
if (Js::Configuration::Global.flags.ProfileBailOutRecordMemory)
{
func->GetScriptContext()->bailOutOffsetBytes += sizeof(GlobalBailOutRecordDataRow) * globalBailOutRecordTables[i]->length;
func->GetScriptContext()->bailOutRecordBytes += sizeof(GlobalBailOutRecordDataRow) * globalBailOutRecordTables[i]->length;
}
#endif
}
}
}
AssertMsg((this->intRegUsedCount + this->floatRegUsedCount) == this->linearScanMD.UnAllocatableRegCount(this->func) , "RegUsedCount is wrong");
AssertMsg(this->activeLiveranges->Empty(), "Active list not empty");
AssertMsg(this->stackPackInUseLiveRanges->Empty(), "Spilled list not empty");
AssertMsg(!this->opHelperBlockIter.IsValid(), "Got to the end with a helper block still on the list?");
Assert(this->currentBlock->inlineeStack.Count() == 0);
this->InsertOpHelperSpillAndRestores();
#if _M_IX86
# if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.Instrument.IsEnabled(Js::LinearScanPhase, this->func->GetSourceContextId(),this->func->GetLocalFunctionId()))
{
this->DynamicStatsInstrument();
}
# endif
#endif
#if DBG_DUMP
if (PHASE_STATS(Js::LinearScanPhase, this->func))
{
this->PrintStats();
}
if (PHASE_TRACE(Js::StackPackPhase, this->func))
{
Output::Print(_u("---------------------------\n"));
}
#endif // DBG_DUMP
DebugOnly(this->func->allowRemoveBailOutArgInstr = true);
}
JitArenaAllocator *
LinearScan::GetTempAlloc()
{
Assert(tempAlloc);
return tempAlloc;
}
#if DBG
void
LinearScan::CheckInvariants() const
{
BitVector bv = this->nonAllocatableRegs;
uint32 lastend = 0;
FOREACH_SLIST_ENTRY(Lifetime *, lifetime, this->activeLiveranges)
{
// Make sure there are only one lifetime per reg
Assert(!bv.Test(lifetime->reg));
bv.Set(lifetime->reg);
Assert(!lifetime->isOpHelperSpilled);
Assert(!lifetime->isSpilled);
Assert(lifetime->end >= lastend);
lastend = lifetime->end;
}
NEXT_SLIST_ENTRY;
// Make sure the active reg bit vector is correct
Assert(bv.Equal(this->activeRegs));
uint ints = 0, floats = 0;
FOREACH_BITSET_IN_UNITBV(index, this->activeRegs, BitVector)
{
if (IRType_IsFloat(RegTypes[index]))
{
floats++;
}
else
{
ints++;
}
}
NEXT_BITSET_IN_UNITBV;
Assert(ints == this->intRegUsedCount);
Assert(floats == this->floatRegUsedCount);
Assert((this->intRegUsedCount + this->floatRegUsedCount) == this->activeRegs.Count());
bv.ClearAll();
lastend = 0;
FOREACH_SLIST_ENTRY(Lifetime *, lifetime, this->opHelperSpilledLiveranges)
{
// Make sure there are only one lifetime per reg in the op helper spilled liveranges
Assert(!bv.Test(lifetime->reg));
if (!lifetime->cantOpHelperSpill)
{
bv.Set(lifetime->reg);
Assert(lifetime->isOpHelperSpilled);
Assert(!lifetime->isSpilled);
}
Assert(lifetime->end >= lastend);
lastend = lifetime->end;
}
NEXT_SLIST_ENTRY;
// Make sure the opHelperSpilledRegs bit vector is correct
Assert(bv.Equal(this->opHelperSpilledRegs));
for (int i = 0; i < RegNumCount; i++)
{
if (this->tempRegs.Test(i))
{
Assert(this->tempRegLifetimes[i]->reg == i);
}
}
FOREACH_BITSET_IN_UNITBV(reg, this->secondChanceRegs, BitVector)
{
Lifetime *lifetime = this->regContent[reg];
Assert(lifetime);
StackSym *sym = lifetime->sym;
Assert(lifetime->isSecondChanceAllocated);
Assert(sym->IsConst() || sym->IsAllocated()); // Should have been spilled already.
} NEXT_BITSET_IN_UNITBV;
}
#endif // DBG
// LinearScan::Init
// Initialize bit vectors
void
LinearScan::Init()
{
FOREACH_REG(reg)
{
// Registers that can't be used are set to active, and will remain this way
if (!LinearScan::IsAllocatable(reg))
{
this->activeRegs.Set(reg);
if (IRType_IsFloat(RegTypes[reg]))
{
this->floatRegUsedCount++;
}
else
{
this->intRegUsedCount++;
}
}
if (RegTypes[reg] == TyMachReg)
{
// JIT64_TODO: Rename int32Regs to machIntRegs.
this->int32Regs.Set(reg);
numInt32Regs++;
}
else if (RegTypes[reg] == TyFloat64)
{
this->floatRegs.Set(reg);
numFloatRegs++;
}
if (LinearScan::IsCallerSaved(reg))
{
this->callerSavedRegs.Set(reg);
}
if (LinearScan::IsCalleeSaved(reg))
{
this->calleeSavedRegs.Set(reg);
}
this->regContent[reg] = nullptr;
} NEXT_REG;
this->instrUseRegs.ClearAll();
this->secondChanceRegs.ClearAll();
this->linearScanMD.Init(this);
#if DBG
this->nonAllocatableRegs = this->activeRegs;
#endif
#if DBG_DUMP
if (PHASE_TRACE(Js::LinearScanPhase, this->func))
{
this->func->DumpHeader();
}
#endif
}
// LinearScan::CheckIfInLoop
// Track whether the current instruction is in a loop or not.
bool
LinearScan::CheckIfInLoop(IR::Instr *instr)
{
if (this->IsInLoop())
{
// Look for end of loop
AssertMsg(this->curLoop->regAlloc.loopEnd != 0, "Something is wrong here....");
if (instr->GetNumber() >= this->curLoop->regAlloc.loopEnd)
{
AssertMsg(instr->IsBranchInstr(), "Loop tail should be a branchInstr");
while (this->IsInLoop() && instr->GetNumber() >= this->curLoop->regAlloc.loopEnd)
{
this->loopNest--;
this->curLoop->regAlloc.defdInLoopBv->ClearAll();
this->curLoop->regAlloc.symRegUseBv->ClearAll();
this->curLoop->regAlloc.liveOnBackEdgeSyms->ClearAll();
this->curLoop->regAlloc.exitRegContentList->Clear();
this->curLoop->isProcessed = true;
this->curLoop = this->curLoop->parent;
if (this->loopNest == 0)
{
this->liveOnBackEdgeSyms->ClearAll();
}
}
}
}
if (instr->IsLabelInstr() && instr->AsLabelInstr()->m_isLoopTop)
{
IR::LabelInstr * labelInstr = instr->AsLabelInstr();
Loop *parentLoop = this->curLoop;
if (parentLoop)
{
parentLoop->isLeaf = false;
}
this->curLoop = labelInstr->GetLoop();
this->curLoop->isProcessed = false;
// Lexically nested may not always nest in a flow based way:
// while(i--) {
// if (cond) {
// while(j--) {
// }
// break;
// }
// }
// These look nested, but they are not...
// So update the flow based parent to be lexical or we won't be able to figure out when we get back
// to the outer loop.
// REVIEW: This isn't necessary anymore now that break blocks are moved out of the loops.
this->curLoop->parent = parentLoop;
this->curLoop->regAlloc.defdInLoopBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
this->curLoop->regAlloc.symRegUseBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
this->curLoop->regAlloc.loopStart = labelInstr->GetNumber();
this->curLoop->regAlloc.exitRegContentList = JitAnew(this->tempAlloc, SList<Lifetime **>, this->tempAlloc);
this->curLoop->regAlloc.regUseBv = 0;
this->liveOnBackEdgeSyms->Or(this->curLoop->regAlloc.liveOnBackEdgeSyms);
this->loopNest++;
}
return this->IsInLoop();
}
void
LinearScan::InsertOpHelperSpillAndRestores()
{
linearScanMD.InsertOpHelperSpillAndRestores(opHelperBlockList);
}
void
LinearScan::CheckOpHelper(IR::Instr *instr)
{
if (this->IsInHelperBlock())
{
if (this->currentOpHelperBlock->opHelperEndInstr == instr)
{
// Get targetInstr if we can.
// We can deterministically get it only for unconditional branches, as conditional branch may fall through.
IR::Instr * targetInstr = nullptr;
if (instr->IsBranchInstr() && instr->AsBranchInstr()->IsUnconditional())
{
AssertMsg(!instr->AsBranchInstr()->IsMultiBranch(), "Not supported for Multibranch");
targetInstr = instr->AsBranchInstr()->GetTarget();
}
/*
* Keep track of the number of registers we've had to
* store and restore around a helper block for LinearScanMD (on ARM
* and X64). We need this to be able to allocate space in the frame.
* We can't emit a PUSH/POP sequence around the block like IA32 because
* the stack pointer can't move outside the prolog.
*/
uint32 helperSpilledLiverangeCount = 0;
// Exiting a helper block. We are going to insert
// the restore here after linear scan. So put all the restored
// lifetime back to active
while (!this->opHelperSpilledLiveranges->Empty())
{
Lifetime * lifetime = this->opHelperSpilledLiveranges->Pop();
lifetime->isOpHelperSpilled = false;
if (!lifetime->cantOpHelperSpill)
{
// Put the life time back to active
this->AssignActiveReg(lifetime, lifetime->reg);
bool reload = true;
// Lifetime ends before the target after helper block, don't need to save and restore helper spilled lifetime.
if (targetInstr && lifetime->end < targetInstr->GetNumber())
{
// However, if lifetime is spilled as arg - we still need to spill it because the helper assumes the value
// to be available in the stack
if (lifetime->isOpHelperSpillAsArg)
{
// we should not attempt to restore it as it is dead on return from the helper.
reload = false;
}
else
{
Assert(!instr->AsBranchInstr()->IsLoopTail(this->func));
continue;
}
}
// Save all the lifetime that needs to be restored
OpHelperSpilledLifetime spilledLifetime;
spilledLifetime.lifetime = lifetime;
spilledLifetime.spillAsArg = lifetime->isOpHelperSpillAsArg;
spilledLifetime.reload = reload;
/*
* Can't unfortunately move this into the else block above because we don't know if this
* lifetime will actually get spilled until register allocation completes.
* Instead we allocate a slot to this StackSym in LinearScanMD iff
* !(lifetime.isSpilled && lifetime.noReloadsIfSpilled).
*/
helperSpilledLiverangeCount++;
// save the reg in case it is spilled later. We still need to save and restore
// for the non-loop case.
spilledLifetime.reg = lifetime->reg;
this->currentOpHelperBlock->spilledLifetime.Prepend(spilledLifetime);
}
else
{
// Clear it for the next helper block
lifetime->cantOpHelperSpill = false;
}
lifetime->isOpHelperSpillAsArg = false;
}
this->totalOpHelperFullVisitedLength += this->currentOpHelperBlock->Length();
// Use a dummy label as the insertion point of the reloads, as second-chance-allocation
// may insert compensation code right before the branch
IR::PragmaInstr *dummyLabel = IR::PragmaInstr::New(Js::OpCode::Nop, 0, this->func);
this->currentOpHelperBlock->opHelperEndInstr->InsertBefore(dummyLabel);
dummyLabel->CopyNumber(this->currentOpHelperBlock->opHelperEndInstr);
this->currentOpHelperBlock->opHelperEndInstr = dummyLabel;
this->opHelperSpilledRegs.ClearAll();
this->currentOpHelperBlock = nullptr;
linearScanMD.EndOfHelperBlock(helperSpilledLiverangeCount);
}
}
if (this->opHelperBlockIter.IsValid())
{
AssertMsg(
!instr->IsLabelInstr() ||
!instr->AsLabelInstr()->isOpHelper ||
this->opHelperBlockIter.Data().opHelperLabel == instr,
"Found a helper label that doesn't begin the next helper block in the list?");
if (this->opHelperBlockIter.Data().opHelperLabel == instr)
{
this->currentOpHelperBlock = &this->opHelperBlockIter.Data();
this->opHelperBlockIter.Next();
}
}
}
uint
LinearScan::HelperBlockStartInstrNumber() const
{
Assert(IsInHelperBlock());
return this->currentOpHelperBlock->opHelperLabel->GetNumber();
}
uint
LinearScan::HelperBlockEndInstrNumber() const
{
Assert(IsInHelperBlock());
return this->currentOpHelperBlock->opHelperEndInstr->GetNumber();
}
// LinearScan::AddToActive
// Add a lifetime to the active list. The list is kept sorted in order lifetime end.
// This makes it easier to pick the lifetimes to retire.
void
LinearScan::AddToActive(Lifetime * lifetime)
{
LinearScan::AddLiveRange(this->activeLiveranges, lifetime);
this->regContent[lifetime->reg] = lifetime;
if (lifetime->isSecondChanceAllocated)
{
this->secondChanceRegs.Set(lifetime->reg);
}
else
{
Assert(!this->secondChanceRegs.Test(lifetime->reg));
}
}
void
LinearScan::AddOpHelperSpilled(Lifetime * lifetime)
{
RegNum reg = lifetime->reg;
Assert(this->IsInHelperBlock());
Assert(!this->opHelperSpilledRegs.Test(reg));
Assert(lifetime->isOpHelperSpilled == false);
Assert(lifetime->cantOpHelperSpill == false);
this->opHelperSpilledRegs.Set(reg);
lifetime->isOpHelperSpilled = true;
this->regContent[reg] = nullptr;
this->secondChanceRegs.Clear(reg);
// If a lifetime is being OpHelper spilled and it's an inlinee arg sym
// we need to make sure its spilled to the sym offset spill space, i.e. isOpHelperSpillAsArg
// is set. Otherwise, it's value will not be available on inline frame reconstruction.
if (this->currentBlock->inlineeFrameSyms.Count() > 0 &&
this->currentBlock->inlineeFrameSyms.ContainsKey(lifetime->sym->m_id) &&
(lifetime->sym->m_isSingleDef || !lifetime->defList.Empty()))
{
lifetime->isOpHelperSpillAsArg = true;
if (!lifetime->sym->IsAllocated())
{
this->AllocateStackSpace(lifetime);
}
this->RecordLoopUse(lifetime, lifetime->reg);
}
LinearScan::AddLiveRange(this->opHelperSpilledLiveranges, lifetime);
}
void
LinearScan::RemoveOpHelperSpilled(Lifetime * lifetime)
{
Assert(this->IsInHelperBlock());
Assert(lifetime->isOpHelperSpilled);
Assert(lifetime->cantOpHelperSpill == false);
Assert(this->opHelperSpilledRegs.Test(lifetime->reg));
this->opHelperSpilledRegs.Clear(lifetime->reg);
lifetime->isOpHelperSpilled = false;
lifetime->cantOpHelperSpill = false;
lifetime->isOpHelperSpillAsArg = false;
this->opHelperSpilledLiveranges->Remove(lifetime);
}
void
LinearScan::SetCantOpHelperSpill(Lifetime * lifetime)
{
Assert(this->IsInHelperBlock());
Assert(lifetime->isOpHelperSpilled);
Assert(lifetime->cantOpHelperSpill == false);
this->opHelperSpilledRegs.Clear(lifetime->reg);
lifetime->isOpHelperSpilled = false;
lifetime->cantOpHelperSpill = true;
}
void
LinearScan::AddLiveRange(SList<Lifetime *> * list, Lifetime * newLifetime)
{
FOREACH_SLIST_ENTRY_EDITING(Lifetime *, lifetime, list, iter)
{
if (newLifetime->end < lifetime->end)
{
break;
}
}
NEXT_SLIST_ENTRY_EDITING;
iter.InsertBefore(newLifetime);
}
Lifetime *
LinearScan::RemoveRegLiveRange(SList<Lifetime *> * list, RegNum reg)
{
// Find the register in the active set
FOREACH_SLIST_ENTRY_EDITING(Lifetime *, lifetime, list, iter)
{
if (lifetime->reg == reg)
{
Lifetime * lifetimeReturn = lifetime;
iter.RemoveCurrent();
return lifetimeReturn;
}
} NEXT_SLIST_ENTRY_EDITING;
AssertMsg(false, "Can't find life range for a reg");
return nullptr;
}
// LinearScan::SetDstReg
// Set the reg on each RegOpnd def.
void
LinearScan::SetDstReg(IR::Instr *instr)
{
//
// Enregister dst
//
IR::Opnd *dst = instr->GetDst();
if (dst == nullptr)
{
return;
}
if (!dst->IsRegOpnd())
{
// This could be, for instance, a store to a sym with a large offset
// that was just assigned when we saw the use.
this->linearScanMD.LegalizeDef(instr);
return;
}
IR::RegOpnd * regOpnd = dst->AsRegOpnd();
/*
* If this is a register used to setup a callsite per
* a calling convention then mark it unavailable to allocate
* until we see a CALL.
*/
if (regOpnd->m_isCallArg)
{
RegNum callSetupReg = regOpnd->GetReg();
callSetupRegs.Set(callSetupReg);
}
StackSym * stackSym = regOpnd->m_sym;
// Arg slot sym can be in a RegOpnd for param passed via registers
// Just use the assigned register
if (stackSym == nullptr || stackSym->IsArgSlotSym())
{
//
// Already allocated register. just spill the destination
//
RegNum reg = regOpnd->GetReg();
if(LinearScan::IsAllocatable(reg))
{
this->SpillReg(reg);
}
this->tempRegs.Clear(reg);
}
else
{
if (regOpnd->GetReg() != RegNOREG)
{
this->RecordLoopUse(nullptr, regOpnd->GetReg());
// Nothing to do
return;
}
Lifetime * lifetime = stackSym->scratch.linearScan.lifetime;
uint32 useCountCost = LinearScan::GetUseSpillCost(this->loopNest, (this->currentOpHelperBlock != nullptr));
// Optimistically decrease the useCount. We'll undo this if we put it on the defList.
lifetime->SubFromUseCount(useCountCost, this->curLoop);
if (lifetime->isSpilled)
{
if (stackSym->IsConst() && !IsSymNonTempLocalVar(stackSym))
{
// We will reload the constant (but in debug mode, we still need to process this if this is a user var).
return;
}
RegNum reg = regOpnd->GetReg();
if (reg != RegNOREG)
{
// It is already assigned, just record it as a temp reg
this->AssignTempReg(lifetime, reg);
}
else
{
IR::Opnd *src1 = instr->GetSrc1();
IR::Opnd *src2 = instr->GetSrc2();
if ((src1 && src1->IsRegOpnd() && src1->AsRegOpnd()->m_sym == stackSym) ||
(src2 && src2->IsRegOpnd() && src2->AsRegOpnd()->m_sym == stackSym))
{
// OpEQ: src1 should have a valid reg (put src2 for other targets)
reg = this->GetAssignedTempReg(lifetime, dst->GetType());
Assert(reg != RegNOREG);
RecordDef(lifetime, instr, 0);
}
else
{
// Try second chance
reg = this->SecondChanceAllocation(lifetime, false);
if (reg != RegNOREG)
{
Assert(!stackSym->m_isSingleDef);
this->SetReg(regOpnd);
// Keep track of defs for this lifetime, in case it gets spilled.
RecordDef(lifetime, instr, useCountCost);
return;
}
else
{
reg = this->GetAssignedTempReg(lifetime, dst->GetType());
RecordDef(lifetime, instr, 0);
}
}
if (LowererMD::IsAssign(instr) && instr->GetSrc1()->IsRegOpnd())
{
// Fold the spilled store
if (reg != RegNOREG)
{
// If the value is in a temp reg, it's not valid any more.
this->tempRegs.Clear(reg);
}
IRType srcType = instr->GetSrc1()->GetType();
instr->ReplaceDst(IR::SymOpnd::New(stackSym, srcType, this->func));
this->linearScanMD.LegalizeDef(instr);
return;
}
if (reg == RegNOREG)
{
IR::Opnd *src = instr->GetSrc1();
if (src && src->IsRegOpnd() && src->AsRegOpnd()->m_sym == stackSym)
{
// Handle OPEQ's for x86/x64
reg = src->AsRegOpnd()->GetReg();
AssertMsg(!this->activeRegs.Test(reg), "Shouldn't be active");
}
else
{
// The lifetime was spilled, but we still need a reg for this operand.
reg = this->FindReg(nullptr, regOpnd);
}
this->AssignTempReg(lifetime, reg);
}
}
if (!lifetime->isDeadStore && !lifetime->isSecondChanceAllocated)
{
// Insert a store since the lifetime is spilled
this->InsertStore(instr, regOpnd->m_sym, reg);
}
}
else
{
if (lifetime->isOpHelperSpilled)
{
// We must be in a helper block and the lifetime must
// start before the helper block
Assert(this->IsInHelperBlock());
Assert(lifetime->start < this->HelperBlockStartInstrNumber());
RegNum reg = lifetime->reg;
Assert(this->opHelperSpilledRegs.Test(reg));
if (this->activeRegs.Test(reg))
{
// The reg must have been used locally in the helper block
// by some other lifetime. Just spill it
this->SpillReg(reg);
}
// We can't save/restore this reg across the helper call because the restore would overwrite
// this def, but the def means we don't need to spill at all. Mark the lifetime as cantOpHelperSpill
// however in case another helper call in this block tries to spill it.
this->SetCantOpHelperSpill(lifetime);
this->AddToActive(lifetime);
this->tempRegs.Clear(reg);