-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
importer.cpp
21664 lines (18343 loc) · 819 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"
#define Verify(cond, msg) \
do \
{ \
if (!(cond)) \
{ \
verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
} \
} while (0)
#define VerifyOrReturn(cond, msg) \
do \
{ \
if (!(cond)) \
{ \
verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
return; \
} \
} while (0)
#define VerifyOrReturnSpeculative(cond, msg, speculative) \
do \
{ \
if (speculative) \
{ \
if (!(cond)) \
{ \
return false; \
} \
} \
else \
{ \
if (!(cond)) \
{ \
verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
return false; \
} \
} \
} while (0)
/*****************************************************************************/
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->bbFlags & BBF_IMPORTED) == 0)))
{
BADCODE("stack overflow");
}
#ifdef DEBUG
// If we are pushing a struct, make certain we know the precise type!
if (tree->TypeGet() == TYP_STRUCT)
{
assert(ti.IsType(TI_STRUCT));
CORINFO_CLASS_HANDLE clsHnd = ti.GetClassHandle();
assert(clsHnd != NO_CLASS_HANDLE);
}
if (tiVerificationNeeded && !ti.IsDead())
{
assert(typeInfo::AreEquivalent(NormaliseForStack(ti), ti)); // types are normalized
// The ti type is consistent with the tree type.
//
// On 64-bit systems, nodes whose "proper" type is "native int" get labeled TYP_LONG.
// In the verification type system, we always transform "native int" to "TI_INT".
// Ideally, we would keep track of which nodes labeled "TYP_LONG" are really "native int", but
// attempts to do that have proved too difficult. Instead, we'll assume that in checks like this,
// when there's a mismatch, it's because of this reason -- the typeInfo::AreEquivalentModuloNativeInt
// method used in the last disjunct allows exactly this mismatch.
assert(ti.IsDead() || (ti.IsByRef() && ((tree->TypeGet() == TYP_I_IMPL) || (tree->TypeGet() == TYP_BYREF))) ||
(ti.IsUnboxedGenericTypeVar() && tree->TypeGet() == TYP_REF) ||
(ti.IsObjRef() && tree->TypeGet() == TYP_REF) || (ti.IsMethod() && tree->TypeGet() == TYP_I_IMPL) ||
(ti.IsType(TI_STRUCT) && tree->TypeGet() != TYP_REF) ||
typeInfo::AreEquivalentModuloNativeInt(NormaliseForStack(ti),
NormaliseForStack(typeInfo(tree->TypeGet()))));
// If it is a struct type, make certain we normalized the primitive types
assert(!ti.IsType(TI_STRUCT) ||
info.compCompHnd->getTypeForPrimitiveValueClass(ti.GetClassHandle()) == CORINFO_TYPE_UNDEF);
}
#if VERBOSE_VERIFY
if (VERBOSE && tiVerificationNeeded)
{
printf("\n");
printf(TI_DUMP_PADDING);
printf("About to push to stack: ");
ti.Dump();
}
#endif // VERBOSE_VERIFY
#endif // DEBUG
verCurrentState.esStack[verCurrentState.esStackDepth].seTypeInfo = ti;
verCurrentState.esStack[verCurrentState.esStackDepth++].val = tree;
if ((tree->gtType == TYP_LONG) && (compLongUsed == false))
{
compLongUsed = true;
}
else if (((tree->gtType == TYP_FLOAT) || (tree->gtType == TYP_DOUBLE)) && (compFloatingPointUsed == false))
{
compFloatingPointUsed = true;
}
}
inline void Compiler::impPushNullObjRefOnStack()
{
impPushOnStack(gtNewIconNode(0, TYP_REF), typeInfo(TI_NULL));
}
// This method gets called when we run into unverifiable code
// (and we are verifying the method)
inline void Compiler::verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* msg) DEBUGARG(const char* file)
DEBUGARG(unsigned line))
{
#ifdef DEBUG
const char* tail = strrchr(file, '\\');
if (tail)
{
file = tail + 1;
}
if (JitConfig.JitBreakOnUnsafeCode())
{
assert(!"Unsafe code detected");
}
#endif
JITLOG((LL_INFO10000, "Detected unsafe code: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
msg, info.compFullName, impCurOpcName, impCurOpcOffs));
if (compIsForImportOnly())
{
JITLOG((LL_ERROR, "Verification failure: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
msg, info.compFullName, impCurOpcName, impCurOpcOffs));
verRaiseVerifyException(INDEBUG(msg) DEBUGARG(file) DEBUGARG(line));
}
}
inline void DECLSPEC_NORETURN Compiler::verRaiseVerifyException(INDEBUG(const char* msg) DEBUGARG(const char* file)
DEBUGARG(unsigned line))
{
JITLOG((LL_ERROR, "Verification failure: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
msg, info.compFullName, impCurOpcName, impCurOpcOffs));
#ifdef DEBUG
// BreakIfDebuggerPresent();
if (getBreakOnBadCode())
{
assert(!"Typechecking error");
}
#endif
RaiseException(SEH_VERIFICATION_EXCEPTION, EXCEPTION_NONCONTINUABLE, 0, nullptr);
UNREACHABLE();
}
// 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;
if (!tiVerificationNeeded)
{
info.compCompHnd->resolveToken(pResolvedToken);
}
else
{
Verify(eeTryResolveToken(pResolvedToken), "Token resolution failed");
}
}
/*****************************************************************************
*
* Pop one tree from the stack.
*/
StackEntry Compiler::impPopStack()
{
if (verCurrentState.esStackDepth == 0)
{
BADCODE("stack underflow");
}
#ifdef DEBUG
#if VERBOSE_VERIFY
if (VERBOSE && tiVerificationNeeded)
{
JITDUMP("\n");
printf(TI_DUMP_PADDING);
printf("About to pop from the stack: ");
const typeInfo& ti = verCurrentState.esStack[verCurrentState.esStackDepth - 1].seTypeInfo;
ti.Dump();
}
#endif // VERBOSE_VERIFY
#endif // DEBUG
return verCurrentState.esStack[--verCurrentState.esStackDepth];
}
/*****************************************************************************
*
* 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_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.
//
inline 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.
*/
inline 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->bbFlags & BBF_IMPORTED) == 0);
block->bbFlags |= BBF_IMPORTED;
}
//------------------------------------------------------------------------
// impEndTreeList: Store the current tree list in the given basic block.
//
// Arguments:
// block - the basic block to store into.
//
inline void Compiler::impEndTreeList(BasicBlock* block)
{
if (impStmtList == nullptr)
{
// The block should not already be marked as imported.
assert((block->bbFlags & BBF_IMPORTED) == 0);
// Empty block. Just mark it as imported.
block->bbFlags |= 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).
*/
inline void Compiler::impAppendStmtCheck(Statement* stmt, unsigned chkLevel)
{
#ifndef DEBUG
return;
#else
if (chkLevel == (unsigned)CHECK_SPILL_ALL)
{
chkLevel = verCurrentState.esStackDepth;
}
if (verCurrentState.esStackDepth == 0 || chkLevel == 0 || chkLevel == (unsigned)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->gtOper == GT_ASG)
{
// For an assignment 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->AsOp()->gtOp1->gtOper == GT_LCL_VAR)
{
unsigned lclNum = tree->AsOp()->gtOp1->AsLclVarCommon()->GetLclNum();
for (unsigned level = 0; level < chkLevel; level++)
{
assert(!gtHasRef(verCurrentState.esStack[level].val, lclNum, false));
assert(!lvaTable[lclNum].lvAddrExposed ||
(verCurrentState.esStack[level].val->gtFlags & GTF_SIDE_EFFECT) == 0);
}
}
// If the access may be to global memory, all side effects have to be spilled.
else if (tree->AsOp()->gtOp1->gtFlags & GTF_GLOB_REF)
{
for (unsigned level = 0; level < chkLevel; level++)
{
assert((verCurrentState.esStack[level].val->gtFlags & GTF_GLOB_REF) == 0);
}
}
}
#endif
}
/*****************************************************************************
*
* Append the given statement to the current block's tree list.
* [0..chkLevel) is the portion of the stack which we will check for
* interference with stmt and spill if needed.
*/
inline void Compiler::impAppendStmt(Statement* stmt, unsigned chkLevel)
{
if (chkLevel == (unsigned)CHECK_SPILL_ALL)
{
chkLevel = verCurrentState.esStackDepth;
}
if ((chkLevel != 0) && (chkLevel != (unsigned)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();
unsigned flags = expr->gtFlags & GTF_GLOB_EFFECT;
// Assignment to (unaliased) locals don't count as a side-effect as
// we handle them specially using impSpillLclRefs(). Temp locals should
// be fine too.
if ((expr->gtOper == GT_ASG) && (expr->AsOp()->gtOp1->gtOper == GT_LCL_VAR) &&
((expr->AsOp()->gtOp1->gtFlags & GTF_GLOB_REF) == 0) && !gtHasLocalsWithAddrOp(expr->AsOp()->gtOp2))
{
unsigned op2Flags = expr->AsOp()->gtOp2->gtFlags & GTF_GLOB_EFFECT;
assert(flags == (op2Flags | GTF_ASG));
flags = op2Flags;
}
if (flags != 0)
{
bool spillGlobEffects = false;
if ((flags & GTF_CALL) != 0)
{
// If there is a call, we have to spill global refs
spillGlobEffects = true;
}
else if (!expr->OperIs(GT_ASG))
{
if ((flags & GTF_ASG) != 0)
{
// The expression is not an assignment node but it has an assignment side effect, it
// must be an atomic op, HW intrinsic or some other kind of node that stores to memory.
// Since we don't know what it assigns to, we need to spill global refs.
spillGlobEffects = true;
}
}
else
{
GenTree* lhs = expr->gtGetOp1();
GenTree* rhs = expr->gtGetOp2();
if (((rhs->gtFlags | lhs->gtFlags) & GTF_ASG) != 0)
{
// Either side of the assignment node has an assignment side effect.
// Since we don't know what it assigns to, we need to spill global refs.
spillGlobEffects = true;
}
else if ((lhs->gtFlags & GTF_GLOB_REF) != 0)
{
spillGlobEffects = true;
}
}
impSpillSideEffects(spillGlobEffects, chkLevel DEBUGARG("impAppendStmt"));
}
else
{
impSpillSpecialSideEff();
}
}
impAppendStmtCheck(stmt, chkLevel);
impAppendStmt(stmt);
#ifdef FEATURE_SIMD
impMarkContiguousSIMDFieldAssignments(stmt);
#endif
/* Once we set impCurStmtOffs in an appended tree, we are ready to
report the following offsets. So reset impCurStmtOffs */
if (impLastStmt->GetILOffsetX() == impCurStmtOffs)
{
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.
//
inline 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.
//
inline 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);
}
/*****************************************************************************
*
* Append the given expression tree to the current block's tree list.
* Return the newly created statement.
*/
Statement* Compiler::impAppendTree(GenTree* tree, unsigned chkLevel, IL_OFFSETX offset)
{
assert(tree);
/* Allocate an 'expression statement' node */
Statement* stmt = gtNewStmt(tree, offset);
/* Append the statement to the current block's stmt list */
impAppendStmt(stmt, chkLevel);
return stmt;
}
/*****************************************************************************
*
* Insert the given expression tree before "stmtBefore"
*/
void Compiler::impInsertTreeBefore(GenTree* tree, IL_OFFSETX offset, Statement* stmtBefore)
{
/* Allocate an 'expression statement' node */
Statement* stmt = gtNewStmt(tree, offset);
/* Append the statement to the current block's stmt list */
impInsertStmtBefore(stmt, stmtBefore);
}
/*****************************************************************************
*
* 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::impAssignTempGen(unsigned tmp,
GenTree* val,
unsigned curLevel,
Statement** pAfterStmt, /* = NULL */
IL_OFFSETX ilOffset, /* = BAD_IL_OFFSET */
BasicBlock* block /* = NULL */
)
{
GenTree* asg = gtNewTempAssign(tmp, val);
if (!asg->IsNothingNode())
{
if (pAfterStmt)
{
Statement* asgStmt = gtNewStmt(asg, ilOffset);
fgInsertStmtAfter(block, *pAfterStmt, asgStmt);
*pAfterStmt = asgStmt;
}
else
{
impAppendTree(asg, curLevel, impCurStmtOffs);
}
}
}
/*****************************************************************************
* same as above, but handle the valueclass case too
*/
void Compiler::impAssignTempGen(unsigned tmpNum,
GenTree* val,
CORINFO_CLASS_HANDLE structType,
unsigned curLevel,
Statement** pAfterStmt, /* = NULL */
IL_OFFSETX ilOffset, /* = BAD_IL_OFFSET */
BasicBlock* block /* = NULL */
)
{
GenTree* asg;
assert(val->TypeGet() != TYP_STRUCT || structType != NO_CLASS_HANDLE);
if (varTypeIsStruct(val) && (structType != NO_CLASS_HANDLE))
{
assert(tmpNum < lvaCount);
assert(structType != NO_CLASS_HANDLE);
// if the method is non-verifiable the assert is not true
// so at least ignore it in the case when verification is turned on
// since any block that tries to use the temp would have failed verification.
var_types varType = lvaTable[tmpNum].lvType;
assert(tiVerificationNeeded || varType == TYP_UNDEF || varTypeIsStruct(varType));
lvaSetStruct(tmpNum, structType, false);
varType = lvaTable[tmpNum].lvType;
// Now, set the type of the struct value. Note that lvaSetStruct may modify the type
// of the lclVar to a specialized type (e.g. TYP_SIMD), based on the handle (structType)
// that has been passed in for the value being assigned to the temp, in which case we
// need to set 'val' to that same type.
// Note also that if we always normalized the types of any node that might be a struct
// type, this would not be necessary - but that requires additional JIT/EE interface
// calls that may not actually be required - e.g. if we only access a field of a struct.
if (compDoOldStructRetyping())
{
val->gtType = varType;
}
GenTree* dst = gtNewLclvNode(tmpNum, varType);
asg = impAssignStruct(dst, val, structType, curLevel, pAfterStmt, ilOffset, block);
}
else
{
asg = gtNewTempAssign(tmpNum, val);
}
if (!asg->IsNothingNode())
{
if (pAfterStmt)
{
Statement* asgStmt = gtNewStmt(asg, ilOffset);
fgInsertStmtAfter(block, *pAfterStmt, asgStmt);
*pAfterStmt = asgStmt;
}
else
{
impAppendTree(asg, curLevel, impCurStmtOffs);
}
}
}
/*****************************************************************************
*
* Pop the given number of values from the stack and return a list node with
* their values.
* The 'prefixTree' argument may optionally contain an argument
* list that is prepended to the list returned from this function.
*
* The notion of prepended is a bit misleading in that the list is backwards
* from the way I would expect: The first element popped is at the end of
* the returned list, and prefixTree is 'before' that, meaning closer to
* the end of the list. To get to prefixTree, you have to walk to the
* end of the list.
*
* For ARG_ORDER_R2L prefixTree is only used to insert extra arguments, as
* such we reverse its meaning such that returnValue has a reversed
* prefixTree at the head of the list.
*/
GenTreeCall::Use* Compiler::impPopCallArgs(unsigned count, CORINFO_SIG_INFO* sig, GenTreeCall::Use* prefixArgs)
{
assert(sig == nullptr || count == sig->numArgs);
CORINFO_CLASS_HANDLE structType;
GenTreeCall::Use* argList;
if (Target::g_tgtArgOrder == Target::ARG_ORDER_R2L)
{
argList = nullptr;
}
else
{ // ARG_ORDER_L2R
argList = prefixArgs;
}
while (count--)
{
StackEntry se = impPopStack();
typeInfo ti = se.seTypeInfo;
GenTree* temp = se.val;
if (varTypeIsStruct(temp))
{
// Morph trees that aren't already OBJs or MKREFANY to be OBJs
assert(ti.IsType(TI_STRUCT));
structType = ti.GetClassHandleForValueClass();
bool forceNormalization = false;
if (varTypeIsSIMD(temp))
{
// We need to ensure that fgMorphArgs will use the correct struct handle to ensure proper
// ABI handling of this argument.
// Note that this can happen, for example, if we have a SIMD intrinsic that returns a SIMD type
// with a different baseType than we've seen.
// We also need to ensure an OBJ node if we have a FIELD node that might be transformed to LCL_FLD
// or a plain GT_IND.
// TODO-Cleanup: Consider whether we can eliminate all of these cases.
if ((gtGetStructHandleIfPresent(temp) != structType) || temp->OperIs(GT_FIELD))
{
forceNormalization = true;
}
}
#ifdef DEBUG
if (verbose)
{
printf("Calling impNormStructVal on:\n");
gtDispTree(temp);
}
#endif
temp = impNormStructVal(temp, structType, (unsigned)CHECK_SPILL_ALL, forceNormalization);
#ifdef DEBUG
if (verbose)
{
printf("resulting tree:\n");
gtDispTree(temp);
}
#endif
}
/* NOTE: we defer bashing the type for I_IMPL to fgMorphArgs */
argList = gtPrependNewCallArg(temp, argList);
}
if (sig != nullptr)
{
if (sig->retTypeSigClass != nullptr && sig->retType != CORINFO_TYPE_CLASS &&
sig->retType != CORINFO_TYPE_BYREF && sig->retType != CORINFO_TYPE_PTR && sig->retType != CORINFO_TYPE_VAR)
{
// Make sure that all valuetypes (including enums) that we push are loaded.
// This is to guarantee that if a GC is triggerred from the prestub of this methods,
// all valuetypes in the method signature are already loaded.
// We need to be able to find the size of the valuetypes, but we cannot
// do a class-load from within GC.
info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(sig->retTypeSigClass);
}
CORINFO_ARG_LIST_HANDLE sigArgs = sig->args;
GenTreeCall::Use* arg;
for (arg = argList, count = sig->numArgs; count > 0; arg = arg->GetNext(), count--)
{
PREFIX_ASSUME(arg != nullptr);
CORINFO_CLASS_HANDLE classHnd;
CorInfoType corType = strip(info.compCompHnd->getArgType(sig, sigArgs, &classHnd));
var_types jitSigType = JITtype2varType(corType);
if (!impCheckImplicitArgumentCoercion(jitSigType, arg->GetNode()->TypeGet()))
{
BADCODE("the call argument has a type that can't be implicitly converted to the signature type");
}
// insert implied casts (from float to double or double to float)
if ((jitSigType == TYP_DOUBLE) && (arg->GetNode()->TypeGet() == TYP_FLOAT))
{
arg->SetNode(gtNewCastNode(TYP_DOUBLE, arg->GetNode(), false, TYP_DOUBLE));
}
else if ((jitSigType == TYP_FLOAT) && (arg->GetNode()->TypeGet() == TYP_DOUBLE))
{
arg->SetNode(gtNewCastNode(TYP_FLOAT, arg->GetNode(), false, TYP_FLOAT));
}
// insert any widening or narrowing casts for backwards compatibility
arg->SetNode(impImplicitIorI4Cast(arg->GetNode(), jitSigType));
if (corType != CORINFO_TYPE_CLASS && corType != CORINFO_TYPE_BYREF && corType != CORINFO_TYPE_PTR &&
corType != CORINFO_TYPE_VAR)
{
CORINFO_CLASS_HANDLE argRealClass = info.compCompHnd->getArgClass(sig, sigArgs);
if (argRealClass != nullptr)
{
// Make sure that all valuetypes (including enums) that we push are loaded.
// This is to guarantee that if a GC is triggered from the prestub of this methods,
// all valuetypes in the method signature are already loaded.
// We need to be able to find the size of the valuetypes, but we cannot
// do a class-load from within GC.
info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(argRealClass);
}
}
const var_types nodeArgType = arg->GetNode()->TypeGet();
if (!varTypeIsStruct(jitSigType) && genTypeSize(nodeArgType) != genTypeSize(jitSigType))
{
assert(!varTypeIsStruct(nodeArgType));
// Some ABI require precise size information for call arguments less than target pointer size,
// for example arm64 OSX. Create a special node to keep this information until morph
// consumes it into `fgArgInfo`.
GenTree* putArgType = gtNewOperNode(GT_PUTARG_TYPE, jitSigType, arg->GetNode());
arg->SetNode(putArgType);
}
sigArgs = info.compCompHnd->getArgNext(sigArgs);
}
}
if (Target::g_tgtArgOrder == Target::ARG_ORDER_R2L)
{
// Prepend the prefixTree