-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathimporter.cpp
13731 lines (11631 loc) · 516 KB
/
importer.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 Importer XX
XX XX
XX Imports the given method and converts it to semantic trees XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "corexcep.h"
/*****************************************************************************/
void Compiler::impInit()
{
impStmtList = impLastStmt = nullptr;
#ifdef DEBUG
impInlinedCodeSize = 0;
#endif // DEBUG
}
/*****************************************************************************
*
* Pushes the given tree on the stack.
*/
void Compiler::impPushOnStack(GenTree* tree, typeInfo ti)
{
/* Check for overflow. If inlining, we may be using a bigger stack */
if ((verCurrentState.esStackDepth >= info.compMaxStack) &&
(verCurrentState.esStackDepth >= impStkSize || !compCurBB->HasFlag(BBF_IMPORTED)))
{
BADCODE("stack overflow");
}
verCurrentState.esStack[verCurrentState.esStackDepth].seTypeInfo = ti;
verCurrentState.esStack[verCurrentState.esStackDepth++].val = tree;
if (tree->gtType == TYP_LONG)
{
compLongUsed = true;
}
else if ((tree->gtType == TYP_FLOAT) || (tree->gtType == TYP_DOUBLE))
{
compFloatingPointUsed = true;
}
}
// helper function that will tell us if the IL instruction at the addr passed
// by param consumes an address at the top of the stack. We use it to save
// us lvAddrTaken
bool Compiler::impILConsumesAddr(const BYTE* codeAddr)
{
assert(!compIsForInlining());
OPCODE opcode;
opcode = (OPCODE)getU1LittleEndian(codeAddr);
switch (opcode)
{
// case CEE_LDFLDA: We're taking this one out as if you have a sequence
// like
//
// ldloca.0
// ldflda whatever
//
// of a primitivelike struct, you end up after morphing with addr of a local
// that's not marked as addrtaken, which is wrong. Also ldflda is usually used
// for structs that contain other structs, which isnt a case we handle very
// well now for other reasons.
case CEE_LDFLD:
{
// We won't collapse small fields. This is probably not the right place to have this
// check, but we're only using the function for this purpose, and is easy to factor
// out if we need to do so.
CORINFO_RESOLVED_TOKEN resolvedToken;
impResolveToken(codeAddr + sizeof(__int8), &resolvedToken, CORINFO_TOKENKIND_Field);
var_types lclTyp = JITtype2varType(info.compCompHnd->getFieldType(resolvedToken.hField));
// Preserve 'small' int types
if (!varTypeIsSmall(lclTyp))
{
lclTyp = genActualType(lclTyp);
}
if (varTypeIsSmall(lclTyp))
{
return false;
}
return true;
}
default:
break;
}
return false;
}
void Compiler::impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind)
{
pResolvedToken->tokenContext = impTokenLookupContextHandle;
pResolvedToken->tokenScope = info.compScopeHnd;
pResolvedToken->token = getU4LittleEndian(addr);
pResolvedToken->tokenType = kind;
info.compCompHnd->resolveToken(pResolvedToken);
}
//------------------------------------------------------------------------
// impPopStack: Pop one tree from the stack.
//
// Returns:
// The stack entry for the popped tree.
//
StackEntry Compiler::impPopStack()
{
if (verCurrentState.esStackDepth == 0)
{
BADCODE("stack underflow");
}
return verCurrentState.esStack[--verCurrentState.esStackDepth];
}
//------------------------------------------------------------------------
// impPopStack: Pop a variable number of trees from the stack.
//
// Arguments:
// n - The number of trees to pop.
//
void Compiler::impPopStack(unsigned n)
{
if (verCurrentState.esStackDepth < n)
{
BADCODE("stack underflow");
}
verCurrentState.esStackDepth -= n;
}
/*****************************************************************************
*
* Peep at n'th (0-based) tree on the top of the stack.
*/
StackEntry& Compiler::impStackTop(unsigned n)
{
if (verCurrentState.esStackDepth <= n)
{
BADCODE("stack underflow");
}
return verCurrentState.esStack[verCurrentState.esStackDepth - n - 1];
}
unsigned Compiler::impStackHeight()
{
return verCurrentState.esStackDepth;
}
/*****************************************************************************
* Some of the trees are spilled specially. While unspilling them, or
* making a copy, these need to be handled specially. The function
* enumerates the operators possible after spilling.
*/
#ifdef DEBUG // only used in asserts
static bool impValidSpilledStackEntry(GenTree* tree)
{
if (tree->gtOper == GT_LCL_VAR)
{
return true;
}
if (tree->OperIsConst())
{
return true;
}
return false;
}
#endif
/*****************************************************************************
*
* The following logic is used to save/restore stack contents.
* If 'copy' is true, then we make a copy of the trees on the stack. These
* have to all be cloneable/spilled values.
*/
void Compiler::impSaveStackState(SavedStack* savePtr, bool copy)
{
savePtr->ssDepth = verCurrentState.esStackDepth;
if (verCurrentState.esStackDepth)
{
savePtr->ssTrees = new (this, CMK_ImpStack) StackEntry[verCurrentState.esStackDepth];
size_t saveSize = verCurrentState.esStackDepth * sizeof(*savePtr->ssTrees);
if (copy)
{
StackEntry* table = savePtr->ssTrees;
/* Make a fresh copy of all the stack entries */
for (unsigned level = 0; level < verCurrentState.esStackDepth; level++, table++)
{
table->seTypeInfo = verCurrentState.esStack[level].seTypeInfo;
GenTree* tree = verCurrentState.esStack[level].val;
assert(impValidSpilledStackEntry(tree));
switch (tree->gtOper)
{
case GT_CNS_INT:
case GT_CNS_LNG:
case GT_CNS_DBL:
case GT_CNS_STR:
case GT_CNS_VEC:
case GT_LCL_VAR:
table->val = gtCloneExpr(tree);
break;
default:
assert(!"Bad oper - Not covered by impValidSpilledStackEntry()");
break;
}
}
}
else
{
memcpy(savePtr->ssTrees, verCurrentState.esStack, saveSize);
}
}
}
void Compiler::impRestoreStackState(SavedStack* savePtr)
{
verCurrentState.esStackDepth = savePtr->ssDepth;
if (verCurrentState.esStackDepth)
{
memcpy(verCurrentState.esStack, savePtr->ssTrees,
verCurrentState.esStackDepth * sizeof(*verCurrentState.esStack));
}
}
//------------------------------------------------------------------------
// impBeginTreeList: Get the tree list started for a new basic block.
//
void Compiler::impBeginTreeList()
{
assert(impStmtList == nullptr && impLastStmt == nullptr);
}
/*****************************************************************************
*
* Store the given start and end stmt in the given basic block. This is
* mostly called by impEndTreeList(BasicBlock *block). It is called
* directly only for handling CEE_LEAVEs out of finally-protected try's.
*/
void Compiler::impEndTreeList(BasicBlock* block, Statement* firstStmt, Statement* lastStmt)
{
/* Make the list circular, so that we can easily walk it backwards */
firstStmt->SetPrevStmt(lastStmt);
/* Store the tree list in the basic block */
block->bbStmtList = firstStmt;
/* The block should not already be marked as imported */
assert(!block->HasFlag(BBF_IMPORTED));
block->SetFlags(BBF_IMPORTED);
}
void Compiler::impEndTreeList(BasicBlock* block)
{
if (impStmtList == nullptr)
{
// The block should not already be marked as imported.
assert(!block->HasFlag(BBF_IMPORTED));
// Empty block. Just mark it as imported.
block->SetFlags(BBF_IMPORTED);
}
else
{
impEndTreeList(block, impStmtList, impLastStmt);
}
#ifdef DEBUG
if (impLastILoffsStmt != nullptr)
{
impLastILoffsStmt->SetLastILOffset(compIsForInlining() ? BAD_IL_OFFSET : impCurOpcOffs);
impLastILoffsStmt = nullptr;
}
#endif
impStmtList = impLastStmt = nullptr;
}
/*****************************************************************************
*
* Check that storing the given tree doesnt mess up the semantic order. Note
* that this has only limited value as we can only check [0..chkLevel).
*/
void Compiler::impAppendStmtCheck(Statement* stmt, unsigned chkLevel)
{
#ifndef DEBUG
return;
#else
if (chkLevel == CHECK_SPILL_ALL)
{
chkLevel = verCurrentState.esStackDepth;
}
if (verCurrentState.esStackDepth == 0 || chkLevel == 0 || chkLevel == CHECK_SPILL_NONE)
{
return;
}
GenTree* tree = stmt->GetRootNode();
// Calls can only be appended if there are no GTF_GLOB_EFFECT on the stack
if (tree->gtFlags & GTF_CALL)
{
for (unsigned level = 0; level < chkLevel; level++)
{
assert((verCurrentState.esStack[level].val->gtFlags & GTF_GLOB_EFFECT) == 0);
}
}
if (tree->OperIsStore())
{
// For a store to a local variable, all references of that variable have to be spilled.
// If it is aliased, all calls and indirect accesses have to be spilled.
if (tree->OperIsLocalStore())
{
unsigned lclNum = tree->AsLclVarCommon()->GetLclNum();
for (unsigned level = 0; level < chkLevel; level++)
{
GenTree* stkTree = verCurrentState.esStack[level].val;
assert(!gtHasRef(stkTree, lclNum) || impIsInvariant(stkTree));
assert(!lvaTable[lclNum].IsAddressExposed() || ((stkTree->gtFlags & GTF_SIDE_EFFECT) == 0));
}
}
// If the access may be to global memory, all side effects have to be spilled.
else if ((tree->gtFlags & GTF_GLOB_REF) != 0)
{
for (unsigned level = 0; level < chkLevel; level++)
{
assert((verCurrentState.esStack[level].val->gtFlags & GTF_GLOB_REF) == 0);
}
}
}
#endif
}
//------------------------------------------------------------------------
// impAppendStmt: Append the given statement to the current block's tree list.
//
//
// Arguments:
// stmt - The statement to add.
// chkLevel - [0..chkLevel) is the portion of the stack which we will check
// for interference with stmt and spilled if needed.
// checkConsumedDebugInfo - Whether to check for consumption of impCurStmtDI. impCurStmtDI
// marks the debug info of the current boundary and is set when we
// start importing IL at that boundary. If this parameter is true,
// then the function checks if 'stmt' has been associated with the
// current boundary, and if so, clears it so that we do not attach
// it to more upcoming statements.
//
void Compiler::impAppendStmt(Statement* stmt, unsigned chkLevel, bool checkConsumedDebugInfo)
{
if (chkLevel == CHECK_SPILL_ALL)
{
chkLevel = verCurrentState.esStackDepth;
}
if ((chkLevel != 0) && (chkLevel != CHECK_SPILL_NONE))
{
assert(chkLevel <= verCurrentState.esStackDepth);
// If the statement being appended has any side-effects, check the stack to see if anything
// needs to be spilled to preserve correct ordering.
//
GenTree* expr = stmt->GetRootNode();
GenTreeFlags flags = expr->gtFlags & GTF_GLOB_EFFECT;
// Stores to unaliased locals require special handling. Here, we look for trees that
// can modify them and spill the references. In doing so, we make two assumptions:
//
// 1. All locals which can be modified indirectly are marked as address-exposed or with
// "lvHasLdAddrOp" -- we will rely on "impSpillSideEffects(spillGlobEffects: true)"
// below to spill them.
// 2. Trees that assign to unaliased locals are always top-level (this avoids having to
// walk down the tree here), and are a subset of what is recognized here.
//
// If any of the above are violated (say for some temps), the relevant code must spill
// things manually.
//
LclVarDsc* dstVarDsc = nullptr;
if (expr->OperIsLocalStore())
{
dstVarDsc = lvaGetDesc(expr->AsLclVarCommon());
}
else if (expr->OperIs(GT_CALL, GT_RET_EXPR)) // The special case of calls with return buffers.
{
GenTree* call = expr->OperIs(GT_RET_EXPR) ? expr->AsRetExpr()->gtInlineCandidate : expr;
if (call->TypeIs(TYP_VOID) && call->AsCall()->TreatAsShouldHaveRetBufArg(this))
{
GenTree* retBuf;
if (call->AsCall()->ShouldHaveRetBufArg())
{
assert(call->AsCall()->gtArgs.HasRetBuffer());
retBuf = call->AsCall()->gtArgs.GetRetBufferArg()->GetNode();
}
else
{
assert(!call->AsCall()->gtArgs.HasThisPointer());
retBuf = call->AsCall()->gtArgs.GetArgByIndex(0)->GetNode();
}
assert(retBuf->TypeIs(TYP_I_IMPL, TYP_BYREF));
if (retBuf->OperIs(GT_LCL_ADDR))
{
dstVarDsc = lvaGetDesc(retBuf->AsLclVarCommon());
}
}
}
// In the case of GT_RET_EXPR any subsequent spills will appear in the wrong place -- after
// the call. We need to move them to before the call
//
Statement* lastStmt = impLastStmt;
if ((dstVarDsc != nullptr) && !dstVarDsc->IsAddressExposed() && !dstVarDsc->lvHasLdAddrOp)
{
impSpillLclRefs(lvaGetLclNum(dstVarDsc), chkLevel);
if (expr->OperIsLocalStore())
{
// For assignments, limit the checking to what the value could modify/interfere with.
GenTree* value = expr->AsLclVarCommon()->Data();
flags = value->gtFlags & GTF_GLOB_EFFECT;
// We don't mark indirections off of "aliased" locals with GLOB_REF, but they must still be
// considered as such in the interference checking.
if (((flags & GTF_GLOB_REF) == 0) && !impIsAddressInLocal(value) && gtHasLocalsWithAddrOp(value))
{
flags |= GTF_GLOB_REF;
}
}
}
if (flags != 0)
{
impSpillSideEffects((flags & (GTF_ASG | GTF_CALL)) != 0, chkLevel DEBUGARG("impAppendStmt"));
}
else
{
impSpillSpecialSideEff();
}
if ((lastStmt != impLastStmt) && expr->OperIs(GT_RET_EXPR))
{
GenTree* const call = expr->AsRetExpr()->gtInlineCandidate;
JITDUMP("\nimpAppendStmt: after sinking a local struct store into inline candidate [%06u], we need to "
"reorder subsequent spills.\n",
dspTreeID(call));
// Move all newly appended statements to just before the call's statement.
// First, find the statement containing the call.
//
Statement* insertBeforeStmt = lastStmt;
while (insertBeforeStmt->GetRootNode() != call)
{
assert(insertBeforeStmt != impStmtList);
insertBeforeStmt = insertBeforeStmt->GetPrevStmt();
}
Statement* movingStmt = lastStmt->GetNextStmt();
JITDUMP("Moving " FMT_STMT " through " FMT_STMT " before " FMT_STMT "\n", movingStmt->GetID(),
impLastStmt->GetID(), insertBeforeStmt->GetID());
// We move these backwards, so must keep moving the insert
// point to keep them in order.
//
while (impLastStmt != lastStmt)
{
Statement* movingStmt = impExtractLastStmt();
impInsertStmtBefore(movingStmt, insertBeforeStmt);
insertBeforeStmt = movingStmt;
}
}
}
impAppendStmtCheck(stmt, chkLevel);
impAppendStmt(stmt);
#ifdef FEATURE_SIMD
impMarkContiguousSIMDFieldStores(stmt);
#endif
// Once we set the current offset as debug info in an appended tree, we are
// ready to report the following offsets. Note that we need to compare
// offsets here instead of debug info, since we do not set the "is call"
// bit in impCurStmtDI.
if (checkConsumedDebugInfo &&
(impLastStmt->GetDebugInfo().GetLocation().GetOffset() == impCurStmtDI.GetLocation().GetOffset()))
{
impCurStmtOffsSet(BAD_IL_OFFSET);
}
#ifdef DEBUG
if (impLastILoffsStmt == nullptr)
{
impLastILoffsStmt = stmt;
}
if (verbose)
{
printf("\n\n");
gtDispStmt(stmt);
}
#endif
}
//------------------------------------------------------------------------
// impAppendStmt: Add the statement to the current stmts list.
//
// Arguments:
// stmt - the statement to add.
//
void Compiler::impAppendStmt(Statement* stmt)
{
if (impStmtList == nullptr)
{
// The stmt is the first in the list.
impStmtList = stmt;
}
else
{
// Append the expression statement to the existing list.
impLastStmt->SetNextStmt(stmt);
stmt->SetPrevStmt(impLastStmt);
}
impLastStmt = stmt;
}
//------------------------------------------------------------------------
// impExtractLastStmt: Extract the last statement from the current stmts list.
//
// Return Value:
// The extracted statement.
//
// Notes:
// It assumes that the stmt will be reinserted later.
//
Statement* Compiler::impExtractLastStmt()
{
assert(impLastStmt != nullptr);
Statement* stmt = impLastStmt;
impLastStmt = impLastStmt->GetPrevStmt();
if (impLastStmt == nullptr)
{
impStmtList = nullptr;
}
return stmt;
}
//-------------------------------------------------------------------------
// impInsertStmtBefore: Insert the given "stmt" before "stmtBefore".
//
// Arguments:
// stmt - a statement to insert;
// stmtBefore - an insertion point to insert "stmt" before.
//
void Compiler::impInsertStmtBefore(Statement* stmt, Statement* stmtBefore)
{
assert(stmt != nullptr);
assert(stmtBefore != nullptr);
if (stmtBefore == impStmtList)
{
impStmtList = stmt;
}
else
{
Statement* stmtPrev = stmtBefore->GetPrevStmt();
stmt->SetPrevStmt(stmtPrev);
stmtPrev->SetNextStmt(stmt);
}
stmt->SetNextStmt(stmtBefore);
stmtBefore->SetPrevStmt(stmt);
}
//------------------------------------------------------------------------
// impAppendTree: Append the given expression tree to the current block's tree list.
//
//
// Arguments:
// tree - The tree that will be the root of the newly created statement.
// chkLevel - [0..chkLevel) is the portion of the stack which we will check
// for interference with stmt and spill if needed.
// di - Debug information to associate with the statement.
// checkConsumedDebugInfo - Whether to check for consumption of impCurStmtDI. impCurStmtDI
// marks the debug info of the current boundary and is set when we
// start importing IL at that boundary. If this parameter is true,
// then the function checks if 'stmt' has been associated with the
// current boundary, and if so, clears it so that we do not attach
// it to more upcoming statements.
//
// Return value:
// The newly created statement.
//
Statement* Compiler::impAppendTree(GenTree* tree, unsigned chkLevel, const DebugInfo& di, bool checkConsumedDebugInfo)
{
assert(tree);
/* Allocate an 'expression statement' node */
Statement* stmt = gtNewStmt(tree, di);
/* Append the statement to the current block's stmt list */
impAppendStmt(stmt, chkLevel, checkConsumedDebugInfo);
return stmt;
}
/*****************************************************************************
*
* Append an assignment of the given value to a temp to the current tree list.
* curLevel is the stack level for which the spill to the temp is being done.
*/
void Compiler::impStoreTemp(unsigned lclNum,
GenTree* val,
unsigned curLevel,
Statement** pAfterStmt, /* = NULL */
const DebugInfo& di, /* = DebugInfo() */
BasicBlock* block /* = NULL */
)
{
GenTree* store = gtNewTempStore(lclNum, val, curLevel, pAfterStmt, di, block);
if (!store->IsNothingNode())
{
if (pAfterStmt)
{
Statement* storeStmt = gtNewStmt(store, di);
fgInsertStmtAfter(block, *pAfterStmt, storeStmt);
*pAfterStmt = storeStmt;
}
else
{
impAppendTree(store, curLevel, impCurStmtDI);
}
}
}
static bool TypeIs(var_types type1, var_types type2)
{
return type1 == type2;
}
// Check if type1 matches any type from the list.
template <typename... T>
static bool TypeIs(var_types type1, var_types type2, T... rest)
{
return TypeIs(type1, type2) || TypeIs(type1, rest...);
}
//------------------------------------------------------------------------
// impCheckImplicitArgumentCoercion: check that the node's type is compatible with
// the signature's type using ECMA implicit argument coercion table.
//
// Arguments:
// sigType - the type in the call signature;
// nodeType - the node type.
//
// Return Value:
// true if they are compatible, false otherwise.
//
// Notes:
// - it is currently allowing byref->long passing, should be fixed in VM;
// - it can't check long -> native int case on 64-bit platforms,
// so the behavior is different depending on the target bitness.
//
bool Compiler::impCheckImplicitArgumentCoercion(var_types sigType, var_types nodeType)
{
if (sigType == nodeType)
{
return true;
}
if (TypeIs(sigType, TYP_UBYTE, TYP_BYTE, TYP_USHORT, TYP_SHORT, TYP_UINT, TYP_INT))
{
if (TypeIs(nodeType, TYP_UBYTE, TYP_BYTE, TYP_USHORT, TYP_SHORT, TYP_UINT, TYP_INT, TYP_I_IMPL))
{
return true;
}
}
else if (TypeIs(sigType, TYP_ULONG, TYP_LONG))
{
if (TypeIs(nodeType, TYP_LONG))
{
return true;
}
}
else if (TypeIs(sigType, TYP_FLOAT, TYP_DOUBLE))
{
if (TypeIs(nodeType, TYP_FLOAT, TYP_DOUBLE))
{
return true;
}
}
else if (TypeIs(sigType, TYP_BYREF))
{
if (TypeIs(nodeType, TYP_I_IMPL))
{
return true;
}
// This condition tolerates such IL:
// ; V00 this ref this class-hnd
// ldarg.0
// call(byref)
if (TypeIs(nodeType, TYP_REF))
{
return true;
}
}
else if (varTypeIsStruct(sigType))
{
if (varTypeIsStruct(nodeType))
{
return true;
}
}
// This condition should not be under `else` because `TYP_I_IMPL`
// intersects with `TYP_LONG` or `TYP_INT`.
if (TypeIs(sigType, TYP_I_IMPL, TYP_U_IMPL))
{
// Note that it allows `ldc.i8 1; call(nint)` on 64-bit platforms,
// but we can't distinguish `nint` from `long` there.
if (TypeIs(nodeType, TYP_I_IMPL, TYP_U_IMPL, TYP_INT, TYP_UINT))
{
return true;
}
// It tolerates IL that ECMA does not allow but that is commonly used.
// Example:
// V02 loc1 struct <RTL_OSVERSIONINFOEX, 32>
// ldloca.s 0x2
// call(native int)
if (TypeIs(nodeType, TYP_BYREF))
{
return true;
}
}
return false;
}
//------------------------------------------------------------------------
// impStoreStruct: Import a struct store.
//
// Arguments:
// store - the store
// curLevel - stack level for which a spill may be being done
// pAfterStmt - statement to insert any additional statements after
// di - debug info for new statements
// block - block to insert any additional statements in
//
// Return Value:
// The tree that should be appended to the statement list that represents the store.
//
// Notes:
// Temp stores may be appended to impStmtList if spilling is necessary.
//
GenTree* Compiler::impStoreStruct(GenTree* store,
unsigned curLevel,
Statement** pAfterStmt, /* = nullptr */
const DebugInfo& di, /* = DebugInfo() */
BasicBlock* block /* = nullptr */
)
{
assert(varTypeIsStruct(store) && store->OperIsStore());
GenTree* src = store->Data();
assert(store->TypeGet() == src->TypeGet());
if (store->TypeIs(TYP_STRUCT))
{
assert(ClassLayout::AreCompatible(store->GetLayout(this), src->GetLayout(this)));
}
DebugInfo usedDI = di;
if (!usedDI.IsValid())
{
usedDI = impCurStmtDI;
}
if (src->IsCall())
{
GenTreeCall* srcCall = src->AsCall();
if (srcCall->TreatAsShouldHaveRetBufArg(this))
{
// Case of call returning a struct via hidden retbuf arg.
// Some calls have an "out buffer" that is not actually a ret buff
// in the ABI sense. We take the path here for those but it should
// not be marked as the ret buff arg since it always follow the
// normal ABI for parameters.
WellKnownArg wellKnownArgType =
srcCall->ShouldHaveRetBufArg() ? WellKnownArg::RetBuffer : WellKnownArg::None;
// TODO-Bug?: verify if flags matter here
GenTreeFlags indirFlags = GTF_EMPTY;
GenTree* destAddr = impGetNodeAddr(store, CHECK_SPILL_ALL, &indirFlags);
NewCallArg newArg = NewCallArg::Primitive(destAddr).WellKnown(wellKnownArgType);
#if !defined(TARGET_ARM)
// Unmanaged instance methods on Windows or Unix X86 need the retbuf arg after the first (this) parameter
if ((TargetOS::IsWindows || compUnixX86Abi()) && srcCall->IsUnmanaged())
{
if (callConvIsInstanceMethodCallConv(srcCall->GetUnmanagedCallConv()))
{
#ifdef TARGET_X86
// The argument list has already been reversed. Insert the
// return buffer as the second-to-last node so it will be
// pushed on to the stack after the user args but before
// the native this arg as required by the native ABI.
if (srcCall->gtArgs.Args().begin() == srcCall->gtArgs.Args().end())
{
// Empty arg list
srcCall->gtArgs.PushFront(this, newArg);
}
else if (srcCall->GetUnmanagedCallConv() == CorInfoCallConvExtension::Thiscall)
{
// For thiscall, the "this" parameter is not included in the argument list reversal,
// so we need to put the return buffer as the last parameter.
srcCall->gtArgs.PushBack(this, newArg);
}
else if (srcCall->gtArgs.Args().begin()->GetNext() == nullptr)
{
// Only 1 arg, so insert at beginning
srcCall->gtArgs.PushFront(this, newArg);
}
else
{
// Find second last arg
CallArg* secondLastArg = nullptr;
for (CallArg& arg : srcCall->gtArgs.Args())
{
assert(arg.GetNext() != nullptr);
if (arg.GetNext()->GetNext() == nullptr)
{
secondLastArg = &arg;
break;
}
}
assert(secondLastArg && "Expected to find second last arg");
srcCall->gtArgs.InsertAfter(this, secondLastArg, newArg);
}
#else
if (srcCall->gtArgs.Args().begin() == srcCall->gtArgs.Args().end())
{
srcCall->gtArgs.PushFront(this, newArg);
}
else
{
srcCall->gtArgs.InsertAfter(this, srcCall->gtArgs.Args().begin().GetArg(), newArg);
}
#endif
}
else
{
#ifdef TARGET_X86
// The argument list has already been reversed.
// Insert the return buffer as the last node so it will be pushed on to the stack last
// as required by the native ABI.
srcCall->gtArgs.PushBack(this, newArg);
#else
// insert the return value buffer into the argument list as first byref parameter
srcCall->gtArgs.PushFront(this, newArg);
#endif
}
}
else
#endif // !defined(TARGET_ARM)
{
// insert the return value buffer into the argument list as first byref parameter after 'this'
srcCall->gtArgs.InsertAfterThisOrFirst(this, newArg);
}
// now returns void, not a struct
src->gtType = TYP_VOID;
// return the morphed call node
return src;
}
#ifdef UNIX_AMD64_ABI
if (store->OperIs(GT_STORE_LCL_VAR))
{
// TODO-Cleanup: delete this quirk.
lvaGetDesc(store->AsLclVar())->lvIsMultiRegRet = true;
}
#endif // UNIX_AMD64_ABI
}
else if (src->OperIs(GT_RET_EXPR))
{
assert(src->AsRetExpr()->gtInlineCandidate->OperIs(GT_CALL));
GenTreeCall* call = src->AsRetExpr()->gtInlineCandidate;
if (call->ShouldHaveRetBufArg())
{
// insert the return value buffer into the argument list as first byref parameter after 'this'
// TODO-Bug?: verify if flags matter here
GenTreeFlags indirFlags = GTF_EMPTY;
GenTree* destAddr = impGetNodeAddr(store, CHECK_SPILL_ALL, &indirFlags);
call->gtArgs.InsertAfterThisOrFirst(this,
NewCallArg::Primitive(destAddr).WellKnown(WellKnownArg::RetBuffer));
// now returns void, not a struct
src->gtType = TYP_VOID;
call->gtType = TYP_VOID;
// We already have appended the write to 'dest' GT_CALL's args
// So now we just return an empty node (pruning the GT_RET_EXPR)
return src;
}
}
else if (src->OperIs(GT_MKREFANY))
{
// Since we are assigning the result of a GT_MKREFANY, "destAddr" must point to a refany.
// TODO-CQ: we can do this without address-exposing the local on the LHS.
GenTreeFlags indirFlags = GTF_EMPTY;
GenTree* destAddr = impGetNodeAddr(store, CHECK_SPILL_ALL, &indirFlags);
GenTree* destAddrClone;
destAddr = impCloneExpr(destAddr, &destAddrClone, curLevel, pAfterStmt DEBUGARG("MKREFANY assignment"));
assert(OFFSETOF__CORINFO_TypedReference__dataPtr == 0);
assert(destAddr->gtType == TYP_I_IMPL || destAddr->gtType == TYP_BYREF);
// Append the store of the pointer value.
// TODO-Bug: the pointer value can be a byref. Use its actual type here instead of TYP_I_IMPL.
GenTree* ptrFieldStore = gtNewStoreIndNode(TYP_I_IMPL, destAddr, src->AsOp()->gtOp1, indirFlags);
if (pAfterStmt)
{
Statement* newStmt = gtNewStmt(ptrFieldStore, usedDI);
fgInsertStmtAfter(block, *pAfterStmt, newStmt);
*pAfterStmt = newStmt;
}
else
{
impAppendTree(ptrFieldStore, curLevel, usedDI);
}
GenTree* typeFieldOffset = gtNewIconNode(OFFSETOF__CORINFO_TypedReference__type, TYP_I_IMPL);
GenTree* typeFieldAddr = gtNewOperNode(GT_ADD, genActualType(destAddr), destAddrClone, typeFieldOffset);
GenTree* typeFieldStore = gtNewStoreIndNode(TYP_I_IMPL, typeFieldAddr, src->AsOp()->gtOp2);
// Return the store of the type value, to be appended.
return typeFieldStore;
}