-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
morph.cpp
19485 lines (17038 loc) · 740 KB
/
morph.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 Morph XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "allocacheck.h" // for alloca
// Convert the given node into a call to the specified helper passing
// the given argument list.
//
// Tries to fold constants and also adds an edge for overflow exception
// returns the morphed tree
GenTree* Compiler::fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper)
{
GenTree* result;
/* If the operand is a constant, we'll try to fold it */
if (oper->OperIsConst())
{
GenTree* oldTree = tree;
tree = gtFoldExprConst(tree); // This may not fold the constant (NaN ...)
if (tree != oldTree)
{
return fgMorphTree(tree);
}
else if (tree->OperKind() & GTK_CONST)
{
return fgMorphConst(tree);
}
// assert that oper is unchanged and that it is still a GT_CAST node
noway_assert(tree->AsCast()->CastOp() == oper);
noway_assert(tree->gtOper == GT_CAST);
}
result = fgMorphIntoHelperCall(tree, helper, gtNewCallArgs(oper));
assert(result == tree);
return result;
}
/*****************************************************************************
*
* Convert the given node into a call to the specified helper passing
* the given argument list.
*/
GenTree* Compiler::fgMorphIntoHelperCall(GenTree* tree, int helper, GenTreeCall::Use* args, bool morphArgs)
{
// The helper call ought to be semantically equivalent to the original node, so preserve its VN.
tree->ChangeOper(GT_CALL, GenTree::PRESERVE_VN);
GenTreeCall* call = tree->AsCall();
call->gtCallType = CT_HELPER;
call->gtCallMethHnd = eeFindHelper(helper);
call->gtCallThisArg = nullptr;
call->gtCallArgs = args;
call->gtCallLateArgs = nullptr;
call->fgArgInfo = nullptr;
call->gtRetClsHnd = nullptr;
call->gtCallMoreFlags = GTF_CALL_M_EMPTY;
call->gtInlineCandidateInfo = nullptr;
call->gtControlExpr = nullptr;
#if DEBUG
// Helper calls are never candidates.
call->gtInlineObservation = InlineObservation::CALLSITE_IS_CALL_TO_HELPER;
call->callSig = nullptr;
#endif // DEBUG
#ifdef FEATURE_READYTORUN_COMPILER
call->gtEntryPoint.addr = nullptr;
call->gtEntryPoint.accessType = IAT_VALUE;
#endif
#if FEATURE_MULTIREG_RET
call->ResetReturnType();
call->ClearOtherRegs();
call->ClearOtherRegFlags();
#ifndef TARGET_64BIT
if (varTypeIsLong(tree))
{
call->InitializeLongReturnType();
}
#endif // !TARGET_64BIT
#endif // FEATURE_MULTIREG_RET
if (tree->OperMayThrow(this))
{
tree->gtFlags |= GTF_EXCEPT;
}
else
{
tree->gtFlags &= ~GTF_EXCEPT;
}
tree->gtFlags |= GTF_CALL;
for (GenTreeCall::Use& use : GenTreeCall::UseList(args))
{
tree->gtFlags |= (use.GetNode()->gtFlags & GTF_ALL_EFFECT);
}
/* Perform the morphing */
if (morphArgs)
{
tree = fgMorphArgs(call);
}
return tree;
}
/*****************************************************************************
*
* Morph a cast node (we perform some very simple transformations here).
*/
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable : 21000) // Suppress PREFast warning about overly large function
#endif
GenTree* Compiler::fgMorphCast(GenTree* tree)
{
noway_assert(tree->gtOper == GT_CAST);
noway_assert(genTypeSize(TYP_I_IMPL) == TARGET_POINTER_SIZE);
/* The first sub-operand is the thing being cast */
GenTree* oper = tree->AsCast()->CastOp();
if (fgGlobalMorph && (oper->gtOper == GT_ADDR))
{
// Make sure we've checked if 'oper' is an address of an implicit-byref parameter.
// If it is, fgMorphImplicitByRefArgs will change its type, and we want the cast
// morphing code to see that type.
fgMorphImplicitByRefArgs(oper);
}
var_types srcType = genActualType(oper->TypeGet());
var_types dstType = tree->CastToType();
unsigned dstSize = genTypeSize(dstType);
// See if the cast has to be done in two steps. R -> I
if (varTypeIsFloating(srcType) && varTypeIsIntegral(dstType))
{
if (srcType == TYP_FLOAT
#if defined(TARGET_ARM64)
// Arm64: src = float, dst is overflow conversion.
// This goes through helper and hence src needs to be converted to double.
&& tree->gtOverflow()
#elif defined(TARGET_AMD64)
// Amd64: src = float, dst = uint64 or overflow conversion.
// This goes through helper and hence src needs to be converted to double.
&& (tree->gtOverflow() || (dstType == TYP_ULONG))
#elif defined(TARGET_ARM)
// Arm: src = float, dst = int64/uint64 or overflow conversion.
&& (tree->gtOverflow() || varTypeIsLong(dstType))
#else
// x86: src = float, dst = uint32/int64/uint64 or overflow conversion.
&& (tree->gtOverflow() || varTypeIsLong(dstType) || (dstType == TYP_UINT))
#endif
)
{
oper = gtNewCastNode(TYP_DOUBLE, oper, false, TYP_DOUBLE);
}
// do we need to do it in two steps R -> I, '-> smallType
CLANG_FORMAT_COMMENT_ANCHOR;
if (dstSize < genTypeSize(TYP_INT))
{
oper = gtNewCastNodeL(TYP_INT, oper, /* fromUnsigned */ false, TYP_INT);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
// We must not mistreat the original cast, which was from a floating point type,
// as from an unsigned type, since we now have a TYP_INT node for the source and
// CAST_OVF(BYTE <- INT) != CAST_OVF(BYTE <- UINT).
assert(!tree->IsUnsigned());
}
else
{
/* Note that if we need to use a helper call then we can not morph oper */
if (!tree->gtOverflow())
{
#ifdef TARGET_ARM64 // On ARM64 All non-overflow checking conversions can be optimized
goto OPTIMIZECAST;
#else
switch (dstType)
{
case TYP_INT:
goto OPTIMIZECAST;
case TYP_UINT:
#if defined(TARGET_ARM) || defined(TARGET_AMD64)
goto OPTIMIZECAST;
#else // TARGET_X86
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT, oper);
#endif // TARGET_X86
case TYP_LONG:
#ifdef TARGET_AMD64
// SSE2 has instructions to convert a float/double directly to a long
goto OPTIMIZECAST;
#else // !TARGET_AMD64
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG, oper);
#endif // !TARGET_AMD64
case TYP_ULONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG, oper);
default:
break;
}
#endif // TARGET_ARM64
}
else
{
switch (dstType)
{
case TYP_INT:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2INT_OVF, oper);
case TYP_UINT:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT_OVF, oper);
case TYP_LONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG_OVF, oper);
case TYP_ULONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG_OVF, oper);
default:
break;
}
}
noway_assert(!"Unexpected dstType");
}
}
#ifndef TARGET_64BIT
// The code generation phase (for x86 & ARM32) does not handle casts
// directly from [u]long to anything other than [u]int. Insert an
// intermediate cast to native int.
else if (varTypeIsLong(srcType) && varTypeIsSmall(dstType))
{
oper = gtNewCastNode(TYP_I_IMPL, oper, tree->IsUnsigned(), TYP_I_IMPL);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->gtFlags &= ~GTF_UNSIGNED;
}
#endif //! TARGET_64BIT
#ifdef TARGET_ARM
else if ((dstType == TYP_FLOAT) && (srcType == TYP_DOUBLE) && (oper->gtOper == GT_CAST) &&
!varTypeIsLong(oper->AsCast()->CastOp()))
{
// optimization: conv.r4(conv.r8(?)) -> conv.r4(d)
// except when the ultimate source is a long because there is no long-to-float helper, so it must be 2 step.
// This happens semi-frequently because there is no IL 'conv.r4.un'
oper->gtType = TYP_FLOAT;
oper->CastToType() = TYP_FLOAT;
return fgMorphTree(oper);
}
// converts long/ulong --> float/double casts into helper calls.
else if (varTypeIsFloating(dstType) && varTypeIsLong(srcType))
{
if (dstType == TYP_FLOAT)
{
// there is only a double helper, so we
// - change the dsttype to double
// - insert a cast from double to float
// - recurse into the resulting tree
tree->CastToType() = TYP_DOUBLE;
tree->gtType = TYP_DOUBLE;
tree = gtNewCastNode(TYP_FLOAT, tree, false, TYP_FLOAT);
return fgMorphTree(tree);
}
if (tree->gtFlags & GTF_UNSIGNED)
return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper);
return fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
}
#endif // TARGET_ARM
#ifdef TARGET_AMD64
// Do we have to do two step U4/8 -> R4/8 ?
// Codegen supports the following conversion as one-step operation
// a) Long -> R4/R8
// b) U8 -> R8
//
// The following conversions are performed as two-step operations using above.
// U4 -> R4/8 = U4-> Long -> R4/8
// U8 -> R4 = U8 -> R8 -> R4
else if (tree->IsUnsigned() && varTypeIsFloating(dstType))
{
srcType = varTypeToUnsigned(srcType);
if (srcType == TYP_ULONG)
{
if (dstType == TYP_FLOAT)
{
// Codegen can handle U8 -> R8 conversion.
// U8 -> R4 = U8 -> R8 -> R4
// - change the dsttype to double
// - insert a cast from double to float
// - recurse into the resulting tree
tree->CastToType() = TYP_DOUBLE;
tree->gtType = TYP_DOUBLE;
tree = gtNewCastNode(TYP_FLOAT, tree, false, TYP_FLOAT);
return fgMorphTree(tree);
}
}
else if (srcType == TYP_UINT)
{
oper = gtNewCastNode(TYP_LONG, oper, true, TYP_LONG);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->gtFlags &= ~GTF_UNSIGNED;
}
}
#endif // TARGET_AMD64
#ifdef TARGET_X86
// Do we have to do two step U4/8 -> R4/8 ?
else if (tree->IsUnsigned() && varTypeIsFloating(dstType))
{
srcType = varTypeToUnsigned(srcType);
if (srcType == TYP_ULONG)
{
return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper);
}
else if (srcType == TYP_UINT)
{
oper = gtNewCastNode(TYP_LONG, oper, true, TYP_LONG);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->gtFlags &= ~GTF_UNSIGNED;
return fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
}
}
else if (((tree->gtFlags & GTF_UNSIGNED) == 0) && (srcType == TYP_LONG) && varTypeIsFloating(dstType))
{
oper = fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
// Since we don't have a Jit Helper that converts to a TYP_FLOAT
// we just use the one that converts to a TYP_DOUBLE
// and then add a cast to TYP_FLOAT
//
if ((dstType == TYP_FLOAT) && (oper->OperGet() == GT_CALL))
{
// Fix the return type to be TYP_DOUBLE
//
oper->gtType = TYP_DOUBLE;
// Add a Cast to TYP_FLOAT
//
tree = gtNewCastNode(TYP_FLOAT, oper, false, TYP_FLOAT);
INDEBUG(tree->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED);
return tree;
}
else
{
return oper;
}
}
#endif // TARGET_X86
else if (varTypeIsGC(srcType) != varTypeIsGC(dstType))
{
// We are casting away GC information. we would like to just
// change the type to int, however this gives the emitter fits because
// it believes the variable is a GC variable at the beginning of the
// instruction group, but is not turned non-gc by the code generator
// we fix this by copying the GC pointer to a non-gc pointer temp.
noway_assert(!varTypeIsGC(dstType) && "How can we have a cast to a GCRef here?");
// We generate an assignment to an int and then do the cast from an int. With this we avoid
// the gc problem and we allow casts to bytes, longs, etc...
unsigned lclNum = lvaGrabTemp(true DEBUGARG("Cast away GC"));
oper->gtType = TYP_I_IMPL;
GenTree* asg = gtNewTempAssign(lclNum, oper);
oper->gtType = srcType;
// do the real cast
GenTree* cast = gtNewCastNode(tree->TypeGet(), gtNewLclvNode(lclNum, TYP_I_IMPL), false, dstType);
// Generate the comma tree
oper = gtNewOperNode(GT_COMMA, tree->TypeGet(), asg, cast);
return fgMorphTree(oper);
}
// Look for narrowing casts ([u]long -> [u]int) and try to push them
// down into the operand before morphing it.
//
// It doesn't matter if this is cast is from ulong or long (i.e. if
// GTF_UNSIGNED is set) because the transformation is only applied to
// overflow-insensitive narrowing casts, which always silently truncate.
//
// Note that casts from [u]long to small integer types are handled above.
if ((srcType == TYP_LONG) && ((dstType == TYP_INT) || (dstType == TYP_UINT)))
{
// As a special case, look for overflow-sensitive casts of an AND
// expression, and see if the second operand is a small constant. Since
// the result of an AND is bound by its smaller operand, it may be
// possible to prove that the cast won't overflow, which will in turn
// allow the cast's operand to be transformed.
if (tree->gtOverflow() && (oper->OperGet() == GT_AND))
{
GenTree* andOp2 = oper->AsOp()->gtOp2;
// Special case to the special case: AND with a casted int.
if ((andOp2->OperGet() == GT_CAST) && (andOp2->AsCast()->CastOp()->OperGet() == GT_CNS_INT))
{
// gtFoldExprConst will deal with whether the cast is signed or
// unsigned, or overflow-sensitive.
andOp2 = gtFoldExprConst(andOp2);
oper->AsOp()->gtOp2 = andOp2;
}
// Look for a constant less than 2^{32} for a cast to uint, or less
// than 2^{31} for a cast to int.
int maxWidth = (dstType == TYP_UINT) ? 32 : 31;
if ((andOp2->OperGet() == GT_CNS_NATIVELONG) && ((andOp2->AsIntConCommon()->LngValue() >> maxWidth) == 0))
{
// This cast can't overflow.
tree->gtFlags &= ~(GTF_OVERFLOW | GTF_EXCEPT);
}
}
// Only apply this transformation during global morph,
// when neither the cast node nor the oper node may throw an exception
// based on the upper 32 bits.
//
if (fgGlobalMorph && !tree->gtOverflow() && !oper->gtOverflowEx())
{
// For these operations the lower 32 bits of the result only depends
// upon the lower 32 bits of the operands.
//
bool canPushCast = oper->OperIs(GT_ADD, GT_SUB, GT_MUL, GT_AND, GT_OR, GT_XOR, GT_NOT, GT_NEG);
// For long LSH cast to int, there is a discontinuity in behavior
// when the shift amount is 32 or larger.
//
// CAST(INT, LSH(1LL, 31)) == LSH(1, 31)
// LSH(CAST(INT, 1LL), CAST(INT, 31)) == LSH(1, 31)
//
// CAST(INT, LSH(1LL, 32)) == 0
// LSH(CAST(INT, 1LL), CAST(INT, 32)) == LSH(1, 32) == LSH(1, 0) == 1
//
// So some extra validation is needed.
//
if (oper->OperIs(GT_LSH))
{
GenTree* shiftAmount = oper->AsOp()->gtOp2;
// Expose constant value for shift, if possible, to maximize the number
// of cases we can handle.
shiftAmount = gtFoldExpr(shiftAmount);
oper->AsOp()->gtOp2 = shiftAmount;
#if DEBUG
// We may remorph the shift amount tree again later, so clear any morphed flag.
shiftAmount->gtDebugFlags &= ~GTF_DEBUG_NODE_MORPHED;
#endif // DEBUG
if (shiftAmount->IsIntegralConst())
{
const ssize_t shiftAmountValue = shiftAmount->AsIntCon()->IconValue();
if ((shiftAmountValue >= 64) || (shiftAmountValue < 0))
{
// Shift amount is large enough or negative so result is undefined.
// Don't try to optimize.
assert(!canPushCast);
}
else if (shiftAmountValue >= 32)
{
// We know that we have a narrowing cast ([u]long -> [u]int)
// and that we are casting to a 32-bit value, which will result in zero.
//
// Check to see if we have any side-effects that we must keep
//
if ((tree->gtFlags & GTF_ALL_EFFECT) == 0)
{
// Result of the shift is zero.
DEBUG_DESTROY_NODE(tree);
GenTree* zero = gtNewZeroConNode(TYP_INT);
return fgMorphTree(zero);
}
else // We do have a side-effect
{
// We could create a GT_COMMA node here to keep the side-effect and return a zero
// Instead we just don't try to optimize this case.
canPushCast = false;
}
}
else
{
// Shift amount is positive and small enough that we can push the cast through.
canPushCast = true;
}
}
else
{
// Shift amount is unknown. We can't optimize this case.
assert(!canPushCast);
}
}
if (canPushCast)
{
DEBUG_DESTROY_NODE(tree);
// Insert narrowing casts for op1 and op2.
oper->AsOp()->gtOp1 = gtNewCastNode(TYP_INT, oper->AsOp()->gtOp1, false, dstType);
if (oper->AsOp()->gtOp2 != nullptr)
{
oper->AsOp()->gtOp2 = gtNewCastNode(TYP_INT, oper->AsOp()->gtOp2, false, dstType);
}
// Clear the GT_MUL_64RSLT if it is set.
if (oper->gtOper == GT_MUL && (oper->gtFlags & GTF_MUL_64RSLT))
{
oper->gtFlags &= ~GTF_MUL_64RSLT;
}
// The operation now produces a 32-bit result.
oper->gtType = TYP_INT;
// Remorph the new tree as the casts that we added may be folded away.
return fgMorphTree(oper);
}
}
}
OPTIMIZECAST:
noway_assert(tree->gtOper == GT_CAST);
/* Morph the operand */
tree->AsCast()->CastOp() = oper = fgMorphTree(oper);
/* Reset the call flag */
tree->gtFlags &= ~GTF_CALL;
/* Reset the assignment flag */
tree->gtFlags &= ~GTF_ASG;
/* unless we have an overflow cast, reset the except flag */
if (!tree->gtOverflow())
{
tree->gtFlags &= ~GTF_EXCEPT;
}
/* Just in case new side effects were introduced */
tree->gtFlags |= (oper->gtFlags & GTF_ALL_EFFECT);
if (!gtIsActiveCSE_Candidate(tree) && !gtIsActiveCSE_Candidate(oper))
{
srcType = oper->TypeGet();
/* See if we can discard the cast */
if (varTypeIsIntegral(srcType) && varTypeIsIntegral(dstType))
{
if (tree->IsUnsigned() && !varTypeIsUnsigned(srcType))
{
if (varTypeIsSmall(srcType))
{
// Small signed values are automatically sign extended to TYP_INT. If the cast is interpreting the
// resulting TYP_INT value as unsigned then the "sign" bits end up being "value" bits and srcType
// must be TYP_UINT, not the original small signed type. Otherwise "conv.ovf.i2.un(i1(-1))" is
// wrongly treated as a widening conversion from i1 to i2 when in fact it is a narrowing conversion
// from u4 to i2.
srcType = genActualType(srcType);
}
srcType = varTypeToUnsigned(srcType);
}
if (srcType == dstType)
{ // Certainly if they are identical it is pointless
goto REMOVE_CAST;
}
if (oper->OperGet() == GT_LCL_VAR && varTypeIsSmall(dstType))
{
unsigned varNum = oper->AsLclVarCommon()->GetLclNum();
LclVarDsc* varDsc = &lvaTable[varNum];
if (varDsc->TypeGet() == dstType && varDsc->lvNormalizeOnStore())
{
goto REMOVE_CAST;
}
}
bool unsignedSrc = varTypeIsUnsigned(srcType);
bool unsignedDst = varTypeIsUnsigned(dstType);
bool signsDiffer = (unsignedSrc != unsignedDst);
unsigned srcSize = genTypeSize(srcType);
// For same sized casts with
// the same signs or non-overflow cast we discard them as well
if (srcSize == dstSize)
{
/* This should have been handled above */
noway_assert(varTypeIsGC(srcType) == varTypeIsGC(dstType));
if (!signsDiffer)
{
goto REMOVE_CAST;
}
if (!tree->gtOverflow())
{
/* For small type casts, when necessary we force
the src operand to the dstType and allow the
implied load from memory to perform the casting */
if (varTypeIsSmall(srcType))
{
switch (oper->gtOper)
{
case GT_IND:
case GT_CLS_VAR:
case GT_LCL_FLD:
case GT_ARR_ELEM:
oper->gtType = dstType;
// We're changing the type here so we need to update the VN;
// in other cases we discard the cast without modifying oper
// so the VN doesn't change.
oper->SetVNsFromNode(tree);
goto REMOVE_CAST;
default:
break;
}
}
else
{
goto REMOVE_CAST;
}
}
}
else if (srcSize < dstSize) // widening cast
{
// Keep any long casts
if (dstSize == sizeof(int))
{
// Only keep signed to unsigned widening cast with overflow check
if (!tree->gtOverflow() || !unsignedDst || unsignedSrc)
{
goto REMOVE_CAST;
}
}
// Widening casts from unsigned or to signed can never overflow
if (unsignedSrc || !unsignedDst)
{
tree->gtFlags &= ~GTF_OVERFLOW;
if (!(oper->gtFlags & GTF_EXCEPT))
{
tree->gtFlags &= ~GTF_EXCEPT;
}
}
}
else // if (srcSize > dstSize)
{
// Try to narrow the operand of the cast and discard the cast
// Note: Do not narrow a cast that is marked as a CSE
// And do not narrow if the oper is marked as a CSE either
//
if (!tree->gtOverflow() && !gtIsActiveCSE_Candidate(oper) && (opts.compFlags & CLFLG_TREETRANS) &&
optNarrowTree(oper, srcType, dstType, tree->gtVNPair, false))
{
optNarrowTree(oper, srcType, dstType, tree->gtVNPair, true);
/* If oper is changed into a cast to TYP_INT, or to a GT_NOP, we may need to discard it */
if (oper->gtOper == GT_CAST && oper->CastToType() == genActualType(oper->CastFromType()))
{
oper = oper->AsCast()->CastOp();
}
goto REMOVE_CAST;
}
}
}
switch (oper->gtOper)
{
/* If the operand is a constant, we'll fold it */
case GT_CNS_INT:
case GT_CNS_LNG:
case GT_CNS_DBL:
case GT_CNS_STR:
{
GenTree* oldTree = tree;
tree = gtFoldExprConst(tree); // This may not fold the constant (NaN ...)
// Did we get a comma throw as a result of gtFoldExprConst?
if ((oldTree != tree) && (oldTree->gtOper != GT_COMMA))
{
noway_assert(fgIsCommaThrow(tree));
tree->AsOp()->gtOp1 = fgMorphTree(tree->AsOp()->gtOp1);
fgMorphTreeDone(tree);
return tree;
}
else if (tree->gtOper != GT_CAST)
{
return tree;
}
noway_assert(tree->AsCast()->CastOp() == oper); // unchanged
}
break;
case GT_CAST:
/* Check for two consecutive casts into the same dstType */
if (!tree->gtOverflow())
{
var_types dstType2 = oper->CastToType();
if (dstType == dstType2)
{
goto REMOVE_CAST;
}
}
break;
case GT_COMMA:
// Check for cast of a GT_COMMA with a throw overflow
// Bug 110829: Since this optimization will bash the types
// neither oper or commaOp2 can be CSE candidates
if (fgIsCommaThrow(oper) && !gtIsActiveCSE_Candidate(oper)) // oper can not be a CSE candidate
{
GenTree* commaOp2 = oper->AsOp()->gtOp2;
if (!gtIsActiveCSE_Candidate(commaOp2)) // commaOp2 can not be a CSE candidate
{
// need type of oper to be same as tree
if (tree->gtType == TYP_LONG)
{
commaOp2->ChangeOperConst(GT_CNS_NATIVELONG);
commaOp2->AsIntConCommon()->SetLngValue(0);
/* Change the types of oper and commaOp2 to TYP_LONG */
oper->gtType = commaOp2->gtType = TYP_LONG;
}
else if (varTypeIsFloating(tree->gtType))
{
commaOp2->ChangeOperConst(GT_CNS_DBL);
commaOp2->AsDblCon()->gtDconVal = 0.0;
// Change the types of oper and commaOp2
oper->gtType = commaOp2->gtType = tree->gtType;
}
else
{
commaOp2->ChangeOperConst(GT_CNS_INT);
commaOp2->AsIntCon()->gtIconVal = 0;
/* Change the types of oper and commaOp2 to TYP_INT */
oper->gtType = commaOp2->gtType = TYP_INT;
}
}
if (vnStore != nullptr)
{
fgValueNumberTreeConst(commaOp2);
}
/* Return the GT_COMMA node as the new tree */
return oper;
}
break;
default:
break;
} /* end switch (oper->gtOper) */
}
if (tree->gtOverflow())
{
fgAddCodeRef(compCurBB, bbThrowIndex(compCurBB), SCK_OVERFLOW);
}
return tree;
REMOVE_CAST:
/* Here we've eliminated the cast, so just return it's operand */
assert(!gtIsActiveCSE_Candidate(tree)); // tree cannot be a CSE candidate
DEBUG_DESTROY_NODE(tree);
return oper;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
#ifdef DEBUG
void fgArgTabEntry::Dump() const
{
printf("fgArgTabEntry[arg %u", argNum);
printf(" %d.%s", GetNode()->gtTreeID, GenTree::OpName(GetNode()->OperGet()));
printf(" %s", varTypeName(argType));
printf(" (%s)", passedByRef ? "By ref" : "By value");
if (GetRegNum() != REG_STK)
{
printf(", %u reg%s:", numRegs, numRegs == 1 ? "" : "s");
for (unsigned i = 0; i < numRegs; i++)
{
printf(" %s", getRegName(regNums[i]));
}
}
if (GetStackByteSize() > 0)
{
#if defined(DEBUG_ARG_SLOTS)
printf(", numSlots=%u, slotNum=%u, byteSize=%u, byteOffset=%u", numSlots, slotNum, m_byteSize, m_byteOffset);
#else
printf(", byteSize=%u, byteOffset=%u", m_byteSize, m_byteOffset);
#endif
}
printf(", byteAlignment=%u", m_byteAlignment);
if (isLateArg())
{
printf(", lateArgInx=%u", GetLateArgInx());
}
if (IsSplit())
{
printf(", isSplit");
}
if (needTmp)
{
printf(", tmpNum=V%02u", tmpNum);
}
if (needPlace)
{
printf(", needPlace");
}
if (isTmp)
{
printf(", isTmp");
}
if (processed)
{
printf(", processed");
}
if (IsHfaRegArg())
{
printf(", isHfa(%s)", varTypeName(GetHfaType()));
}
if (isBackFilled)
{
printf(", isBackFilled");
}
if (isNonStandard)
{
printf(", isNonStandard");
}
if (isStruct)
{
printf(", isStruct");
}
printf("]\n");
}
#endif
fgArgInfo::fgArgInfo(Compiler* comp, GenTreeCall* call, unsigned numArgs)
{
compiler = comp;
callTree = call;
argCount = 0; // filled in arg count, starts at zero
DEBUG_ARG_SLOTS_ONLY(nextSlotNum = INIT_ARG_STACK_SLOT;)
nextStackByteOffset = INIT_ARG_STACK_SLOT * TARGET_POINTER_SIZE;
stkLevel = 0;
#if defined(UNIX_X86_ABI)
alignmentDone = false;
stkSizeBytes = 0;
padStkAlign = 0;
#endif
#if FEATURE_FIXED_OUT_ARGS
outArgSize = 0;
#endif
argTableSize = numArgs; // the allocated table size
hasRegArgs = false;
hasStackArgs = false;
argsComplete = false;
argsSorted = false;
needsTemps = false;
if (argTableSize == 0)
{
argTable = nullptr;
}
else
{
argTable = new (compiler, CMK_fgArgInfoPtrArr) fgArgTabEntry*[argTableSize];
}
}
/*****************************************************************************
*
* fgArgInfo Copy Constructor
*
* This method needs to act like a copy constructor for fgArgInfo.
* The newCall needs to have its fgArgInfo initialized such that
* we have newCall that is an exact copy of the oldCall.
* We have to take care since the argument information
* in the argTable contains pointers that must point to the
* new arguments and not the old arguments.
*/
fgArgInfo::fgArgInfo(GenTreeCall* newCall, GenTreeCall* oldCall)
{
fgArgInfo* oldArgInfo = oldCall->AsCall()->fgArgInfo;
compiler = oldArgInfo->compiler;
callTree = newCall;
argCount = 0; // filled in arg count, starts at zero
DEBUG_ARG_SLOTS_ONLY(nextSlotNum = INIT_ARG_STACK_SLOT;)
nextStackByteOffset = INIT_ARG_STACK_SLOT * TARGET_POINTER_SIZE;
stkLevel = oldArgInfo->stkLevel;
#if defined(UNIX_X86_ABI)
alignmentDone = oldArgInfo->alignmentDone;
stkSizeBytes = oldArgInfo->stkSizeBytes;
padStkAlign = oldArgInfo->padStkAlign;
#endif
#if FEATURE_FIXED_OUT_ARGS
outArgSize = oldArgInfo->outArgSize;
#endif
argTableSize = oldArgInfo->argTableSize;
argsComplete = false;
argTable = nullptr;
assert(oldArgInfo->argsComplete);
if (argTableSize > 0)
{
argTable = new (compiler, CMK_fgArgInfoPtrArr) fgArgTabEntry*[argTableSize];
// Copy the old arg entries
for (unsigned i = 0; i < argTableSize; i++)
{
argTable[i] = new (compiler, CMK_fgArgInfo) fgArgTabEntry(*oldArgInfo->argTable[i]);
}
// The copied arg entries contain pointers to old uses, they need
// to be updated to point to new uses.
if (newCall->gtCallThisArg != nullptr)
{
for (unsigned i = 0; i < argTableSize; i++)
{
if (argTable[i]->use == oldCall->gtCallThisArg)
{
argTable[i]->use = newCall->gtCallThisArg;
break;
}
}
}
GenTreeCall::UseIterator newUse = newCall->Args().begin();
GenTreeCall::UseIterator newUseEnd = newCall->Args().end();
GenTreeCall::UseIterator oldUse = oldCall->Args().begin();
GenTreeCall::UseIterator oldUseEnd = newCall->Args().end();
for (; newUse != newUseEnd; ++newUse, ++oldUse)
{
for (unsigned i = 0; i < argTableSize; i++)
{
if (argTable[i]->use == oldUse.GetUse())
{
argTable[i]->use = newUse.GetUse();
break;
}
}
}
newUse = newCall->LateArgs().begin();
newUseEnd = newCall->LateArgs().end();
oldUse = oldCall->LateArgs().begin();
oldUseEnd = newCall->LateArgs().end();
for (; newUse != newUseEnd; ++newUse, ++oldUse)
{
for (unsigned i = 0; i < argTableSize; i++)
{
if (argTable[i]->lateUse == oldUse.GetUse())
{
argTable[i]->lateUse = newUse.GetUse();
break;
}
}
}
}
argCount = oldArgInfo->argCount;