forked from dotnet/coreclr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlower.cpp
3586 lines (3114 loc) · 133 KB
/
lower.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. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Lower XX
XX XX
XX Preconditions: XX
XX XX
XX Postconditions (for the nodes currently handled): XX
XX - All operands requiring a register are explicit in the graph XX
XX XX
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 "lower.h"
//------------------------------------------------------------------------
// MakeSrcContained: Make "tree" a contained node
//
// Arguments:
// 'parentNode' is a non-leaf node that can contain its 'childNode'
// 'childNode' is an op that will now be contained by its parent.
//
// Notes:
// If 'childNode' it has any existing sources, they will now be sources for the parent.
//
void Lowering::MakeSrcContained(GenTreePtr parentNode, GenTreePtr childNode)
{
assert(!parentNode->OperIsLeaf());
int srcCount = childNode->gtLsraInfo.srcCount;
assert(srcCount >= 0);
m_lsra->clearOperandCounts(childNode);
assert(parentNode->gtLsraInfo.srcCount > 0);
parentNode->gtLsraInfo.srcCount += srcCount - 1;
}
//------------------------------------------------------------------------
// CheckImmedAndMakeContained: Check and make 'childNode' contained
// Arguments:
// 'parentNode' is any non-leaf node
// 'childNode' is an child op of 'parentNode'
// Return value:
// returns true if we are able to make childNode contained immediate
//
// Notes:
// Checks if the 'childNode' is a containable immediate
// and then makes it contained
//
bool Lowering::CheckImmedAndMakeContained(GenTree* parentNode, GenTree* childNode)
{
assert(!parentNode->OperIsLeaf());
// If childNode is a containable immediate
if (IsContainableImmed(parentNode, childNode))
{
// then make it contained within the parentNode
MakeSrcContained(parentNode, childNode);
return true;
}
return false;
}
//------------------------------------------------------------------------
// IsSafeToContainMem: Checks for conflicts between childNode and parentNode.
//
// Arguments:
// parentNode - a non-leaf binary node
// childNode - a memory op that is a child op of 'parentNode'
//
// Return value:
// returns true if it is safe to make childNode a contained memory op
//
// Notes:
// Checks for memory conflicts in the instructions between childNode and parentNode,
// and returns true iff childNode can be contained.
bool Lowering::IsSafeToContainMem(GenTree* parentNode, GenTree* childNode)
{
assert(parentNode->OperIsBinary());
assert(childNode->isMemoryOp());
// Check conflicts against nodes between 'childNode' and 'parentNode'
GenTree* node;
unsigned int childFlags = (childNode->gtFlags & GTF_ALL_EFFECT);
for (node = childNode->gtNext;
(node != parentNode) && (node != nullptr);
node = node->gtNext)
{
if ((childFlags != 0) && node->IsCall())
{
bool isPureHelper = (node->gtCall.gtCallType == CT_HELPER) && comp->s_helperCallProperties.IsPure(comp->eeGetHelperNum(node->gtCall.gtCallMethHnd));
if (!isPureHelper && ((node->gtFlags & childFlags & GTF_ALL_EFFECT) != 0))
{
return false;
}
}
else if (node->OperIsStore() && comp->fgNodesMayInterfere(node, childNode))
{
return false;
}
}
if (node != parentNode)
{
assert(!"Ran off end of stmt\n");
return false;
}
return true;
}
//------------------------------------------------------------------------
Compiler::fgWalkResult Lowering::DecompNodeHelper(GenTreePtr* pTree, Compiler::fgWalkData* data)
{
Lowering* lower = (Lowering*)data->pCallbackData;
lower->DecomposeNode(pTree, data);
return Compiler::WALK_CONTINUE;
}
Compiler::fgWalkResult Lowering::LowerNodeHelper(GenTreePtr* pTree, Compiler::fgWalkData* data)
{
Lowering* lower = (Lowering*)data->pCallbackData;
lower->LowerNode(pTree, data);
return Compiler::WALK_CONTINUE;
}
//------------------------------------------------------------------------
// DecomposeNode: Decompose long-type trees into lower & upper halves.
//
// Arguments:
// *pTree - A node that may or may not require decomposition.
// data - The tree-walk data that provides the context.
//
// Return Value:
// None.
//
// Notes: The rationale behind this is to avoid adding code complexity
// downstream caused by the introduction of handling longs as special cases, especially in
// LSRA.
// This function is called just prior to the more general purpose lowering.
//
void Lowering::DecomposeNode(GenTreePtr* pTree, Compiler::fgWalkData* data)
{
#if !defined(_TARGET_64BIT_)
GenTree* tree = *(pTree);
// Handle the case where we are implicitly using the lower half of a long lclVar.
if ((tree->TypeGet() == TYP_INT) && tree->OperIsLocal())
{
LclVarDsc * varDsc = comp->lvaTable + tree->AsLclVarCommon()->gtLclNum;
if (varTypeIsLong(varDsc) && varDsc->lvPromoted)
{
#ifdef DEBUG
if (comp->verbose)
{
printf("Changing implicit reference to lo half of long lclVar to an explicit reference of its promoted half:\n");
comp->gtDispTree(tree);
}
#endif
comp->lvaDecRefCnts(tree);
unsigned loVarNum = varDsc->lvFieldLclStart;
tree->AsLclVarCommon()->SetLclNum(loVarNum);
comp->lvaIncRefCnts(tree);
return;
}
}
if (tree->TypeGet() != TYP_LONG)
{
return;
}
#ifdef DEBUG
if (comp->verbose)
{
printf("Decomposing TYP_LONG tree. BEFORE:\n");
comp->gtDispTree(tree);
}
#endif
// The most common pattern is that we will create a loResult and a hiResult, where
// the loResult reuses some or all of the existing tree, and the hiResult is new.
// For these, we will set loResult and hiResult in the switch case below, ensuring
// that loResult is correctly linked into the statement, and hiResult is not, but
// is internally sequenced appropriately (if it is not a single node).
// Common code after the switch will link in hiResult and create a GT_LONG node.
GenTree* newTree = nullptr;
GenTree* loResult = nullptr;
GenTree* hiResult = nullptr;
GenTreeStmt* curStmt = comp->compCurStmt->AsStmt();
genTreeOps oper = tree->OperGet();
switch(oper)
{
case GT_PHI:
case GT_PHI_ARG:
break;
case GT_LCL_VAR:
{
loResult = tree;
unsigned varNum = tree->AsLclVarCommon()->gtLclNum;
LclVarDsc * varDsc = comp->lvaTable + varNum;
comp->lvaDecRefCnts(tree);
hiResult = comp->gtNewLclLNode(varNum, TYP_INT);
if (varDsc->lvPromoted)
{
assert(varDsc->lvFieldCnt == 2);
unsigned loVarNum = varDsc->lvFieldLclStart;
unsigned hiVarNum = loVarNum + 1;
tree->AsLclVarCommon()->SetLclNum(loVarNum);
hiResult->AsLclVarCommon()->SetLclNum(hiVarNum);
}
else
{
noway_assert(varDsc->lvLRACandidate == false);
tree->SetOper(GT_LCL_FLD);
tree->AsLclFld()->gtLclOffs = 0;
tree->AsLclFld()->gtFieldSeq = FieldSeqStore::NotAField();
hiResult->SetOper(GT_LCL_FLD);
hiResult->AsLclFld()->gtLclOffs = 4;
hiResult->AsLclFld()->gtFieldSeq = FieldSeqStore::NotAField();
}
tree->gtType = TYP_INT;
comp->lvaIncRefCnts(loResult);
comp->lvaIncRefCnts(hiResult);
break;
}
case GT_LCL_FLD:
loResult = tree;
loResult->gtType = TYP_INT;
hiResult = comp->gtNewLclFldNode(loResult->AsLclFld()->gtLclNum,
TYP_INT,
loResult->AsLclFld()->gtLclOffs + 4);
break;
case GT_STORE_LCL_VAR:
{
GenTree* nextTree = tree->gtNext;
GenTree* rhs = tree->gtGetOp1();
if (rhs->OperGet() == GT_PHI)
{
break;
}
noway_assert(rhs->OperGet() == GT_LONG);
unsigned varNum = tree->AsLclVarCommon()->gtLclNum;
LclVarDsc * varDsc = comp->lvaTable + varNum;
comp->lvaDecRefCnts(tree);
GenTree* loRhs = rhs->gtGetOp1();
GenTree* hiRhs = rhs->gtGetOp2();
GenTree* hiStore = comp->gtNewLclLNode(varNum, TYP_INT);
if (varDsc->lvPromoted)
{
assert(varDsc->lvFieldCnt == 2);
unsigned loVarNum = varDsc->lvFieldLclStart;
unsigned hiVarNum = loVarNum + 1;
tree->AsLclVarCommon()->SetLclNum(loVarNum);
hiStore->SetOper(GT_STORE_LCL_VAR);
}
else
{
noway_assert(varDsc->lvLRACandidate == false);
tree->SetOper(GT_STORE_LCL_FLD);
tree->AsLclFld()->gtLclOffs = 0;
tree->AsLclFld()->gtFieldSeq = FieldSeqStore::NotAField();
hiStore->SetOper(GT_STORE_LCL_FLD);
hiStore->AsLclFld()->gtLclOffs = 4;
hiStore->AsLclFld()->gtFieldSeq = FieldSeqStore::NotAField();
}
tree->gtOp.gtOp1 = loRhs;
tree->gtType = TYP_INT;
loRhs->gtNext = tree;
tree->gtPrev = loRhs;
hiStore->gtOp.gtOp1 = hiRhs;
hiStore->CopyCosts(tree);
hiStore->gtFlags |= GTF_VAR_DEF;
comp->lvaIncRefCnts(tree);
comp->lvaIncRefCnts(hiStore);
hiRhs->gtPrev = tree;
hiRhs->gtNext = hiStore;
hiStore->gtPrev = hiRhs;
hiStore->gtNext = nextTree;
if (nextTree != nullptr)
{
nextTree->gtPrev = hiStore;
}
nextTree = hiRhs;
GenTreeStmt* stmt;
if (comp->compCurStmt->gtStmt.gtStmtExpr == tree)
{
tree->gtNext = nullptr;
hiRhs->gtPrev = nullptr;
stmt = comp->fgNewStmtFromTree(hiStore);
comp->fgInsertStmtAfter(comp->compCurBB, comp->compCurStmt, stmt);
}
else
{
stmt = comp->fgMakeEmbeddedStmt(comp->compCurBB, hiStore, comp->compCurStmt);
}
stmt->gtStmtILoffsx = comp->compCurStmt->gtStmt.gtStmtILoffsx;
#ifdef DEBUG
stmt->gtStmtLastILoffs = comp->compCurStmt->gtStmt.gtStmtLastILoffs;
#endif // DEBUG
}
break;
case GT_CAST:
{
assert(tree->gtPrev == tree->gtGetOp1());
NYI_IF(tree->gtOverflow(), "TYP_LONG cast with overflow");
switch (tree->AsCast()->CastFromType())
{
case TYP_INT:
loResult = tree->gtGetOp1();
hiResult = new (comp, GT_CNS_INT) GenTreeIntCon(TYP_INT, 0);
comp->fgSnipNode(curStmt, tree);
break;
default:
NYI("Unimplemented type for Lowering of cast to TYP_LONG");
break;
}
break;
}
case GT_CNS_LNG:
{
INT32 hiVal = tree->AsLngCon()->HiVal();
loResult = tree;
loResult->ChangeOperConst(GT_CNS_INT);
loResult->gtType = TYP_INT;
hiResult = new (comp, GT_CNS_INT) GenTreeIntCon(TYP_INT, hiVal);
hiResult->CopyCosts(tree);
}
break;
case GT_CALL:
NYI("Call with TYP_LONG return value");
break;
case GT_RETURN:
assert(tree->gtOp.gtOp1->OperGet() == GT_LONG);
break;
case GT_STOREIND:
assert(tree->gtOp.gtOp2->OperGet() == GT_LONG);
NYI("StoreInd of of TYP_LONG");
break;
case GT_STORE_LCL_FLD:
assert(tree->gtOp.gtOp1->OperGet() == GT_LONG);
NYI("st.lclFld of of TYP_LONG");
break;
case GT_IND:
NYI("GT_IND of TYP_LONG");
break;
case GT_NOT:
{
GenTree* op1 = tree->gtGetOp1();
noway_assert(op1->OperGet() == GT_LONG);
GenTree* loOp1 = op1->gtGetOp1();
GenTree* hiOp1 = op1->gtGetOp2();
comp->fgSnipNode(curStmt, op1);
loResult = tree;
loResult->gtOp.gtOp1 = loOp1;
loOp1->gtNext = loResult;
loResult->gtPrev = loOp1;
hiResult = new (comp, oper) GenTreeOp(oper, TYP_INT, hiOp1, nullptr);
hiOp1->gtNext = hiResult;
hiResult->gtPrev = hiOp1;
}
break;
case GT_NEG:
NYI("GT_NEG of TYP_LONG");
break;
// Binary operators whose long result is simply the concatenation of the int result
// on its constituent halves:
case GT_OR:
case GT_XOR:
case GT_AND:
NYI("Logical binary operators on TYP_LONG");
break;
// Binary operators whose upper and lower halves require different computation.
case GT_ADD:
case GT_SUB:
case GT_MUL:
case GT_DIV:
case GT_MOD:
case GT_UDIV:
case GT_UMOD:
case GT_LSH:
case GT_RSH:
case GT_RSZ:
case GT_MULHI:
NYI("Arithmetic binary operators on TYP_LONG");
break;
case GT_LOCKADD:
case GT_XADD:
case GT_XCHG:
case GT_CMPXCHG:
NYI("Interlocked operations on TYP_LONG");
break;
default:
{
JITDUMP("Illegal TYP_LONG node %s in Lowering.", GenTree::NodeName(tree->OperGet()));
noway_assert(!"Illegal TYP_LONG node in Lowering.");
break;
}
}
if (loResult != nullptr)
{
noway_assert(hiResult != nullptr);
comp->fgInsertTreeInListAfter(hiResult, loResult, curStmt);
hiResult->CopyCosts(tree);
newTree = new (comp, GT_LONG) GenTreeOp(GT_LONG, TYP_LONG, loResult, hiResult);
SimpleLinkNodeAfter(hiResult, newTree);
}
if (newTree != nullptr)
{
comp->fgFixupIfCallArg(data->parentStack, tree, newTree);
newTree->CopyCosts(tree);
*pTree = newTree;
}
#ifdef DEBUG
if (comp->verbose)
{
printf(" AFTER:\n");
comp->gtDispTree(*pTree);
}
#endif
#endif // //_TARGET_64BIT_
}
/** Creates an assignment of an existing tree to a new temporary local variable
* and the specified reference count for the new variable.
*/
GenTreePtr Lowering::CreateLocalTempAsg(GenTreePtr rhs,
unsigned refCount,
GenTreePtr* ppLclVar) //out legacy arg
{
unsigned lclNum = comp->lvaGrabTemp(true DEBUGARG("Lowering is creating a new local variable"));
comp->lvaSortAgain = true;
comp->lvaTable[lclNum].lvType = rhs->TypeGet();
// Make sure we don't lose precision when downgrading to short
noway_assert(FitsIn<short>(refCount));
comp->lvaTable[lclNum].lvRefCnt = (short)(refCount);
JITDUMP("Lowering has requested a new temporary local variable: V%02u with refCount %u \n", lclNum, refCount);
GenTreeLclVar* store = new(comp, GT_STORE_LCL_VAR) GenTreeLclVar(GT_STORE_LCL_VAR, rhs->TypeGet(), lclNum, BAD_IL_OFFSET);
store->gtOp1 = rhs;
store->gtFlags = (rhs->gtFlags & GTF_COMMON_MASK);
store->gtFlags |= GTF_VAR_DEF;
return store;
}
// This is the main entry point for Lowering.
// In addition to that, LowerNode is also responsible for initializing the
// treeNodeMap data structure consumed by LSRA. This map is a 1:1 mapping between
// expression trees and TreeNodeInfo structs. Currently, Lowering initializes
// treeNodeMap with new instances of TreeNodeInfo for each tree and also annotates them
// with the register requirements needed for each tree.
// We receive a double pointer to a tree in order to be able, if needed, to entirely
// replace the tree by creating a new one and updating the underying pointer so this
// enables in-place tree manipulation.
// The current design is made in such a way we perform a helper call for each different
// type of tree. Currently, the only supported node is GT_IND and for that we call the
// LowerInd private method. The build system picks up the appropiate Lower.cpp (either
// LowerArm/LowerX86/LowerAMD64) that has the machine dependent logic to lower each node.
// TODO-Throughput: Modify post-order traversal to propagate parent info OR
// implement child iterator directly on GenTree, so that we can
// lower in-place.
void Lowering::LowerNode(GenTreePtr* ppTree, Compiler::fgWalkData* data)
{
// First, lower any child nodes (done via post-order walk)
assert(ppTree);
assert(*ppTree);
switch ((*ppTree)->gtOper)
{
case GT_IND:
case GT_STOREIND:
LowerInd(ppTree);
break;
case GT_ADD:
LowerAdd(ppTree, data);
break;
case GT_SWITCH:
LowerSwitch(ppTree);
break;
case GT_CALL:
LowerCall(*ppTree);
break;
case GT_JMP:
LowerJmpMethod(*ppTree);
break;
case GT_RETURN:
LowerRet(*ppTree);
break;
case GT_CAST:
LowerCast(ppTree);
break;
case GT_ARR_ELEM:
{
GenTree* oldTree = *ppTree;
LowerArrElem(ppTree, data);
comp->fgFixupIfCallArg(data->parentStack, oldTree, *ppTree);
}
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
if ((*ppTree)->TypeGet() == TYP_SIMD12)
{
// GT_SIMD node requiring to produce TYP_SIMD12 in fact
// produces a TYP_SIMD16 result
(*ppTree)->gtType = TYP_SIMD16;
}
break;
case GT_LCL_VAR:
case GT_STORE_LCL_VAR:
if ((*ppTree)->TypeGet() == TYP_SIMD12)
{
#ifdef _TARGET_64BIT_
// On 64-bit architectures, size of Vector3 local on stack will be
// rounded to TARGET_POINTER_SIZE and hence will be 16 bytes. Therefore,
// Vector3 locals on stack could be read/written as if they were TYP_SIMD16
(*ppTree)->gtType = TYP_SIMD16;
#else
NYI("Lowering of TYP_SIMD12 locals");
#endif // _TARGET_64BIT_
}
#endif //FEATURE_SIMD
default:
return;
}
}
/** -- Switch Lowering --
* The main idea of switch lowering is to keep transparency of the register requirements of this node
* downstream in LSRA. Given that the switch instruction is inherently a control statement which in the JIT
* is represented as a simple tree node, at the time we actually generate code for it we end up
* generating instructions that actually modify the flow of execution that imposes complicated
* register requirement and lifetimes.
*
* So, for the purpose of LSRA, we want to have a more detailed specification of what a switch node actually
* means and more importantly, which and when do we need a register for each instruction we want to issue
* to correctly allocate them downstream.
*
* For this purpose, this procedure performs switch lowering in two different ways:
*
* a) Represent the switch statement as a zero-index jump table construct. This means that for every destination
* of the switch, we will store this destination in an array of addresses and the code generator will issue
* a data section where this array will live and will emit code that based on the switch index, will indirect and
* jump to the destination specified in the jump table.
*
* For this transformation we introduce a new GT node called GT_SWITCH_TABLE that is a specialization of the switch node
* for jump table based switches.
* The overall structure of a GT_SWITCH_TABLE is:
*
* GT_SWITCH_TABLE
* |_________ localVar (a temporary local that holds the switch index)
* |_________ jumpTable (this is a special node that holds the address of the jump table array)
*
* Now, the way we morph a GT_SWITCH node into this lowered switch table node form is the following:
*
* Input: GT_SWITCH (inside a basic block whose Branch Type is BBJ_SWITCH)
* |_____ expr (an arbitrary complex GT_NODE that represents the switch index)
*
* This gets transformed into the following statements inside a BBJ_COND basic block (the target would be
* the default case of the switch in case the conditional is evaluated to true).
*
* GT_ASG
* |_____ tempLocal (a new temporary local variable used to store the switch index)
* |_____ expr (the index expression)
*
* GT_JTRUE
* |_____ GT_COND
* |_____ GT_GE
* |___ Int_Constant (This constant is the index of the default case
* that happens to be the highest index in the jump table).
* |___ tempLocal (The local variable were we stored the index expression).
*
* GT_SWITCH_TABLE
* |_____ tempLocal
* |_____ jumpTable (a new jump table node that now LSRA can allocate registers for explicitly
* and LinearCodeGen will be responsible to generate downstream).
*
* This way there are no implicit temporaries.
*
* b) For small-sized switches, we will actually morph them into a series of conditionals of the form
* if (case falls into the default){ goto jumpTable[size]; // last entry in the jump table is the default case }
* (For the default case conditional, we'll be constructing the exact same code as the jump table case one).
* else if (case == firstCase){ goto jumpTable[1]; }
* else if (case == secondCase) { goto jumptable[2]; } and so on.
*
* This transformation is of course made in JIT-IR, not downstream to CodeGen level, so this way we no longer require
* internal temporaries to maintain the index we're evaluating plus we're using existing code from LinearCodeGen
* to implement this instead of implement all the control flow constructs using InstrDscs and InstrGroups downstream.
*/
void Lowering::LowerSwitch(GenTreePtr* pTree)
{
unsigned jumpCnt;
unsigned targetCnt;
BasicBlock** jumpTab;
GenTreePtr tree = *pTree;
assert(tree->gtOper == GT_SWITCH);
// The first step is to build the default case conditional construct that is
// shared between both kinds of expansion of the switch node.
// To avoid confusion, we'll alias compCurBB to originalSwitchBB
// that represents the node we're morphing.
BasicBlock* originalSwitchBB = comp->compCurBB;
// jumpCnt is the number of elements in the jump table array.
// jumpTab is the actual pointer to the jump table array.
// targetCnt is the number of unique targets in the jump table array.
jumpCnt = originalSwitchBB->bbJumpSwt->bbsCount;
jumpTab = originalSwitchBB->bbJumpSwt->bbsDstTab;
targetCnt = originalSwitchBB->NumSucc(comp);
JITDUMP("Lowering switch BB%02u, %d cases\n", originalSwitchBB->bbNum, jumpCnt);
// Handle a degenerate case: if the switch has only a default case, just convert it
// to an unconditional branch. This should only happen in minopts or with debuggable
// code.
if (targetCnt == 1)
{
JITDUMP("Lowering switch BB%02u: single target; converting to BBJ_ALWAYS\n", originalSwitchBB->bbNum);
noway_assert(comp->opts.MinOpts() || comp->opts.compDbgCode);
if (originalSwitchBB->bbNext == jumpTab[0])
{
originalSwitchBB->bbJumpKind = BBJ_NONE;
originalSwitchBB->bbJumpDest = nullptr;
}
else
{
originalSwitchBB->bbJumpKind = BBJ_ALWAYS;
originalSwitchBB->bbJumpDest = jumpTab[0];
}
// Remove extra predecessor links if there was more than one case.
for (unsigned i = 1; i < jumpCnt; ++i)
{
(void) comp->fgRemoveRefPred(jumpTab[i], originalSwitchBB);
}
// We have to get rid of the GT_SWITCH node but a child might have side effects so just assign
// the result of the child subtree to a temp.
GenTree* store = CreateLocalTempAsg(tree->gtOp.gtOp1, 1);
tree->InsertAfterSelf(store, comp->compCurStmt->AsStmt());
Compiler::fgSnipNode(comp->compCurStmt->AsStmt(), tree);
*pTree = store;
return;
}
noway_assert(jumpCnt >= 2);
// Split the switch node to insert an assignment to a temporary variable.
// Note that 'tree' is the GT_SWITCH, and its op1 may be overwritten by SplitTree
//
GenTreeStmt* asgStmt = comp->fgInsertEmbeddedFormTemp(&(tree->gtOp.gtOp1));
// GT_SWITCH(indexExpression) is now two statements:
// 1. a statement containing 'asg' (for temp = indexExpression)
// 2. and a statement with GT_SWITCH(temp)
// The return value of fgInsertEmbeddedFormTemp is stmt 1
// The 'asg' can either be a GT_ASG or a GT_STORE_LCL_VAR
// 'tree' is still a GT_SWITCH but tree->gtOp.gtOp1 is modified to be 'temp'
// The asgStmt needs to pickup the IL offsets from the current statement
//
asgStmt->gtStmtILoffsx = comp->compCurStmt->gtStmt.gtStmtILoffsx;
#ifdef DEBUG
asgStmt->gtStmtLastILoffs = comp->compCurStmt->gtStmt.gtStmtLastILoffs;
#endif // DEBUG
assert(tree->gtOper == GT_SWITCH);
GenTreePtr temp = tree->gtOp.gtOp1;
assert(temp->gtOper == GT_LCL_VAR);
unsigned tempLclNum = temp->gtLclVarCommon.gtLclNum;
LclVarDsc * tempVarDsc = comp->lvaTable + tempLclNum;
var_types tempLclType = tempVarDsc->TypeGet();
BasicBlock* defaultBB = jumpTab[jumpCnt - 1];
BasicBlock* followingBB = originalSwitchBB->bbNext;
/* Is the number of cases right for a test and jump switch? */
const bool fFirstCaseFollows = (followingBB == jumpTab[0]);
const bool fDefaultFollows = (followingBB == defaultBB);
unsigned minSwitchTabJumpCnt = 2; // table is better than just 2 cmp/jcc
// This means really just a single cmp/jcc (aka a simple if/else)
if (fFirstCaseFollows || fDefaultFollows)
minSwitchTabJumpCnt++;
#if defined(_TARGET_ARM_)
// On ARM for small switch tables we will
// generate a sequence of compare and branch instructions
// because the code to load the base of the switch
// table is huge and hideous due to the relocation... :(
minSwitchTabJumpCnt += 2;
#elif defined(_TARGET_ARM64_) // _TARGET_ARM_
// In the case of ARM64 we'll stick to generate a sequence of
// compare and branch for now to get switch working and revisit
// to implement jump tables in the future.
//
// TODO-AMD64-NYI: Implement Jump Tables.
minSwitchTabJumpCnt = -1;
#endif // _TARGET_ARM64_
// Once we have the temporary variable, we construct the conditional branch for
// the default case. As stated above, this conditional is being shared between
// both GT_SWITCH lowering code paths.
// This condition is of the form: if (temp > jumpTableLength - 2){ goto jumpTable[jumpTableLength - 1]; }
GenTreePtr gtDefaultCaseCond = comp->gtNewOperNode(GT_GT, TYP_INT,
comp->gtNewLclvNode(tempLclNum, tempLclType),
comp->gtNewIconNode(jumpCnt - 2, TYP_INT));
//
// Make sure we perform an unsigned comparison, just in case the switch index in 'temp'
// is now less than zero 0 (that would also hit the default case).
gtDefaultCaseCond->gtFlags |= GTF_UNSIGNED;
/* Increment the lvRefCnt and lvRefCntWtd for temp */
tempVarDsc->incRefCnts(originalSwitchBB->getBBWeight(comp), comp);
GenTreePtr gtDefaultCaseJump = comp->gtNewOperNode(GT_JTRUE,
TYP_VOID,
gtDefaultCaseCond);
gtDefaultCaseJump->gtFlags = tree->gtFlags;
GenTreePtr condStmt = comp->fgNewStmtFromTree(gtDefaultCaseJump, originalSwitchBB, comp->compCurStmt->gtStmt.gtStmtILoffsx);
#ifdef DEBUG
condStmt->gtStmt.gtStmtLastILoffs = comp->compCurStmt->gtStmt.gtStmtLastILoffs;
#endif // DEBUG
comp->fgInsertStmtAfter(originalSwitchBB, comp->compCurStmt, condStmt);
BasicBlock* afterDefCondBlock = comp->fgSplitBlockAfterStatement(originalSwitchBB, condStmt);
// afterDefCondBlock is now the switch, and all the switch targets have it as a predecessor.
// originalSwitchBB is now a BBJ_NONE, and there is a predecessor edge in afterDefCondBlock
// representing the fall-through flow from originalSwitchBB.
assert(originalSwitchBB->bbJumpKind == BBJ_NONE);
assert(afterDefCondBlock->bbJumpKind == BBJ_SWITCH);
assert(afterDefCondBlock->bbJumpSwt->bbsHasDefault);
// Turn originalSwitchBB into a BBJ_COND.
originalSwitchBB->bbJumpKind = BBJ_COND;
originalSwitchBB->bbJumpDest = jumpTab[jumpCnt - 1];
// Fix the pred for the default case: the default block target still has originalSwitchBB
// as a predecessor, but the fgSplitBlockAfterStatement() moved all predecessors to point
// to afterDefCondBlock.
flowList* oldEdge = comp->fgRemoveRefPred(jumpTab[jumpCnt - 1], afterDefCondBlock);
comp->fgAddRefPred(jumpTab[jumpCnt - 1], originalSwitchBB, oldEdge);
// If we originally had 2 unique successors, check to see whether there is a unique
// non-default case, in which case we can eliminate the switch altogether.
// Note that the single unique successor case is handled above.
BasicBlock* uniqueSucc = nullptr;
if (targetCnt == 2)
{
uniqueSucc = jumpTab[0];
noway_assert(jumpCnt >= 2);
for (unsigned i = 1; i < jumpCnt - 1; i++)
{
if (jumpTab[i] != uniqueSucc)
{
uniqueSucc = nullptr;
break;
}
}
}
if (uniqueSucc != nullptr)
{
// If the unique successor immediately follows this block, we have nothing to do -
// it will simply fall-through after we remove the switch, below.
// Otherwise, make this a BBJ_ALWAYS.
// Now, fixup the predecessor links to uniqueSucc. In the original jumpTab:
// jumpTab[i-1] was the default target, which we handled above,
// jumpTab[0] is the first target, and we'll leave that predecessor link.
// Remove any additional predecessor links to uniqueSucc.
for (unsigned i = 1; i < jumpCnt - 1; ++i)
{
assert(jumpTab[i] == uniqueSucc);
(void) comp->fgRemoveRefPred(uniqueSucc, afterDefCondBlock);
}
if (afterDefCondBlock->bbNext == uniqueSucc)
{
afterDefCondBlock->bbJumpKind = BBJ_NONE;
afterDefCondBlock->bbJumpDest = nullptr;
}
else
{
afterDefCondBlock->bbJumpKind = BBJ_ALWAYS;
afterDefCondBlock->bbJumpDest = uniqueSucc;
}
}
// If the number of possible destinations is small enough, we proceed to expand the switch
// into a series of conditional branches, otherwise we follow the jump table based switch
// transformation.
else if (jumpCnt < minSwitchTabJumpCnt)
{
// Lower the switch into a series of compare and branch IR trees.
//
// In this case we will morph the tree in the following way:
// 1. Generate a JTRUE statement to evaluate the default case. (This happens above.)
// 2. Start splitting the switch basic block into subsequent basic blocks, each of which will contain
// a statement that is responsible for performing a comparison of the table index and conditional
// branch if equal.
JITDUMP("Lowering switch BB%02u: using compare/branch expansion\n", originalSwitchBB->bbNum);
// We'll use 'afterDefCondBlock' for the first conditional. After that, we'll add new
// blocks. If we end up not needing it at all (say, if all the non-default cases just fall through),
// we'll delete it.
bool fUsedAfterDefCondBlock = false;
BasicBlock* currentBlock = afterDefCondBlock;
// Walk to entries 0 to jumpCnt - 1. If a case target follows, ignore it and let it fall through.
// If no case target follows, the last one doesn't need to be a compare/branch: it can be an
// unconditional branch.
bool fAnyTargetFollows = false;
for (unsigned i = 0; i < jumpCnt - 1; ++i)
{
assert(currentBlock != nullptr);
// Remove the switch from the predecessor list of this case target's block.
// We'll add the proper new predecessor edge later.
flowList* oldEdge = comp->fgRemoveRefPred(jumpTab[i], afterDefCondBlock);
if (jumpTab[i] == followingBB)
{
// This case label follows the switch; let it fall through.
fAnyTargetFollows = true;
continue;
}
// We need a block to put in the new compare and/or branch.
// If we haven't used the afterDefCondBlock yet, then use that.
if (fUsedAfterDefCondBlock)
{
BasicBlock* newBlock = comp->fgNewBBafter(BBJ_NONE, currentBlock, true);
comp->fgAddRefPred(newBlock, currentBlock); // The fall-through predecessor.
currentBlock = newBlock;
}
else
{
assert(currentBlock == afterDefCondBlock);
fUsedAfterDefCondBlock = true;
}
// We're going to have a branch, either a conditional or unconditional,
// to the target. Set the target.
currentBlock->bbJumpDest = jumpTab[i];
// Wire up the predecessor list for the "branch" case.
comp->fgAddRefPred(jumpTab[i], currentBlock, oldEdge);
if (!fAnyTargetFollows && (i == jumpCnt - 2))
{
// We're processing the last one, and there is no fall through from any case
// to the following block, so we can use an unconditional branch to the final
// case: there is no need to compare against the case index, since it's
// guaranteed to be taken (since the default case was handled first, above).
currentBlock->bbJumpKind = BBJ_ALWAYS;
}
else
{
// Otherwise, it's a conditional branch. Set the branch kind, then add the
// condition statement.
currentBlock->bbJumpKind = BBJ_COND;
// Now, build the conditional statement for the current case that is
// being evaluated:
// GT_JTRUE
// |__ GT_COND
// |____GT_EQ
// |____ (switchIndex) (The temp variable)
// |____ (ICon) (The actual case constant)
GenTreePtr gtCaseCond = comp->gtNewOperNode(GT_EQ, TYP_INT,
comp->gtNewLclvNode(tempLclNum, tempLclType),
comp->gtNewIconNode(i, TYP_INT));
/* Increment the lvRefCnt and lvRefCntWtd for temp */
tempVarDsc->incRefCnts(originalSwitchBB->getBBWeight(comp), comp);
GenTreePtr gtCaseBranch = comp->gtNewOperNode(GT_JTRUE, TYP_VOID, gtCaseCond);
GenTreePtr gtCaseStmt = comp->fgNewStmtFromTree(gtCaseBranch, currentBlock);
comp->fgInsertStmtAtEnd(currentBlock, gtCaseStmt);
}
}
if (fAnyTargetFollows)
{
// There is a fall-through to the following block. In the loop
// above, we deleted all the predecessor edges from the switch.
// In this case, we need to add one back.
comp->fgAddRefPred(currentBlock->bbNext, currentBlock);
}
if (!fUsedAfterDefCondBlock)
{
// All the cases were fall-through! We don't need this block.
// Convert it from BBJ_SWITCH to BBJ_NONE and unset the BBF_DONT_REMOVE flag
// so fgRemoveBlock() doesn't complain.
JITDUMP("Lowering switch BB%02u: all switch cases were fall-through\n", originalSwitchBB->bbNum);
assert(currentBlock == afterDefCondBlock);
assert(currentBlock->bbJumpKind == BBJ_SWITCH);
currentBlock->bbJumpKind = BBJ_NONE;
currentBlock->bbFlags &= ~BBF_DONT_REMOVE;
comp->fgRemoveBlock(currentBlock, /* unreachable */ false); // It's an empty block.
}
}
else
{
// Lower the switch into an indirect branch using a jump table:
//
// 1. Create the constant for the default case
// 2. Generate a GT_GE condition to compare to the default case
// 3. Generate a GT_JTRUE to jump.
// 4. Load the jump table address into a local (presumably the just
// created constant for GT_SWITCH).
// 5. Create a new node for the lowered switch, this will both generate
// the branch table and also will be responsible for the indirect
// branch.
JITDUMP("Lowering switch BB%02u: using jump table expansion\n", originalSwitchBB->bbNum);
GenTreePtr gtTableSwitch = comp->gtNewOperNode(GT_SWITCH_TABLE,
TYP_VOID,
comp->gtNewLclvNode(tempLclNum, tempLclType),
comp->gtNewJmpTableNode());
/* Increment the lvRefCnt and lvRefCntWtd for temp */
tempVarDsc->incRefCnts(originalSwitchBB->getBBWeight(comp), comp);
// this block no longer branches to the default block
afterDefCondBlock->bbJumpSwt->removeDefault();
comp->fgInvalidateSwitchDescMapEntry(afterDefCondBlock);
GenTreeStmt* stmt = comp->fgNewStmtFromTree(gtTableSwitch);
comp->fgInsertStmtAtEnd(afterDefCondBlock, stmt);
}
// Get rid of the original GT_SWITCH.
comp->fgRemoveStmt(originalSwitchBB, comp->compCurStmt, false);
// Set compCurStmt. If asgStmt is top-level, we need to set it to that, so that any of
// its embedded statements are traversed. Otherwise, set it to condStmt, which will
// contain the embedded asgStmt.
if (asgStmt->gtStmtIsTopLevel())
{
comp->compCurStmt = asgStmt;
}
else
{
#ifdef DEBUG
GenTree* nextStmt = condStmt->gtNext;
while (nextStmt != nullptr && nextStmt != asgStmt)
{
nextStmt = nextStmt->gtNext;
}
assert(nextStmt == asgStmt);
#endif // DEBUG
comp->compCurStmt = condStmt;
}
}
// splice in a unary op, between the child and parent
// resulting in parent->newNode->child
void Lowering::SpliceInUnary(GenTreePtr parent, GenTreePtr* ppChild, GenTreePtr newNode)
{
GenTreePtr oldChild = *ppChild;
// Replace tree in the parent node
*ppChild = newNode;
newNode->gtOp.gtOp1 = oldChild;