-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathcodegencommon.cpp
8396 lines (7243 loc) · 289 KB
/
codegencommon.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.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Code Generator Common: XX
XX Methods common to all architectures and register allocation strategies XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
// TODO-Cleanup: There are additional methods in CodeGen*.cpp that are almost
// identical, and which should probably be moved here.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "codegen.h"
#include "gcinfo.h"
#include "emit.h"
#ifndef JIT32_GCENCODER
#include "gcinfoencoder.h"
#endif
#include "patchpointinfo.h"
#include "optcse.h" // for cse metrics
#include "jitstd/algorithm.h"
/*****************************************************************************/
void CodeGenInterface::setFramePointerRequiredEH(bool value)
{
m_cgFramePointerRequired = value;
#ifndef JIT32_GCENCODER
if (value)
{
// EnumGcRefs will only enumerate slots in aborted frames
// if they are fully-interruptible. So if we have a catch
// or finally that will keep frame-vars alive, we need to
// force fully-interruptible.
#ifdef DEBUG
if (verbose)
{
printf("Method has EH, marking method as fully interruptible\n");
}
#endif
m_cgInterruptible = true;
}
#endif // JIT32_GCENCODER
}
/*****************************************************************************/
CodeGenInterface* getCodeGenerator(Compiler* comp)
{
return new (comp, CMK_Codegen) CodeGen(comp);
}
NodeInternalRegisters::NodeInternalRegisters(Compiler* comp)
: m_table(comp->getAllocator(CMK_LSRA))
{
}
//------------------------------------------------------------------------
// Add: Add internal allocated registers for the specified node.
//
// Parameters:
// tree - IR node to add internal allocated registers to
// regs - Registers to add
//
void NodeInternalRegisters::Add(GenTree* tree, regMaskTP regs)
{
assert(regs != RBM_NONE);
regMaskTP* result = m_table.LookupPointerOrAdd(tree, RBM_NONE);
*result |= regs;
}
//------------------------------------------------------------------------
// Extract: Find the lowest number temporary register from the gtRsvdRegs set
// that is also in the optional given mask (typically, RBM_ALLINT or
// RBM_ALLFLOAT), and return it. Remove this register from the temporary
// register set, so it won't be returned again.
//
// Parameters:
// tree - IR node whose internal registers to extract
// mask - Mask of allowed registers that can be returned
//
// Returns:
// Register number.
//
regNumber NodeInternalRegisters::Extract(GenTree* tree, regMaskTP mask)
{
regMaskTP* regs = m_table.LookupPointer(tree);
assert(regs != nullptr);
regMaskTP availableSet = *regs & mask;
assert(availableSet != RBM_NONE);
regNumber result = genFirstRegNumFromMask(availableSet);
*regs ^= genRegMask(result);
return result;
}
//------------------------------------------------------------------------
// GetSingle: There is expected to be exactly one available temporary register
// in the given mask in the internal register set. Get that register. No future calls to get
// a temporary register are expected. Removes the register from the set, but only in
// DEBUG to avoid doing unnecessary work in non-DEBUG builds.
//
// Parameters:
// tree - IR node whose internal registers to extract
// mask - Mask of allowed registers that can be returned
//
// Returns:
// Register number.
//
regNumber NodeInternalRegisters::GetSingle(GenTree* tree, regMaskTP mask)
{
regMaskTP* regs = m_table.LookupPointer(tree);
assert(regs != nullptr);
regMaskTP availableSet = *regs & mask;
assert(genExactlyOneBit(availableSet));
regNumber result = genFirstRegNumFromMask(availableSet);
INDEBUG(*regs &= ~genRegMask(result));
return result;
}
//------------------------------------------------------------------------
// GetAll: Get all internal registers for the specified IR node.
//
// Parameters:
// tree - IR node whose internal registers to query
//
// Returns:
// Mask of registers.
//
regMaskTP NodeInternalRegisters::GetAll(GenTree* tree)
{
regMaskTP regs;
return m_table.Lookup(tree, ®s) ? regs : RBM_NONE;
}
//------------------------------------------------------------------------
// Count: return the number of available temporary registers in the (optional)
// given set (typically, RBM_ALLINT or RBM_ALLFLOAT).
//
// Parameters:
// tree - IR node whose internal registers to query
// mask - Mask of registers to count
//
// Returns:
// Count of nodes
//
unsigned NodeInternalRegisters::Count(GenTree* tree, regMaskTP mask)
{
regMaskTP regs;
return m_table.Lookup(tree, ®s) ? genCountBits(regs & mask) : 0;
}
// CodeGen constructor
CodeGenInterface::CodeGenInterface(Compiler* theCompiler)
: gcInfo(theCompiler)
, regSet(theCompiler, gcInfo)
, internalRegisters(theCompiler)
, compiler(theCompiler)
, treeLifeUpdater(nullptr)
{
}
#if defined(TARGET_XARCH)
void CodeGenInterface::CopyRegisterInfo()
{
#if defined(TARGET_AMD64)
rbmAllFloat = compiler->rbmAllFloat;
rbmFltCalleeTrash = compiler->rbmFltCalleeTrash;
rbmAllInt = compiler->rbmAllInt;
rbmIntCalleeTrash = compiler->rbmIntCalleeTrash;
regIntLast = compiler->regIntLast;
#endif // TARGET_AMD64
rbmAllMask = compiler->rbmAllMask;
rbmMskCalleeTrash = compiler->rbmMskCalleeTrash;
}
#endif // TARGET_XARCH
/*****************************************************************************/
CodeGen::CodeGen(Compiler* theCompiler)
: CodeGenInterface(theCompiler)
{
#if !defined(TARGET_X86)
m_stkArgVarNum = BAD_VAR_NUM;
#endif
#if defined(UNIX_X86_ABI)
curNestedAlignment = 0;
maxNestedAlignment = 0;
#endif
gcInfo.regSet = ®Set;
m_cgEmitter = new (compiler->getAllocator()) emitter();
m_cgEmitter->codeGen = this;
m_cgEmitter->gcInfo = &gcInfo;
#ifdef DEBUG
setVerbose(compiler->verbose);
#endif // DEBUG
regSet.tmpInit();
#ifdef LATE_DISASM
getDisAssembler().disInit(compiler);
#endif
#ifdef DEBUG
genTrnslLocalVarCount = 0;
// Shouldn't be used before it is set in genFnProlog()
compiler->compCalleeRegsPushed = UninitializedWord<unsigned>(compiler);
#if defined(TARGET_XARCH)
// Shouldn't be used before it is set in genFnProlog()
compiler->compCalleeFPRegsSavedMask = (regMaskTP)-1;
#endif // defined(TARGET_XARCH)
#endif // DEBUG
#ifdef TARGET_AMD64
// This will be set before final frame layout.
compiler->compVSQuirkStackPaddingNeeded = 0;
#endif // TARGET_AMD64
compiler->genCallSite2DebugInfoMap = nullptr;
/* Assume that we not fully interruptible */
SetInterruptible(false);
#if defined(TARGET_ARMARCH) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
SetHasTailCalls(false);
#endif // TARGET_ARMARCH || TARGET_LOONGARCH64 || TARGET_RISCV64
#ifdef DEBUG
genInterruptibleUsed = false;
genCurDispOffset = (unsigned)-1;
#endif
#ifdef TARGET_ARM64
genSaveFpLrWithAllCalleeSavedRegisters = false;
genForceFuncletFrameType5 = false;
genReverseAndPairCalleeSavedRegisters = false;
#endif // TARGET_ARM64
}
#if defined(TARGET_X86) || defined(TARGET_ARM)
//---------------------------------------------------------------------
// genTotalFrameSize - return the "total" size of the stack frame, including local size
// and callee-saved register size. There are a few things "missing" depending on the
// platform. The function genCallerSPtoInitialSPdelta() includes those things.
//
// For ARM, this doesn't include the prespilled registers.
//
// For x86, this doesn't include the frame pointer if codeGen->isFramePointerUsed() is true.
// It also doesn't include the pushed return address.
//
// Return value:
// Frame size
int CodeGenInterface::genTotalFrameSize() const
{
assert(!IsUninitialized(compiler->compCalleeRegsPushed));
int totalFrameSize = compiler->compCalleeRegsPushed * REGSIZE_BYTES + compiler->compLclFrameSize;
assert(totalFrameSize >= 0);
return totalFrameSize;
}
//---------------------------------------------------------------------
// genSPtoFPdelta - return the offset from SP to the frame pointer.
// This number is going to be positive, since SP must be at the lowest
// address.
//
// There must be a frame pointer to call this function!
int CodeGenInterface::genSPtoFPdelta() const
{
assert(isFramePointerUsed());
int delta;
delta = -genCallerSPtoInitialSPdelta() + genCallerSPtoFPdelta();
assert(delta >= 0);
return delta;
}
//---------------------------------------------------------------------
// genCallerSPtoFPdelta - return the offset from Caller-SP to the frame pointer.
// This number is going to be negative, since the Caller-SP is at a higher
// address than the frame pointer.
//
// There must be a frame pointer to call this function!
int CodeGenInterface::genCallerSPtoFPdelta() const
{
assert(isFramePointerUsed());
int callerSPtoFPdelta = 0;
#if defined(TARGET_ARM)
// On ARM, we first push the prespill registers, then store LR, then R11 (FP), and point R11 at the saved R11.
callerSPtoFPdelta -= genCountBits(regSet.rsMaskPreSpillRegs(true)) * REGSIZE_BYTES;
callerSPtoFPdelta -= 2 * REGSIZE_BYTES;
#elif defined(TARGET_X86)
// Thanks to ebp chaining, the difference between ebp-based addresses
// and caller-SP-relative addresses is just the 2 pointers:
// return address
// pushed ebp
callerSPtoFPdelta -= 2 * REGSIZE_BYTES;
#else
#error "Unknown TARGET"
#endif // TARGET*
assert(callerSPtoFPdelta <= 0);
return callerSPtoFPdelta;
}
//---------------------------------------------------------------------
// genCallerSPtoInitialSPdelta - return the offset from Caller-SP to Initial SP.
//
// This number will be negative.
int CodeGenInterface::genCallerSPtoInitialSPdelta() const
{
int callerSPtoSPdelta = 0;
#if defined(TARGET_ARM)
callerSPtoSPdelta -= genCountBits(regSet.rsMaskPreSpillRegs(true)) * REGSIZE_BYTES;
callerSPtoSPdelta -= genTotalFrameSize();
#elif defined(TARGET_X86)
callerSPtoSPdelta -= genTotalFrameSize();
callerSPtoSPdelta -= REGSIZE_BYTES; // caller-pushed return address
// compCalleeRegsPushed does not account for the frame pointer
// TODO-Cleanup: shouldn't this be part of genTotalFrameSize?
if (isFramePointerUsed())
{
callerSPtoSPdelta -= REGSIZE_BYTES;
}
#else
#error "Unknown TARGET"
#endif // TARGET*
assert(callerSPtoSPdelta <= 0);
return callerSPtoSPdelta;
}
#endif // defined(TARGET_X86) || defined(TARGET_ARM)
/*****************************************************************************
*
* Initialize some global variables.
*/
void CodeGen::genPrepForCompiler()
{
treeLifeUpdater = new (compiler, CMK_bitset) TreeLifeUpdater<true>(compiler);
/* Figure out which non-register variables hold pointers */
VarSetOps::AssignNoCopy(compiler, gcInfo.gcTrkStkPtrLcls, VarSetOps::MakeEmpty(compiler));
// Also, initialize gcTrkStkPtrLcls to include all tracked variables that do not fully live
// in a register (i.e. they live on the stack for all or part of their lifetime).
// Note that lvRegister indicates that a lclVar is in a register for its entire lifetime.
unsigned varNum;
LclVarDsc* varDsc;
for (varNum = 0, varDsc = compiler->lvaTable; varNum < compiler->lvaCount; varNum++, varDsc++)
{
if (varDsc->lvTracked || varDsc->lvIsRegCandidate())
{
if (!varDsc->lvRegister && compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::AddElemD(compiler, gcInfo.gcTrkStkPtrLcls, varDsc->lvVarIndex);
}
}
}
VarSetOps::AssignNoCopy(compiler, genLastLiveSet, VarSetOps::MakeEmpty(compiler));
genLastLiveMask = RBM_NONE;
compiler->Metrics.BasicBlocksAtCodegen = compiler->fgBBcount;
}
//------------------------------------------------------------------------
// genMarkLabelsForCodegen: Mark labels required for codegen.
//
// Mark all blocks that require a label with BBF_HAS_LABEL. These are either blocks that are:
// 1. the target of jumps (fall-through flow doesn't require a label),
// 2. referenced labels such as for "switch" codegen,
// 3. needed to denote the range of EH regions to the VM.
//
// No labels will be in the IR before now, but future codegen might annotate additional blocks
// with this flag, such as "switch" codegen, or codegen-created blocks from genCreateTempLabel().
//
// To report exception handling information to the VM, we need the size of the exception
// handling regions. To compute that, we need to emit labels for the beginning block of
// an EH region, and the block that immediately follows a region. Go through the EH
// table and mark all these blocks with BBF_HAS_LABEL to make this happen.
//
// This code is closely couple with genReportEH() in the sense that any block
// that this procedure has determined it needs to have a label has to be selected
// using the same logic both here and in genReportEH(), so basically any time there is
// a change in the way we handle EH reporting, we have to keep the logic of these two
// methods 'in sync'.
//
// No blocks should be added or removed after this.
//
void CodeGen::genMarkLabelsForCodegen()
{
assert(!compiler->fgSafeBasicBlockCreation);
JITDUMP("Mark labels for codegen\n");
#ifdef DEBUG
// No label flags should be set before this.
for (BasicBlock* const block : compiler->Blocks())
{
assert(!block->HasFlag(BBF_HAS_LABEL));
}
#endif // DEBUG
// The first block is special; it always needs a label. This is to properly set up GC info.
JITDUMP(" " FMT_BB " : first block\n", compiler->fgFirstBB->bbNum);
compiler->fgFirstBB->SetFlags(BBF_HAS_LABEL);
// The current implementation of switch tables requires the first block to have a label so it
// can generate offsets to the switch label targets.
// (This is duplicative with the fact we always set the first block with a label above.)
// TODO-CQ: remove this when switches have been re-implemented to not use this.
if (compiler->fgHasSwitch)
{
JITDUMP(" " FMT_BB " : function has switch; mark first block\n", compiler->fgFirstBB->bbNum);
compiler->fgFirstBB->SetFlags(BBF_HAS_LABEL);
}
for (BasicBlock* const block : compiler->Blocks())
{
switch (block->GetKind())
{
case BBJ_ALWAYS:
// If we can skip this jump, don't create a label for the target
if (block->CanRemoveJumpToNext(compiler))
{
break;
}
FALLTHROUGH;
case BBJ_EHCATCHRET:
JITDUMP(" " FMT_BB " : branch target\n", block->GetTarget()->bbNum);
block->GetTarget()->SetFlags(BBF_HAS_LABEL);
break;
case BBJ_COND:
JITDUMP(" " FMT_BB " : branch target\n", block->GetTrueTarget()->bbNum);
block->GetTrueTarget()->SetFlags(BBF_HAS_LABEL);
// If we need a jump to the false target, give it a label
if (!block->CanRemoveJumpToTarget(block->GetFalseTarget(), compiler))
{
JITDUMP(" " FMT_BB " : branch target\n", block->GetFalseTarget()->bbNum);
block->GetFalseTarget()->SetFlags(BBF_HAS_LABEL);
}
break;
case BBJ_SWITCH:
for (BasicBlock* const bTarget : block->SwitchTargets())
{
JITDUMP(" " FMT_BB " : switch target\n", bTarget->bbNum);
bTarget->SetFlags(BBF_HAS_LABEL);
}
break;
case BBJ_CALLFINALLY:
// The finally target itself will get marked by walking the EH table, below, and marking
// all handler begins.
if (compiler->UsesCallFinallyThunks())
{
// For callfinally thunks, we need to mark the block following the callfinally/callfinallyret pair,
// as that's needed for identifying the range of the "duplicate finally" region in EH data.
BasicBlock* bbToLabel = block->Next();
if (block->isBBCallFinallyPair())
{
bbToLabel = bbToLabel->Next(); // skip the BBJ_CALLFINALLYRET
}
if (bbToLabel != nullptr)
{
JITDUMP(" " FMT_BB " : callfinally thunk region end\n", bbToLabel->bbNum);
bbToLabel->SetFlags(BBF_HAS_LABEL);
}
}
break;
case BBJ_CALLFINALLYRET:
JITDUMP(" " FMT_BB " : finally continuation\n", block->GetFinallyContinuation()->bbNum);
block->GetFinallyContinuation()->SetFlags(BBF_HAS_LABEL);
break;
case BBJ_EHFINALLYRET:
case BBJ_EHFAULTRET:
case BBJ_EHFILTERRET: // The filter-handler will get marked when processing the EH handlers, below.
case BBJ_RETURN:
case BBJ_THROW:
break;
default:
noway_assert(!"Unexpected bbKind");
break;
}
}
// Walk all the exceptional code blocks and mark them, since they don't appear in the normal flow graph.
if (compiler->fgHasAddCodeDscMap())
{
for (Compiler::AddCodeDsc* const add : Compiler::AddCodeDscMap::ValueIteration(compiler->fgGetAddCodeDscMap()))
{
if (add->acdUsed)
{
JITDUMP(" " FMT_BB " : throw helper block\n", add->acdDstBlk->bbNum);
add->acdDstBlk->SetFlags(BBF_HAS_LABEL);
}
}
}
for (EHblkDsc* const HBtab : EHClauses(compiler))
{
HBtab->ebdTryBeg->SetFlags(BBF_HAS_LABEL);
HBtab->ebdHndBeg->SetFlags(BBF_HAS_LABEL);
JITDUMP(" " FMT_BB " : try begin\n", HBtab->ebdTryBeg->bbNum);
JITDUMP(" " FMT_BB " : hnd begin\n", HBtab->ebdHndBeg->bbNum);
if (!HBtab->ebdTryLast->IsLast())
{
HBtab->ebdTryLast->Next()->SetFlags(BBF_HAS_LABEL);
JITDUMP(" " FMT_BB " : try end\n", HBtab->ebdTryLast->Next()->bbNum);
}
if (!HBtab->ebdHndLast->IsLast())
{
HBtab->ebdHndLast->Next()->SetFlags(BBF_HAS_LABEL);
JITDUMP(" " FMT_BB " : hnd end\n", HBtab->ebdHndLast->Next()->bbNum);
}
if (HBtab->HasFilter())
{
HBtab->ebdFilter->SetFlags(BBF_HAS_LABEL);
JITDUMP(" " FMT_BB " : filter begin\n", HBtab->ebdFilter->bbNum);
}
}
#ifdef DEBUG
if (compiler->verbose)
{
printf("*************** After genMarkLabelsForCodegen()\n");
compiler->fgDispBasicBlocks();
}
#endif // DEBUG
}
void CodeGenInterface::genUpdateLife(GenTree* tree)
{
treeLifeUpdater->UpdateLife(tree);
}
void CodeGenInterface::genUpdateLife(VARSET_VALARG_TP newLife)
{
compiler->compUpdateLife</*ForCodeGen*/ true>(newLife);
}
// Return the register mask for the given register variable
// inline
regMaskTP CodeGenInterface::genGetRegMask(const LclVarDsc* varDsc)
{
regMaskTP regMask;
assert(varDsc->lvIsInReg());
regNumber reg = varDsc->GetRegNum();
if (genIsValidFloatReg(reg))
{
regMask = genRegMaskFloat(reg ARM_ARG(varDsc->GetRegisterType()));
}
else
{
regMask = genRegMask(reg);
}
return regMask;
}
// Return the register mask for the given lclVar or regVar tree node
// inline
regMaskTP CodeGenInterface::genGetRegMask(GenTree* tree)
{
assert(tree->gtOper == GT_LCL_VAR);
regMaskTP regMask = RBM_NONE;
const LclVarDsc* varDsc = compiler->lvaGetDesc(tree->AsLclVarCommon());
if (varDsc->lvPromoted)
{
for (unsigned i = varDsc->lvFieldLclStart; i < varDsc->lvFieldLclStart + varDsc->lvFieldCnt; ++i)
{
const LclVarDsc* fieldVarDsc = compiler->lvaGetDesc(i);
noway_assert(fieldVarDsc->lvIsStructField);
if (fieldVarDsc->lvIsInReg())
{
regMask |= genGetRegMask(fieldVarDsc);
}
}
}
else if (varDsc->lvIsInReg())
{
regMask = genGetRegMask(varDsc);
}
return regMask;
}
// The given lclVar is either going live (being born) or dying.
// It might be both going live and dying (that is, it is a dead store) under MinOpts.
// Update regSet.GetMaskVars() accordingly.
// inline
void CodeGenInterface::genUpdateRegLife(const LclVarDsc* varDsc, bool isBorn, bool isDying DEBUGARG(GenTree* tree))
{
regMaskTP regMask = genGetRegMask(varDsc);
#ifdef DEBUG
if (compiler->verbose)
{
printf("\t\t\t\t\t\t\tV%02u in reg ", compiler->lvaGetLclNum(varDsc));
varDsc->PrintVarReg();
printf(" is becoming %s ", (isDying) ? "dead" : "live");
Compiler::printTreeID(tree);
printf("\n");
}
#endif // DEBUG
if (isDying)
{
// We'd like to be able to assert the following, however if we are walking
// through a qmark/colon tree, we may encounter multiple last-use nodes.
// assert((regSet.GetMaskVars() & regMask) == regMask);
regSet.RemoveMaskVars(regMask);
}
else
{
// If this is going live, the register must not have a variable in it, except
// in the case of an exception or "spill at single-def" variable, which may be already treated
// as live in the register.
assert(varDsc->IsAlwaysAliveInMemory() || ((regSet.GetMaskVars() & regMask) == 0));
regSet.AddMaskVars(regMask);
}
}
//----------------------------------------------------------------------
// compHelperCallKillSet: Gets a register mask that represents the kill set for a helper call.
// Not all JIT Helper calls follow the standard ABI on the target architecture.
//
// Arguments:
// helper - The helper being inquired about
//
// Return Value:
// Mask of register kills -- registers whose values are no longer guaranteed to be the same.
//
regMaskTP Compiler::compHelperCallKillSet(CorInfoHelpFunc helper)
{
switch (helper)
{
// Most of the helpers are written in C++ and C# and we can't make
// any additional assumptions beyond the standard ABI. However, some are written in raw assembly,
// so we can narrow down the kill sets.
//
// TODO-CQ: Inspect all asm helpers and narrow down the kill sets for them.
//
case CORINFO_HELP_ASSIGN_REF:
case CORINFO_HELP_CHECKED_ASSIGN_REF:
return RBM_CALLEE_TRASH_WRITEBARRIER;
case CORINFO_HELP_ASSIGN_BYREF:
return RBM_CALLEE_TRASH_WRITEBARRIER_BYREF;
case CORINFO_HELP_PROF_FCN_ENTER:
return RBM_PROFILER_ENTER_TRASH;
case CORINFO_HELP_PROF_FCN_LEAVE:
return RBM_PROFILER_LEAVE_TRASH;
case CORINFO_HELP_PROF_FCN_TAILCALL:
return RBM_PROFILER_TAILCALL_TRASH;
#ifdef TARGET_X86
case CORINFO_HELP_ASSIGN_REF_EAX:
case CORINFO_HELP_ASSIGN_REF_ECX:
case CORINFO_HELP_ASSIGN_REF_EBX:
case CORINFO_HELP_ASSIGN_REF_EBP:
case CORINFO_HELP_ASSIGN_REF_ESI:
case CORINFO_HELP_ASSIGN_REF_EDI:
case CORINFO_HELP_CHECKED_ASSIGN_REF_EAX:
case CORINFO_HELP_CHECKED_ASSIGN_REF_ECX:
case CORINFO_HELP_CHECKED_ASSIGN_REF_EBX:
case CORINFO_HELP_CHECKED_ASSIGN_REF_EBP:
case CORINFO_HELP_CHECKED_ASSIGN_REF_ESI:
case CORINFO_HELP_CHECKED_ASSIGN_REF_EDI:
return RBM_EDX;
#endif
case CORINFO_HELP_STOP_FOR_GC:
return RBM_STOP_FOR_GC_TRASH;
case CORINFO_HELP_INIT_PINVOKE_FRAME:
return RBM_INIT_PINVOKE_FRAME_TRASH;
case CORINFO_HELP_VALIDATE_INDIRECT_CALL:
return RBM_VALIDATE_INDIRECT_CALL_TRASH;
default:
return RBM_CALLEE_TRASH;
}
}
//------------------------------------------------------------------------
// compChangeLife: Compare the given "newLife" with last set of live variables and update
// codeGen "gcInfo", siScopes, "regSet" with the new variable's homes/liveness.
//
// Arguments:
// newLife - the new set of variables that are alive.
//
// Assumptions:
// The set of live variables reflects the result of only emitted code, it should not be considering the becoming
// live/dead of instructions that has not been emitted yet. This is used to ensure [) "VariableLiveRange"
// intervals when calling "siStartVariableLiveRange" and "siEndVariableLiveRange".
//
// Notes:
// If "ForCodeGen" is false, only "compCurLife" set (and no mask) will be updated.
//
template <bool ForCodeGen>
void Compiler::compChangeLife(VARSET_VALARG_TP newLife)
{
#ifdef DEBUG
if (verbose)
{
printf("Change life %s ", VarSetOps::ToString(this, compCurLife));
dumpConvertedVarSet(this, compCurLife);
printf(" -> %s ", VarSetOps::ToString(this, newLife));
dumpConvertedVarSet(this, newLife);
printf("\n");
}
#endif // DEBUG
/* We should only be called when the live set has actually changed */
noway_assert(!VarSetOps::Equal(this, compCurLife, newLife));
if (!ForCodeGen)
{
VarSetOps::Assign(this, compCurLife, newLife);
return;
}
/* Figure out which variables are becoming live/dead at this point */
// deadSet = compCurLife - newLife
VARSET_TP deadSet(VarSetOps::Diff(this, compCurLife, newLife));
// bornSet = newLife - compCurLife
VARSET_TP bornSet(VarSetOps::Diff(this, newLife, compCurLife));
/* Can't simultaneously become live and dead at the same time */
// (deadSet UNION bornSet) != EMPTY
noway_assert(!VarSetOps::IsEmptyUnion(this, deadSet, bornSet));
// (deadSet INTERSECTION bornSet) == EMPTY
noway_assert(VarSetOps::IsEmptyIntersection(this, deadSet, bornSet));
VarSetOps::Assign(this, compCurLife, newLife);
// Handle the dying vars first, then the newly live vars.
// This is because, in the RyuJIT backend case, they may occupy registers that
// will be occupied by another var that is newly live.
VarSetOps::Iter deadIter(this, deadSet);
unsigned deadVarIndex = 0;
while (deadIter.NextElem(&deadVarIndex))
{
unsigned varNum = lvaTrackedIndexToLclNum(deadVarIndex);
LclVarDsc* varDsc = lvaGetDesc(varNum);
bool isGCRef = (varDsc->TypeGet() == TYP_REF);
bool isByRef = (varDsc->TypeGet() == TYP_BYREF);
bool isInReg = varDsc->lvIsInReg();
bool isInMemory = !isInReg || varDsc->IsAlwaysAliveInMemory();
if (isInReg)
{
// TODO-Cleanup: Move the code from compUpdateLifeVar to genUpdateRegLife that updates the
// gc sets
regMaskTP regMask = varDsc->lvRegMask();
if (isGCRef)
{
codeGen->gcInfo.gcRegGCrefSetCur &= ~regMask;
}
else if (isByRef)
{
codeGen->gcInfo.gcRegByrefSetCur &= ~regMask;
}
codeGen->genUpdateRegLife(varDsc, false /*isBorn*/, true /*isDying*/ DEBUGARG(nullptr));
}
// Update the gcVarPtrSetCur if it is in memory.
if (isInMemory && (isGCRef || isByRef))
{
VarSetOps::RemoveElemD(this, codeGen->gcInfo.gcVarPtrSetCur, deadVarIndex);
JITDUMP("\t\t\t\t\t\t\tV%02u becoming dead\n", varNum);
}
codeGen->getVariableLiveKeeper()->siEndVariableLiveRange(varNum);
}
VarSetOps::Iter bornIter(this, bornSet);
unsigned bornVarIndex = 0;
while (bornIter.NextElem(&bornVarIndex))
{
unsigned varNum = lvaTrackedIndexToLclNum(bornVarIndex);
LclVarDsc* varDsc = lvaGetDesc(varNum);
bool isGCRef = (varDsc->TypeGet() == TYP_REF);
bool isByRef = (varDsc->TypeGet() == TYP_BYREF);
if (varDsc->lvIsInReg())
{
// If this variable is going live in a register, it is no longer live on the stack,
// unless it is an EH/"spill at single-def" var, which always remains live on the stack.
if (!varDsc->IsAlwaysAliveInMemory())
{
#ifdef DEBUG
if (VarSetOps::IsMember(this, codeGen->gcInfo.gcVarPtrSetCur, bornVarIndex))
{
JITDUMP("\t\t\t\t\t\t\tRemoving V%02u from gcVarPtrSetCur\n", varNum);
}
#endif // DEBUG
VarSetOps::RemoveElemD(this, codeGen->gcInfo.gcVarPtrSetCur, bornVarIndex);
}
codeGen->genUpdateRegLife(varDsc, true /*isBorn*/, false /*isDying*/ DEBUGARG(nullptr));
regMaskTP regMask = varDsc->lvRegMask();
if (isGCRef)
{
codeGen->gcInfo.gcRegGCrefSetCur |= regMask;
}
else if (isByRef)
{
codeGen->gcInfo.gcRegByrefSetCur |= regMask;
}
}
else if (lvaIsGCTracked(varDsc))
{
// This isn't in a register, so update the gcVarPtrSetCur to show that it's live on the stack.
VarSetOps::AddElemD(this, codeGen->gcInfo.gcVarPtrSetCur, bornVarIndex);
JITDUMP("\t\t\t\t\t\t\tV%02u becoming live\n", varNum);
}
codeGen->getVariableLiveKeeper()->siStartVariableLiveRange(varDsc, varNum);
}
}
// Need an explicit instantiation.
template void Compiler::compChangeLife<true>(VARSET_VALARG_TP newLife);
/*****************************************************************************
*
* Generate a spill.
*/
void CodeGenInterface::spillReg(var_types type, TempDsc* tmp, regNumber reg)
{
GetEmitter()->emitIns_S_R(ins_Store(type), emitActualTypeSize(type), reg, tmp->tdTempNum(), 0);
}
/*****************************************************************************
*
* Generate a reload.
*/
void CodeGenInterface::reloadReg(var_types type, TempDsc* tmp, regNumber reg)
{
GetEmitter()->emitIns_R_S(ins_Load(type), emitActualTypeSize(type), reg, tmp->tdTempNum(), 0);
}
// inline
regNumber CodeGenInterface::genGetThisArgReg(GenTreeCall* call) const
{
return REG_ARG_0;
}
//----------------------------------------------------------------------
// getSpillTempDsc: get the TempDsc corresponding to a spilled tree.
//
// Arguments:
// tree - spilled GenTree node
//
// Return Value:
// TempDsc corresponding to tree
TempDsc* CodeGenInterface::getSpillTempDsc(GenTree* tree)
{
// tree must be in spilled state.
assert((tree->gtFlags & GTF_SPILLED) != 0);
// Get the tree's SpillDsc.
RegSet::SpillDsc* prevDsc;
RegSet::SpillDsc* spillDsc = regSet.rsGetSpillInfo(tree, tree->GetRegNum(), &prevDsc);
assert(spillDsc != nullptr);
// Get the temp desc.
TempDsc* temp = regSet.rsGetSpillTempWord(tree->GetRegNum(), spillDsc, prevDsc);
return temp;
}
/*****************************************************************************
*
* The following can be used to create basic blocks that serve as labels for
* the emitter. Use with caution - these are not real basic blocks!
*
*/
// inline
BasicBlock* CodeGen::genCreateTempLabel()
{
#ifdef DEBUG
// These blocks don't affect FP
compiler->fgSafeBasicBlockCreation = true;
#endif
// Label doesn't need a jump kind
BasicBlock* block = BasicBlock::New(compiler);
#ifdef DEBUG
compiler->fgSafeBasicBlockCreation = false;
#endif
JITDUMP("Mark " FMT_BB " as label: codegen temp block\n", block->bbNum);
block->SetFlags(BBF_HAS_LABEL);
// Use coldness of current block, as this label will
// be contained in it.
block->CopyFlags(compiler->compCurBB, BBF_COLD);
#ifdef DEBUG
#ifdef UNIX_X86_ABI
block->bbTgtStkDepth = (genStackLevel - curNestedAlignment) / sizeof(int);
#else
block->bbTgtStkDepth = genStackLevel / sizeof(int);
#endif
#endif
return block;
}
void CodeGen::genLogLabel(BasicBlock* bb)
{
#ifdef DEBUG
if (compiler->opts.dspCode)
{
printf("\n L_M%03u_" FMT_BB ":\n", compiler->compMethodID, bb->bbNum);
}
#endif
}
// genDefineTempLabel: Define a label based on the current GC info tracked by
// the code generator.
//
// Arguments:
// label - A label represented as a basic block. These are created with
// genCreateTempLabel and are not normal basic blocks.
//
// Notes:
// The label will be defined with the current GC info tracked by the code
// generator. When the emitter sees this label it will thus remove any temporary
// GC refs it is tracking in registers. For example, a call might produce a ref
// in RAX which the emitter would track but which would not be tracked in
// codegen's GC info since codegen would immediately copy it from RAX into its
// home.
//
void CodeGen::genDefineTempLabel(BasicBlock* label)
{
genLogLabel(label);
label->bbEmitCookie =