This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
lsra.cpp
12898 lines (11738 loc) · 493 KB
/
lsra.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Linear Scan Register Allocation
a.k.a. LSRA
Preconditions
- All register requirements are expressed in the code stream, either as destination
registers of tree nodes, or as internal registers. These requirements are
expressed in the TreeNodeInfo (gtLsraInfo) on each node, which includes:
- The number of register sources and destinations.
- The register restrictions (candidates) of the target register, both from itself,
as producer of the value (dstCandidates), and from its consuming node (srcCandidates).
Note that the srcCandidates field of TreeNodeInfo refers to the destination register
(not any of its sources).
- The number (internalCount) of registers required, and their register restrictions (internalCandidates).
These are neither inputs nor outputs of the node, but used in the sequence of code generated for the tree.
"Internal registers" are registers used during the code sequence generated for the node.
The register lifetimes must obey the following lifetime model:
- First, any internal registers are defined.
- Next, any source registers are used (and are then freed if they are last use and are not identified as
"delayRegFree").
- Next, the internal registers are used (and are then freed).
- Next, any registers in the kill set for the instruction are killed.
- Next, the destination register(s) are defined (multiple destination registers are only supported on ARM)
- Finally, any "delayRegFree" source registers are freed.
There are several things to note about this order:
- The internal registers will never overlap any use, but they may overlap a destination register.
- Internal registers are never live beyond the node.
- The "delayRegFree" annotation is used for instructions that are only available in a Read-Modify-Write form.
That is, the destination register is one of the sources. In this case, we must not use the same register for
the non-RMW operand as for the destination.
Overview (doLinearScan):
- Walk all blocks, building intervals and RefPositions (buildIntervals)
- Allocate registers (allocateRegisters)
- Annotate nodes with register assignments (resolveRegisters)
- Add move nodes as needed to resolve conflicting register
assignments across non-adjacent edges. (resolveEdges, called from resolveRegisters)
Postconditions:
Tree nodes (GenTree):
- GenTree::gtRegNum (and gtRegPair for ARM) is annotated with the register
assignment for a node. If the node does not require a register, it is
annotated as such (for single registers, gtRegNum = REG_NA; for register
pair type, gtRegPair = REG_PAIR_NONE). For a variable definition or interior
tree node (an "implicit" definition), this is the register to put the result.
For an expression use, this is the place to find the value that has previously
been computed.
- In most cases, this register must satisfy the constraints specified by the TreeNodeInfo.
- In some cases, this is difficult:
- If a lclVar node currently lives in some register, it may not be desirable to move it
(i.e. its current location may be desirable for future uses, e.g. if it's a callee save register,
but needs to be in a specific arg register for a call).
- In other cases there may be conflicts on the restrictions placed by the defining node and the node which
consumes it
- If such a node is constrained to a single fixed register (e.g. an arg register, or a return from a call),
then LSRA is free to annotate the node with a different register. The code generator must issue the appropriate
move.
- However, if such a node is constrained to a set of registers, and its current location does not satisfy that
requirement, LSRA must insert a GT_COPY node between the node and its parent. The gtRegNum on the GT_COPY node
must satisfy the register requirement of the parent.
- GenTree::gtRsvdRegs has a set of registers used for internal temps.
- A tree node is marked GTF_SPILL if the tree node must be spilled by the code generator after it has been
evaluated.
- LSRA currently does not set GTF_SPILLED on such nodes, because it caused problems in the old code generator.
In the new backend perhaps this should change (see also the note below under CodeGen).
- A tree node is marked GTF_SPILLED if it is a lclVar that must be reloaded prior to use.
- The register (gtRegNum) on the node indicates the register to which it must be reloaded.
- For lclVar nodes, since the uses and defs are distinct tree nodes, it is always possible to annotate the node
with the register to which the variable must be reloaded.
- For other nodes, since they represent both the def and use, if the value must be reloaded to a different
register, LSRA must insert a GT_RELOAD node in order to specify the register to which it should be reloaded.
Local variable table (LclVarDsc):
- LclVarDsc::lvRegister is set to true if a local variable has the
same register assignment for its entire lifetime.
- LclVarDsc::lvRegNum / lvOtherReg: these are initialized to their
first value at the end of LSRA (it looks like lvOtherReg isn't?
This is probably a bug (ARM)). Codegen will set them to their current value
as it processes the trees, since a variable can (now) be assigned different
registers over its lifetimes.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator
#include "lsra.h"
#ifdef DEBUG
const char* LinearScan::resolveTypeName[] = {"Split", "Join", "Critical", "SharedCritical"};
#endif // DEBUG
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Small Helper functions XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
//--------------------------------------------------------------
// lsraAssignRegToTree: Assign the given reg to tree node.
//
// Arguments:
// tree - Gentree node
// reg - register to be assigned
// regIdx - register idx, if tree is a multi-reg call node.
// regIdx will be zero for single-reg result producing tree nodes.
//
// Return Value:
// None
//
void lsraAssignRegToTree(GenTreePtr tree, regNumber reg, unsigned regIdx)
{
if (regIdx == 0)
{
tree->gtRegNum = reg;
}
#if defined(_TARGET_ARM_)
else if (tree->OperGet() == GT_MUL_LONG || tree->OperGet() == GT_PUTARG_REG)
{
assert(regIdx == 1);
GenTreeMultiRegOp* mul = tree->AsMultiRegOp();
mul->gtOtherReg = reg;
}
else if (tree->OperGet() == GT_COPY)
{
assert(regIdx == 1);
GenTreeCopyOrReload* copy = tree->AsCopyOrReload();
copy->gtOtherRegs[0] = (regNumberSmall)reg;
}
else if (tree->OperGet() == GT_PUTARG_SPLIT)
{
GenTreePutArgSplit* putArg = tree->AsPutArgSplit();
putArg->SetRegNumByIdx(reg, regIdx);
}
#endif // _TARGET_ARM_
else
{
assert(tree->IsMultiRegCall());
GenTreeCall* call = tree->AsCall();
call->SetRegNumByIdx(reg, regIdx);
}
}
//-------------------------------------------------------------
// getWeight: Returns the weight of the RefPosition.
//
// Arguments:
// refPos - ref position
//
// Returns:
// Weight of ref position.
unsigned LinearScan::getWeight(RefPosition* refPos)
{
unsigned weight;
GenTreePtr treeNode = refPos->treeNode;
if (treeNode != nullptr)
{
if (isCandidateLocalRef(treeNode))
{
// Tracked locals: use weighted ref cnt as the weight of the
// ref position.
GenTreeLclVarCommon* lclCommon = treeNode->AsLclVarCommon();
LclVarDsc* varDsc = &(compiler->lvaTable[lclCommon->gtLclNum]);
weight = varDsc->lvRefCntWtd;
}
else
{
// Non-candidate local ref or non-lcl tree node.
// These are considered to have two references in the basic block:
// a def and a use and hence weighted ref count is 2 times
// the basic block weight in which they appear.
weight = 2 * this->blockInfo[refPos->bbNum].weight;
}
}
else
{
// Non-tree node ref positions. These will have a single
// reference in the basic block and hence their weighted
// refcount is equal to the block weight in which they
// appear.
weight = this->blockInfo[refPos->bbNum].weight;
}
return weight;
}
// allRegs represents a set of registers that can
// be used to allocate the specified type in any point
// in time (more of a 'bank' of registers).
regMaskTP LinearScan::allRegs(RegisterType rt)
{
if (rt == TYP_FLOAT)
{
return availableFloatRegs;
}
else if (rt == TYP_DOUBLE)
{
return availableDoubleRegs;
#ifdef FEATURE_SIMD
// TODO-Cleanup: Add an RBM_ALLSIMD
}
else if (varTypeIsSIMD(rt))
{
return availableDoubleRegs;
#endif // FEATURE_SIMD
}
else
{
return availableIntRegs;
}
}
//--------------------------------------------------------------------------
// allMultiRegCallNodeRegs: represents a set of registers that can be used
// to allocate a multi-reg call node.
//
// Arguments:
// call - Multi-reg call node
//
// Return Value:
// Mask representing the set of available registers for multi-reg call
// node.
//
// Note:
// Multi-reg call node available regs = Bitwise-OR(allregs(GetReturnRegType(i)))
// for all i=0..RetRegCount-1.
regMaskTP LinearScan::allMultiRegCallNodeRegs(GenTreeCall* call)
{
assert(call->HasMultiRegRetVal());
ReturnTypeDesc* retTypeDesc = call->GetReturnTypeDesc();
regMaskTP resultMask = allRegs(retTypeDesc->GetReturnRegType(0));
unsigned count = retTypeDesc->GetReturnRegCount();
for (unsigned i = 1; i < count; ++i)
{
resultMask |= allRegs(retTypeDesc->GetReturnRegType(i));
}
return resultMask;
}
//--------------------------------------------------------------------------
// allRegs: returns the set of registers that can accomodate the type of
// given node.
//
// Arguments:
// tree - GenTree node
//
// Return Value:
// Mask representing the set of available registers for given tree
//
// Note: In case of multi-reg call node, the full set of registers must be
// determined by looking at types of individual return register types.
// In this case, the registers may include registers from different register
// sets and will not be limited to the actual ABI return registers.
regMaskTP LinearScan::allRegs(GenTree* tree)
{
regMaskTP resultMask;
// In case of multi-reg calls, allRegs is defined as
// Bitwise-Or(allRegs(GetReturnRegType(i)) for i=0..ReturnRegCount-1
if (tree->IsMultiRegCall())
{
resultMask = allMultiRegCallNodeRegs(tree->AsCall());
}
else
{
resultMask = allRegs(tree->TypeGet());
}
return resultMask;
}
regMaskTP LinearScan::allSIMDRegs()
{
return availableFloatRegs;
}
//------------------------------------------------------------------------
// internalFloatRegCandidates: Return the set of registers that are appropriate
// for use as internal float registers.
//
// Return Value:
// The set of registers (as a regMaskTP).
//
// Notes:
// compFloatingPointUsed is only required to be set if it is possible that we
// will use floating point callee-save registers.
// It is unlikely, if an internal register is the only use of floating point,
// that it will select a callee-save register. But to be safe, we restrict
// the set of candidates if compFloatingPointUsed is not already set.
regMaskTP LinearScan::internalFloatRegCandidates()
{
if (compiler->compFloatingPointUsed)
{
return allRegs(TYP_FLOAT);
}
else
{
return RBM_FLT_CALLEE_TRASH;
}
}
/*****************************************************************************
* Register types
*****************************************************************************/
template <class T>
RegisterType regType(T type)
{
#ifdef FEATURE_SIMD
if (varTypeIsSIMD(type))
{
return FloatRegisterType;
}
#endif // FEATURE_SIMD
return varTypeIsFloating(TypeGet(type)) ? FloatRegisterType : IntRegisterType;
}
bool useFloatReg(var_types type)
{
return (regType(type) == FloatRegisterType);
}
bool registerTypesEquivalent(RegisterType a, RegisterType b)
{
return varTypeIsIntegralOrI(a) == varTypeIsIntegralOrI(b);
}
bool isSingleRegister(regMaskTP regMask)
{
return (regMask != RBM_NONE && genMaxOneBit(regMask));
}
/*****************************************************************************
* Inline functions for RegRecord
*****************************************************************************/
bool RegRecord::isFree()
{
return ((assignedInterval == nullptr || !assignedInterval->isActive) && !isBusyUntilNextKill);
}
/*****************************************************************************
* Inline functions for LinearScan
*****************************************************************************/
RegRecord* LinearScan::getRegisterRecord(regNumber regNum)
{
return &physRegs[regNum];
}
#ifdef DEBUG
//----------------------------------------------------------------------------
// getConstrainedRegMask: Returns new regMask which is the intersection of
// regMaskActual and regMaskConstraint if the new regMask has at least
// minRegCount registers, otherwise returns regMaskActual.
//
// Arguments:
// regMaskActual - regMask that needs to be constrained
// regMaskConstraint - regMask constraint that needs to be
// applied to regMaskActual
// minRegCount - Minimum number of regs that should be
// be present in new regMask.
//
// Return Value:
// New regMask that has minRegCount registers after instersection.
// Otherwise returns regMaskActual.
regMaskTP LinearScan::getConstrainedRegMask(regMaskTP regMaskActual, regMaskTP regMaskConstraint, unsigned minRegCount)
{
regMaskTP newMask = regMaskActual & regMaskConstraint;
if (genCountBits(newMask) >= minRegCount)
{
return newMask;
}
return regMaskActual;
}
//------------------------------------------------------------------------
// stressLimitRegs: Given a set of registers, expressed as a register mask, reduce
// them based on the current stress options.
//
// Arguments:
// mask - The current mask of register candidates for a node
//
// Return Value:
// A possibly-modified mask, based on the value of COMPlus_JitStressRegs.
//
// Notes:
// This is the method used to implement the stress options that limit
// the set of registers considered for allocation.
regMaskTP LinearScan::stressLimitRegs(RefPosition* refPosition, regMaskTP mask)
{
if (getStressLimitRegs() != LSRA_LIMIT_NONE)
{
// The refPosition could be null, for example when called
// by getTempRegForResolution().
int minRegCount = (refPosition != nullptr) ? refPosition->minRegCandidateCount : 1;
switch (getStressLimitRegs())
{
case LSRA_LIMIT_CALLEE:
if (!compiler->opts.compDbgEnC)
{
mask = getConstrainedRegMask(mask, RBM_CALLEE_SAVED, minRegCount);
}
break;
case LSRA_LIMIT_CALLER:
{
mask = getConstrainedRegMask(mask, RBM_CALLEE_TRASH, minRegCount);
}
break;
case LSRA_LIMIT_SMALL_SET:
if ((mask & LsraLimitSmallIntSet) != RBM_NONE)
{
mask = getConstrainedRegMask(mask, LsraLimitSmallIntSet, minRegCount);
}
else if ((mask & LsraLimitSmallFPSet) != RBM_NONE)
{
mask = getConstrainedRegMask(mask, LsraLimitSmallFPSet, minRegCount);
}
break;
default:
unreached();
}
if (refPosition != nullptr && refPosition->isFixedRegRef)
{
mask |= refPosition->registerAssignment;
}
}
return mask;
}
#endif // DEBUG
// TODO-Cleanup: Consider adding an overload that takes a varDsc, and can appropriately
// set such fields as isStructField
Interval* LinearScan::newInterval(RegisterType theRegisterType)
{
intervals.emplace_back(theRegisterType, allRegs(theRegisterType));
Interval* newInt = &intervals.back();
#ifdef DEBUG
newInt->intervalIndex = static_cast<unsigned>(intervals.size() - 1);
#endif // DEBUG
DBEXEC(VERBOSE, newInt->dump());
return newInt;
}
RefPosition* LinearScan::newRefPositionRaw(LsraLocation nodeLocation, GenTree* treeNode, RefType refType)
{
refPositions.emplace_back(curBBNum, nodeLocation, treeNode, refType);
RefPosition* newRP = &refPositions.back();
#ifdef DEBUG
newRP->rpNum = static_cast<unsigned>(refPositions.size() - 1);
#endif // DEBUG
return newRP;
}
//------------------------------------------------------------------------
// resolveConflictingDefAndUse: Resolve the situation where we have conflicting def and use
// register requirements on a single-def, single-use interval.
//
// Arguments:
// defRefPosition - The interval definition
// useRefPosition - The (sole) interval use
//
// Return Value:
// None.
//
// Assumptions:
// The two RefPositions are for the same interval, which is a tree-temp.
//
// Notes:
// We require some special handling for the case where the use is a "delayRegFree" case of a fixedReg.
// In that case, if we change the registerAssignment on the useRefPosition, we will lose the fact that,
// even if we assign a different register (and rely on codegen to do the copy), that fixedReg also needs
// to remain busy until the Def register has been allocated. In that case, we don't allow Case 1 or Case 4
// below.
// Here are the cases we consider (in this order):
// 1. If The defRefPosition specifies a single register, and there are no conflicting
// FixedReg uses of it between the def and use, we use that register, and the code generator
// will insert the copy. Note that it cannot be in use because there is a FixedRegRef for the def.
// 2. If the useRefPosition specifies a single register, and it is not in use, and there are no
// conflicting FixedReg uses of it between the def and use, we use that register, and the code generator
// will insert the copy.
// 3. If the defRefPosition specifies a single register (but there are conflicts, as determined
// in 1.), and there are no conflicts with the useRefPosition register (if it's a single register),
/// we set the register requirements on the defRefPosition to the use registers, and the
// code generator will insert a copy on the def. We can't rely on the code generator to put a copy
// on the use if it has multiple possible candidates, as it won't know which one has been allocated.
// 4. If the useRefPosition specifies a single register, and there are no conflicts with the register
// on the defRefPosition, we leave the register requirements on the defRefPosition as-is, and set
// the useRefPosition to the def registers, for similar reasons to case #3.
// 5. If both the defRefPosition and the useRefPosition specify single registers, but both have conflicts,
// We set the candiates on defRefPosition to be all regs of the appropriate type, and since they are
// single registers, codegen can insert the copy.
// 6. Finally, if the RefPositions specify disjoint subsets of the registers (or the use is fixed but
// has a conflict), we must insert a copy. The copy will be inserted before the use if the
// use is not fixed (in the fixed case, the code generator will insert the use).
//
// TODO-CQ: We get bad register allocation in case #3 in the situation where no register is
// available for the lifetime. We end up allocating a register that must be spilled, and it probably
// won't be the register that is actually defined by the target instruction. So, we have to copy it
// and THEN spill it. In this case, we should be using the def requirement. But we need to change
// the interface to this method a bit to make that work (e.g. returning a candidate set to use, but
// leaving the registerAssignment as-is on the def, so that if we find that we need to spill anyway
// we can use the fixed-reg on the def.
//
void LinearScan::resolveConflictingDefAndUse(Interval* interval, RefPosition* defRefPosition)
{
assert(!interval->isLocalVar);
RefPosition* useRefPosition = defRefPosition->nextRefPosition;
regMaskTP defRegAssignment = defRefPosition->registerAssignment;
regMaskTP useRegAssignment = useRefPosition->registerAssignment;
RegRecord* defRegRecord = nullptr;
RegRecord* useRegRecord = nullptr;
regNumber defReg = REG_NA;
regNumber useReg = REG_NA;
bool defRegConflict = false;
bool useRegConflict = false;
// If the useRefPosition is a "delayRegFree", we can't change the registerAssignment
// on it, or we will fail to ensure that the fixedReg is busy at the time the target
// (of the node that uses this interval) is allocated.
bool canChangeUseAssignment = !useRefPosition->isFixedRegRef || !useRefPosition->delayRegFree;
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CONFLICT));
if (!canChangeUseAssignment)
{
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_FIXED_DELAY_USE));
}
if (defRefPosition->isFixedRegRef)
{
defReg = defRefPosition->assignedReg();
defRegRecord = getRegisterRecord(defReg);
if (canChangeUseAssignment)
{
RefPosition* currFixedRegRefPosition = defRegRecord->recentRefPosition;
assert(currFixedRegRefPosition != nullptr &&
currFixedRegRefPosition->nodeLocation == defRefPosition->nodeLocation);
if (currFixedRegRefPosition->nextRefPosition == nullptr ||
currFixedRegRefPosition->nextRefPosition->nodeLocation > useRefPosition->getRefEndLocation())
{
// This is case #1. Use the defRegAssignment
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE1));
useRefPosition->registerAssignment = defRegAssignment;
return;
}
else
{
defRegConflict = true;
}
}
}
if (useRefPosition->isFixedRegRef)
{
useReg = useRefPosition->assignedReg();
useRegRecord = getRegisterRecord(useReg);
RefPosition* currFixedRegRefPosition = useRegRecord->recentRefPosition;
// We know that useRefPosition is a fixed use, so the nextRefPosition must not be null.
RefPosition* nextFixedRegRefPosition = useRegRecord->getNextRefPosition();
assert(nextFixedRegRefPosition != nullptr &&
nextFixedRegRefPosition->nodeLocation <= useRefPosition->nodeLocation);
// First, check to see if there are any conflicting FixedReg references between the def and use.
if (nextFixedRegRefPosition->nodeLocation == useRefPosition->nodeLocation)
{
// OK, no conflicting FixedReg references.
// Now, check to see whether it is currently in use.
if (useRegRecord->assignedInterval != nullptr)
{
RefPosition* possiblyConflictingRef = useRegRecord->assignedInterval->recentRefPosition;
LsraLocation possiblyConflictingRefLocation = possiblyConflictingRef->getRefEndLocation();
if (possiblyConflictingRefLocation >= defRefPosition->nodeLocation)
{
useRegConflict = true;
}
}
if (!useRegConflict)
{
// This is case #2. Use the useRegAssignment
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE2));
defRefPosition->registerAssignment = useRegAssignment;
return;
}
}
else
{
useRegConflict = true;
}
}
if (defRegRecord != nullptr && !useRegConflict)
{
// This is case #3.
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE3));
defRefPosition->registerAssignment = useRegAssignment;
return;
}
if (useRegRecord != nullptr && !defRegConflict && canChangeUseAssignment)
{
// This is case #4.
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE4));
useRefPosition->registerAssignment = defRegAssignment;
return;
}
if (defRegRecord != nullptr && useRegRecord != nullptr)
{
// This is case #5.
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE5));
RegisterType regType = interval->registerType;
assert((getRegisterType(interval, defRefPosition) == regType) &&
(getRegisterType(interval, useRefPosition) == regType));
regMaskTP candidates = allRegs(regType);
defRefPosition->registerAssignment = candidates;
return;
}
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_DEFUSE_CASE6));
return;
}
//------------------------------------------------------------------------
// conflictingFixedRegReference: Determine whether the current RegRecord has a
// fixed register use that conflicts with 'refPosition'
//
// Arguments:
// refPosition - The RefPosition of interest
//
// Return Value:
// Returns true iff the given RefPosition is NOT a fixed use of this register,
// AND either:
// - there is a RefPosition on this RegRecord at the nodeLocation of the given RefPosition, or
// - the given RefPosition has a delayRegFree, and there is a RefPosition on this RegRecord at
// the nodeLocation just past the given RefPosition.
//
// Assumptions:
// 'refPosition is non-null.
bool RegRecord::conflictingFixedRegReference(RefPosition* refPosition)
{
// Is this a fixed reference of this register? If so, there is no conflict.
if (refPosition->isFixedRefOfRegMask(genRegMask(regNum)))
{
return false;
}
// Otherwise, check for conflicts.
// There is a conflict if:
// 1. There is a recent RefPosition on this RegRecord that is at this location,
// except in the case where it is a special "putarg" that is associated with this interval, OR
// 2. There is an upcoming RefPosition at this location, or at the next location
// if refPosition is a delayed use (i.e. must be kept live through the next/def location).
LsraLocation refLocation = refPosition->nodeLocation;
if (recentRefPosition != nullptr && recentRefPosition->refType != RefTypeKill &&
recentRefPosition->nodeLocation == refLocation &&
(!isBusyUntilNextKill || assignedInterval != refPosition->getInterval()))
{
return true;
}
LsraLocation nextPhysRefLocation = getNextRefLocation();
if (nextPhysRefLocation == refLocation || (refPosition->delayRegFree && nextPhysRefLocation == (refLocation + 1)))
{
return true;
}
return false;
}
void LinearScan::applyCalleeSaveHeuristics(RefPosition* rp)
{
#ifdef _TARGET_AMD64_
if (compiler->opts.compDbgEnC)
{
// We only use RSI and RDI for EnC code, so we don't want to favor callee-save regs.
return;
}
#endif // _TARGET_AMD64_
Interval* theInterval = rp->getInterval();
#ifdef DEBUG
regMaskTP calleeSaveMask = calleeSaveRegs(getRegisterType(theInterval, rp));
if (doReverseCallerCallee())
{
rp->registerAssignment =
getConstrainedRegMask(rp->registerAssignment, calleeSaveMask, rp->minRegCandidateCount);
}
else
#endif // DEBUG
{
// Set preferences so that this register set will be preferred for earlier refs
theInterval->updateRegisterPreferences(rp->registerAssignment);
}
}
void LinearScan::associateRefPosWithInterval(RefPosition* rp)
{
Referenceable* theReferent = rp->referent;
if (theReferent != nullptr)
{
// All RefPositions except the dummy ones at the beginning of blocks
if (rp->isIntervalRef())
{
Interval* theInterval = rp->getInterval();
applyCalleeSaveHeuristics(rp);
if (theInterval->isLocalVar)
{
if (RefTypeIsUse(rp->refType))
{
RefPosition* const prevRP = theInterval->recentRefPosition;
if ((prevRP != nullptr) && (prevRP->bbNum == rp->bbNum))
{
prevRP->lastUse = false;
}
}
rp->lastUse = (rp->refType != RefTypeExpUse) && (rp->refType != RefTypeParamDef) &&
(rp->refType != RefTypeZeroInit) && !extendLifetimes();
}
else if (rp->refType == RefTypeUse)
{
// Ensure that we have consistent def/use on SDSU temps.
// However, there are a couple of cases where this may over-constrain allocation:
// 1. In the case of a non-commutative rmw def (in which the rmw source must be delay-free), or
// 2. In the case where the defining node requires a temp distinct from the target (also a
// delay-free case).
// In those cases, if we propagate a single-register restriction from the consumer to the producer
// the delayed uses will not see a fixed reference in the PhysReg at that position, and may
// incorrectly allocate that register.
// TODO-CQ: This means that we may often require a copy at the use of this node's result.
// This case could be moved to BuildRefPositionsForNode, at the point where the def RefPosition is
// created, causing a RefTypeFixedRef to be added at that location. This, however, results in
// more PhysReg RefPositions (a throughput impact), and a large number of diffs that require
// further analysis to determine benefit.
// See Issue #11274.
RefPosition* prevRefPosition = theInterval->recentRefPosition;
assert(prevRefPosition != nullptr && theInterval->firstRefPosition == prevRefPosition);
// All defs must have a valid treeNode, but we check it below to be conservative.
assert(prevRefPosition->treeNode != nullptr);
regMaskTP prevAssignment = prevRefPosition->registerAssignment;
regMaskTP newAssignment = (prevAssignment & rp->registerAssignment);
if (newAssignment != RBM_NONE)
{
if (!isSingleRegister(newAssignment) ||
(!theInterval->hasNonCommutativeRMWDef && (prevRefPosition->treeNode != nullptr) &&
!prevRefPosition->treeNode->gtLsraInfo.isInternalRegDelayFree))
{
prevRefPosition->registerAssignment = newAssignment;
}
}
else
{
theInterval->hasConflictingDefUse = true;
}
rp->lastUse = true;
}
}
RefPosition* prevRP = theReferent->recentRefPosition;
if (prevRP != nullptr)
{
prevRP->nextRefPosition = rp;
}
else
{
theReferent->firstRefPosition = rp;
}
theReferent->recentRefPosition = rp;
theReferent->lastRefPosition = rp;
}
else
{
assert((rp->refType == RefTypeBB) || (rp->refType == RefTypeKillGCRefs));
}
}
//---------------------------------------------------------------------------
// newRefPosition: allocate and initialize a new RefPosition.
//
// Arguments:
// reg - reg number that identifies RegRecord to be associated
// with this RefPosition
// theLocation - LSRA location of RefPosition
// theRefType - RefPosition type
// theTreeNode - GenTree node for which this RefPosition is created
// mask - Set of valid registers for this RefPosition
// multiRegIdx - register position if this RefPosition corresponds to a
// multi-reg call node.
//
// Return Value:
// a new RefPosition
//
RefPosition* LinearScan::newRefPosition(
regNumber reg, LsraLocation theLocation, RefType theRefType, GenTree* theTreeNode, regMaskTP mask)
{
RefPosition* newRP = newRefPositionRaw(theLocation, theTreeNode, theRefType);
newRP->setReg(getRegisterRecord(reg));
newRP->registerAssignment = mask;
newRP->setMultiRegIdx(0);
newRP->setAllocateIfProfitable(false);
associateRefPosWithInterval(newRP);
DBEXEC(VERBOSE, newRP->dump());
return newRP;
}
//---------------------------------------------------------------------------
// newRefPosition: allocate and initialize a new RefPosition.
//
// Arguments:
// theInterval - interval to which RefPosition is associated with.
// theLocation - LSRA location of RefPosition
// theRefType - RefPosition type
// theTreeNode - GenTree node for which this RefPosition is created
// mask - Set of valid registers for this RefPosition
// multiRegIdx - register position if this RefPosition corresponds to a
// multi-reg call node.
// minRegCount - Minimum number registers that needs to be ensured while
// constraining candidates for this ref position under
// LSRA stress. This is a DEBUG only arg.
//
// Return Value:
// a new RefPosition
//
RefPosition* LinearScan::newRefPosition(Interval* theInterval,
LsraLocation theLocation,
RefType theRefType,
GenTree* theTreeNode,
regMaskTP mask,
unsigned multiRegIdx /* = 0 */
DEBUGARG(unsigned minRegCandidateCount /* = 1 */))
{
#ifdef DEBUG
if (theInterval != nullptr && regType(theInterval->registerType) == FloatRegisterType)
{
// In the case we're using floating point registers we must make sure
// this flag was set previously in the compiler since this will mandate
// whether LSRA will take into consideration FP reg killsets.
assert(compiler->compFloatingPointUsed || ((mask & RBM_FLT_CALLEE_SAVED) == 0));
}
#endif // DEBUG
// If this reference is constrained to a single register (and it's not a dummy
// or Kill reftype already), add a RefTypeFixedReg at this location so that its
// availability can be more accurately determined
bool isFixedRegister = isSingleRegister(mask);
bool insertFixedRef = false;
if (isFixedRegister)
{
// Insert a RefTypeFixedReg for any normal def or use (not ParamDef or BB)
if (theRefType == RefTypeUse || theRefType == RefTypeDef)
{
insertFixedRef = true;
}
}
if (insertFixedRef)
{
regNumber physicalReg = genRegNumFromMask(mask);
RefPosition* pos = newRefPosition(physicalReg, theLocation, RefTypeFixedReg, nullptr, mask);
assert(theInterval != nullptr);
assert((allRegs(theInterval->registerType) & mask) != 0);
}
RefPosition* newRP = newRefPositionRaw(theLocation, theTreeNode, theRefType);
newRP->setInterval(theInterval);
// Spill info
newRP->isFixedRegRef = isFixedRegister;
#ifndef _TARGET_AMD64_
// We don't need this for AMD because the PInvoke method epilog code is explicit
// at register allocation time.
if (theInterval != nullptr && theInterval->isLocalVar && compiler->info.compCallUnmanaged &&
theInterval->varNum == compiler->genReturnLocal)
{
mask &= ~(RBM_PINVOKE_TCB | RBM_PINVOKE_FRAME);
noway_assert(mask != RBM_NONE);
}
#endif // !_TARGET_AMD64_
newRP->registerAssignment = mask;
newRP->setMultiRegIdx(multiRegIdx);
newRP->setAllocateIfProfitable(false);
#ifdef DEBUG
newRP->minRegCandidateCount = minRegCandidateCount;
#endif // DEBUG
associateRefPosWithInterval(newRP);
DBEXEC(VERBOSE, newRP->dump());
return newRP;
}
/*****************************************************************************
* Inline functions for Interval
*****************************************************************************/
RefPosition* Referenceable::getNextRefPosition()
{
if (recentRefPosition == nullptr)
{
return firstRefPosition;
}
else
{
return recentRefPosition->nextRefPosition;
}
}
LsraLocation Referenceable::getNextRefLocation()
{
RefPosition* nextRefPosition = getNextRefPosition();
if (nextRefPosition == nullptr)
{
return MaxLocation;
}
else
{
return nextRefPosition->nodeLocation;
}
}
// Iterate through all the registers of the given type
class RegisterIterator
{
friend class Registers;
public:
RegisterIterator(RegisterType type) : regType(type)
{
if (useFloatReg(regType))
{
currentRegNum = REG_FP_FIRST;
}
else
{
currentRegNum = REG_INT_FIRST;
}
}
protected:
static RegisterIterator Begin(RegisterType regType)
{
return RegisterIterator(regType);
}
static RegisterIterator End(RegisterType regType)
{
RegisterIterator endIter = RegisterIterator(regType);
// This assumes only integer and floating point register types
// if we target a processor with additional register types,
// this would have to change
if (useFloatReg(regType))
{
// This just happens to work for both double & float
endIter.currentRegNum = REG_NEXT(REG_FP_LAST);
}
else