-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
morph.cpp
17696 lines (15484 loc) · 657 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->OperIsConst())
{
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, true /* morphArgs */, oper);
assert(result == tree);
return result;
}
/*****************************************************************************
*
* Convert the given node into a call to the specified helper passing
* the given argument list.
*/
//------------------------------------------------------------------------
// fgMorphIntoHelperCall:
// Morph a node into a helper call, specifying up to two args and whether to
// call fgMorphArgs after.
//
// Parameters:
// tree - The node that is changed. This must be a large node.
// helper - The helper.
// morphArgs - Whether to call fgMorphArgs after adding the args.
// arg1, arg2 - Optional arguments to add to the call.
//
// Return value:
// The call (which is the same as `tree`).
//
GenTree* Compiler::fgMorphIntoHelperCall(GenTree* tree, int helper, bool morphArgs, GenTree* arg1, GenTree* arg2)
{
// 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();
// Args are cleared by ChangeOper above
call->gtCallType = CT_HELPER;
call->gtReturnType = tree->TypeGet();
call->gtCallMethHnd = eeFindHelper(helper);
call->gtRetClsHnd = nullptr;
call->gtCallMoreFlags = GTF_CALL_M_EMPTY;
call->gtInlineCandidateInfo = nullptr;
call->gtControlExpr = nullptr;
#ifdef UNIX_X86_ABI
call->gtFlags |= GTF_CALL_POP_ARGS;
#endif // UNIX_X86_ABI
#if DEBUG
// Helper calls are never candidates.
call->gtInlineObservation = InlineObservation::CALLSITE_IS_CALL_TO_HELPER;
call->callSig = nullptr;
#endif // DEBUG
#ifdef FEATURE_READYTORUN
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 (call->OperMayThrow(this))
{
call->gtFlags |= GTF_EXCEPT;
}
else
{
call->gtFlags &= ~GTF_EXCEPT;
}
call->gtFlags |= GTF_CALL;
if (arg2 != nullptr)
{
call->gtArgs.PushFront(this, NewCallArg::Primitive(arg2));
call->gtFlags |= arg2->gtFlags & GTF_ALL_EFFECT;
}
if (arg1 != nullptr)
{
call->gtArgs.PushFront(this, NewCallArg::Primitive(arg1));
call->gtFlags |= arg1->gtFlags & GTF_ALL_EFFECT;
}
// Perform the morphing
if (morphArgs)
{
tree = fgMorphArgs(call);
}
return tree;
}
//------------------------------------------------------------------------
// fgMorphExpandCast: Performs the pre-order (required) morphing for a cast.
//
// Performs a rich variety of pre-order transformations (and some optimizations).
//
// Notably:
// 1. Splits long -> small type casts into long -> int -> small type
// for 32 bit targets. Does the same for float/double -> small type
// casts for all targets.
// 2. Morphs casts not supported by the target directly into helpers.
// These mostly have to do with casts from and to floating point
// types, especially checked ones. Refer to the implementation for
// what specific casts need to be handled - it is a complex matrix.
// 3. "Casts away" the GC-ness of a tree (for CAST(nint <- byref)) via
// assigning the GC tree to an inline - COMMA(ASG, LCL_VAR) - non-GC
// temporary.
// 3. "Pushes down" truncating long -> int casts for some operations:
// CAST(int <- MUL(long, long)) => MUL(CAST(int <- long), CAST(int <- long)).
// The purpose of this is to allow "optNarrowTree" in the post-order
// traversal to fold the tree into a TYP_INT one, which helps 32 bit
// targets (and AMD64 too since 32 bit instructions are more compact).
// TODO-Arm64-CQ: Re-evaluate the value of this optimization for ARM64.
//
// Arguments:
// tree - the cast tree to morph
//
// Return Value:
// The fully morphed tree, or "nullptr" if it needs further morphing,
// in which case the cast may be transformed into an unchecked one
// and its operand changed (the cast "expanded" into two).
//
GenTree* Compiler::fgMorphExpandCast(GenTreeCast* tree)
{
GenTree* oper = tree->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);
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) || defined(TARGET_LOONGARCH64)
// 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?
if (dstSize < genTypeSize(TYP_INT))
{
oper = gtNewCastNodeL(TYP_INT, oper, /* fromUnsigned */ false, TYP_INT);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->AsCast()->CastOp() = oper;
// 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
{
if (!tree->gtOverflow())
{
// ARM64 and LoongArch64 optimize all non-overflow checking conversions
#if defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
return nullptr;
#else
switch (dstType)
{
case TYP_INT:
return nullptr;
case TYP_UINT:
#if defined(TARGET_ARM) || defined(TARGET_AMD64)
return nullptr;
#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
return nullptr;
#else // !TARGET_AMD64
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG, oper);
#endif // !TARGET_AMD64
case TYP_ULONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG, oper);
default:
unreached();
}
#endif // TARGET_ARM64 || TARGET_LOONGARCH64
}
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:
unreached();
}
}
}
}
#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->ClearUnsigned();
tree->AsCast()->CastOp() = oper;
}
#endif //! TARGET_64BIT
#ifdef TARGET_ARMARCH
// AArch, unlike x86/amd64, has instructions that can cast directly from
// all integers (except for longs on AArch32 of course) to floats.
// Because there is no IL instruction conv.r4.un, uint/ulong -> float
// casts are always imported as CAST(float <- CAST(double <- uint/ulong)).
// We can eliminate the redundant intermediate cast as an optimization.
else if ((dstType == TYP_FLOAT) && (srcType == TYP_DOUBLE) && oper->OperIs(GT_CAST)
#ifdef TARGET_ARM
&& !varTypeIsLong(oper->AsCast()->CastOp())
#endif
)
{
oper->gtType = TYP_FLOAT;
oper->CastToType() = TYP_FLOAT;
return fgMorphTree(oper);
}
#endif // TARGET_ARMARCH
#ifdef TARGET_ARM
// 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->ClearUnsigned();
tree->CastOp() = oper;
}
}
#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;
// 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))
{
tree->ClearOverflow();
tree->SetAllEffectsFlags(oper);
}
}
// 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);
}
}
}
return nullptr;
}
#ifdef DEBUG
//------------------------------------------------------------------------
// getWellKnownArgName: Get a string representation of a WellKnownArg.
//
const char* getWellKnownArgName(WellKnownArg arg)
{
switch (arg)
{
case WellKnownArg::None:
return "None";
case WellKnownArg::ThisPointer:
return "ThisPointer";
case WellKnownArg::VarArgsCookie:
return "VarArgsCookie";
case WellKnownArg::InstParam:
return "InstParam";
case WellKnownArg::RetBuffer:
return "RetBuffer";
case WellKnownArg::PInvokeFrame:
return "PInvokeFrame";
case WellKnownArg::SecretStubParam:
return "SecretStubParam";
case WellKnownArg::WrapperDelegateCell:
return "WrapperDelegateCell";
case WellKnownArg::ShiftLow:
return "ShiftLow";
case WellKnownArg::ShiftHigh:
return "ShiftHigh";
case WellKnownArg::VirtualStubCell:
return "VirtualStubCell";
case WellKnownArg::PInvokeCookie:
return "PInvokeCookie";
case WellKnownArg::PInvokeTarget:
return "PInvokeTarget";
case WellKnownArg::R2RIndirectionCell:
return "R2RIndirectionCell";
case WellKnownArg::ValidateIndirectCallTarget:
return "ValidateIndirectCallTarget";
case WellKnownArg::DispatchIndirectCallTarget:
return "DispatchIndirectCallTarget";
}
return "N/A";
}
//------------------------------------------------------------------------
// Dump: Dump information about a CallArg to jitstdout.
//
void CallArg::Dump(Compiler* comp)
{
printf("CallArg[[%06u].%s", comp->dspTreeID(GetNode()), GenTree::OpName(GetNode()->OperGet()));
printf(" %s", varTypeName(m_signatureType));
printf(" (%s)", AbiInfo.PassedByRef ? "By ref" : "By value");
if (AbiInfo.GetRegNum() != REG_STK)
{
printf(", %u reg%s:", AbiInfo.NumRegs, AbiInfo.NumRegs == 1 ? "" : "s");
for (unsigned i = 0; i < AbiInfo.NumRegs; i++)
{
printf(" %s", getRegName(AbiInfo.GetRegNum(i)));
}
}
if (AbiInfo.GetStackByteSize() > 0)
{
printf(", byteSize=%u, byteOffset=%u", AbiInfo.ByteSize, AbiInfo.ByteOffset);
}
printf(", byteAlignment=%u", AbiInfo.ByteAlignment);
if (GetLateNode() != nullptr)
{
printf(", isLate");
}
if (AbiInfo.IsSplit())
{
printf(", isSplit");
}
if (m_needTmp)
{
printf(", tmpNum=V%02u", m_tmpNum);
}
if (m_needPlace)
{
printf(", needPlace");
}
if (m_isTmp)
{
printf(", isTmp");
}
if (m_processed)
{
printf(", processed");
}
if (AbiInfo.IsHfaRegArg())
{
printf(", isHfa(%s)", varTypeName(AbiInfo.GetHfaType()));
}
if (AbiInfo.IsBackFilled)
{
printf(", isBackFilled");
}
if (m_wellKnownArg != WellKnownArg::None)
{
printf(", wellKnown[%s]", getWellKnownArgName(m_wellKnownArg));
}
if (AbiInfo.IsStruct)
{
printf(", isStruct");
}
printf("]\n");
}
#endif
//------------------------------------------------------------------------
// SplitArg:
// Record that the arg will be split over registers and stack, increasing the
// current stack usage.
//
// Parameters:
// arg - The argument.
// numRegs - The number of registers that will be used.
// numSlots - The number of stack slots that will be used.
//
void CallArgs::SplitArg(CallArg* arg, unsigned numRegs, unsigned numSlots)
{
assert(numRegs > 0);
assert(numSlots > 0);
if (m_argsComplete)
{
assert(arg->AbiInfo.IsSplit() == true);
assert(arg->AbiInfo.NumRegs == numRegs);
assert(m_hasStackArgs);
}
else
{
arg->AbiInfo.SetSplit(true);
arg->AbiInfo.NumRegs = numRegs;
arg->AbiInfo.ByteOffset = 0;
m_hasStackArgs = true;
}
m_nextStackByteOffset += numSlots * TARGET_POINTER_SIZE;
}
//------------------------------------------------------------------------
// SetTemp: Set that the specified argument was evaluated into a temp.
//
void CallArgs::SetTemp(CallArg* arg, unsigned tmpNum)
{
arg->m_tmpNum = tmpNum;
arg->m_isTmp = true;
}
//------------------------------------------------------------------------
// ArgsComplete: Make final decisions on which arguments to evaluate into temporaries.
//
void CallArgs::ArgsComplete(Compiler* comp, GenTreeCall* call)
{
bool hasStructRegArg = false;
unsigned argCount = CountArgs();
for (CallArg& arg : Args())
{
GenTree* argx = arg.GetEarlyNode();
if (argx == nullptr)
{
// Should only happen if remorphing in which case we do not need to
// make a decision about temps.
continue;
}
if (arg.AbiInfo.GetRegNum() == REG_STK)
{
assert(m_hasStackArgs);
#if !FEATURE_FIXED_OUT_ARGS
// On x86 we use push instructions to pass arguments:
// The non-register arguments are evaluated and pushed in order
// and they are never evaluated into temps
//
continue;
#endif
}
#if FEATURE_ARG_SPLIT
else if (arg.AbiInfo.IsSplit())
{
hasStructRegArg = true;
assert(m_hasStackArgs);
}
#endif // FEATURE_ARG_SPLIT
else // we have a register argument, next we look for a struct type.
{
if (varTypeIsStruct(argx) UNIX_AMD64_ABI_ONLY(|| arg.AbiInfo.IsStruct))
{
hasStructRegArg = true;
}
}
/* If the argument tree contains an assignment (GTF_ASG) then the argument and
and every earlier argument (except constants) must be evaluated into temps
since there may be other arguments that follow and they may use the value being assigned.
EXAMPLE: ArgTab is "a, a=5, a"
-> when we see the second arg "a=5"
we know the first two arguments "a, a=5" have to be evaluated into temps
For the case of an assignment, we only know that there exist some assignment someplace
in the tree. We don't know what is being assigned so we are very conservative here
and assume that any local variable could have been assigned.
*/
if (argx->gtFlags & GTF_ASG)
{
// If this is not the only argument, or it's a copyblk, or it already evaluates the expression to
// a tmp, then we need a temp in the late arg list.
if ((argCount > 1) || argx->OperIsCopyBlkOp()
#ifdef FEATURE_FIXED_OUT_ARGS
|| arg.m_isTmp // Protect this by "FEATURE_FIXED_OUT_ARGS" to preserve the property
// that we only have late non-register args when that feature is on.
#endif
)
{
SetNeedsTemp(&arg);
}
// For all previous arguments, unless they are a simple constant
// we require that they be evaluated into temps
for (CallArg& prevArg : Args())
{
if (&prevArg == &arg)
{
break;
}
if ((prevArg.GetEarlyNode() != nullptr) && !prevArg.GetEarlyNode()->IsInvariant())
{
SetNeedsTemp(&prevArg);
}
}
}
bool treatLikeCall = ((argx->gtFlags & GTF_CALL) != 0);
#if FEATURE_FIXED_OUT_ARGS
// Like calls, if this argument has a tree that will do an inline throw,
// a call to a jit helper, then we need to treat it like a call (but only
// if there are/were any stack args).
// This means unnesting, sorting, etc. Technically this is overly
// conservative, but I want to avoid as much special-case debug-only code
// as possible, so leveraging the GTF_CALL flag is the easiest.
//
if (!treatLikeCall && (argx->gtFlags & GTF_EXCEPT) && (argCount > 1) && comp->opts.compDbgCode &&
(comp->fgWalkTreePre(&argx, Compiler::fgChkThrowCB) == Compiler::WALK_ABORT))
{
for (CallArg& otherArg : Args())
{
if (&otherArg == &arg)
{
continue;
}
if (otherArg.AbiInfo.GetRegNum() == REG_STK)
{
treatLikeCall = true;
break;
}
}
}
#endif // FEATURE_FIXED_OUT_ARGS
/* If it contains a call (GTF_CALL) then itself and everything before the call
with a GLOB_EFFECT must eval to temp (this is because everything with SIDE_EFFECT
has to be kept in the right order since we will move the call to the first position)
For calls we don't have to be quite as conservative as we are with an assignment
since the call won't be modifying any non-address taken LclVars.
*/
if (treatLikeCall)
{
if (argCount > 1) // If this is not the only argument
{
SetNeedsTemp(&arg);
}
else if (varTypeIsFloating(argx->TypeGet()) && (argx->OperGet() == GT_CALL))
{
// Spill all arguments that are floating point calls
SetNeedsTemp(&arg);
}
// All previous arguments may need to be evaluated into temps
for (CallArg& prevArg : Args())
{
if (&prevArg == &arg)
{
break;
}
// For all previous arguments, if they have any GTF_ALL_EFFECT
// we require that they be evaluated into a temp
if ((prevArg.GetEarlyNode() != nullptr) && ((prevArg.GetEarlyNode()->gtFlags & GTF_ALL_EFFECT) != 0))
{
SetNeedsTemp(&prevArg);
}
#if FEATURE_FIXED_OUT_ARGS
// Or, if they are stored into the FIXED_OUT_ARG area
// we require that they be moved to the gtCallLateArgs
// and replaced with a placeholder node
else if (prevArg.AbiInfo.GetRegNum() == REG_STK)
{
prevArg.m_needPlace = true;
}
#if FEATURE_ARG_SPLIT
else if (prevArg.AbiInfo.IsSplit())
{
prevArg.m_needPlace = true;
}
#endif // FEATURE_ARG_SPLIT
#endif
}
}
#if FEATURE_MULTIREG_ARGS
// For RyuJIT backend we will expand a Multireg arg into a GT_FIELD_LIST
// with multiple indirections, so here we consider spilling it into a tmp LclVar.
//
CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef TARGET_ARM
bool isMultiRegArg = (arg.AbiInfo.NumRegs > 0) && (arg.AbiInfo.NumRegs + arg.AbiInfo.GetStackSlotsNumber() > 1);
#else
bool isMultiRegArg = (arg.AbiInfo.NumRegs > 1);
#endif
if (varTypeIsStruct(argx->TypeGet()) && !arg.m_needTmp)
{
if (isMultiRegArg && ((argx->gtFlags & GTF_PERSISTENT_SIDE_EFFECTS) != 0))
{
// Spill multireg struct arguments that have Assignments or Calls embedded in them
SetNeedsTemp(&arg);
}
else
{
// We call gtPrepareCost to measure the cost of evaluating this tree
comp->gtPrepareCost(argx);
if (isMultiRegArg && (argx->GetCostEx() > (6 * IND_COST_EX)))
{
// Spill multireg struct arguments that are expensive to evaluate twice
SetNeedsTemp(&arg);
}
#if defined(FEATURE_SIMD) && defined(TARGET_ARM64)
else if (isMultiRegArg && varTypeIsSIMD(argx->TypeGet()))
{
// SIMD types do not need the optimization below due to their sizes
if (argx->OperIsSimdOrHWintrinsic() ||
(argx->OperIs(GT_OBJ) && argx->AsObj()->gtOp1->OperIs(GT_ADDR) &&
argx->AsObj()->gtOp1->AsOp()->gtOp1->OperIsSimdOrHWintrinsic()))
{
SetNeedsTemp(&arg);
}
}
#endif
#ifndef TARGET_ARM
// TODO-Arm: This optimization is not implemented for ARM32
// so we skip this for ARM32 until it is ported to use RyuJIT backend
//
else if (argx->OperGet() == GT_OBJ)
{
GenTreeObj* argObj = argx->AsObj();
unsigned structSize = argObj->GetLayout()->GetSize();
switch (structSize)
{
case 3:
case 5:
case 6:
case 7:
// If we have a stack based LclVar we can perform a wider read of 4 or 8 bytes
//
if (argObj->AsObj()->gtOp1->IsLocalAddrExpr() == nullptr) // Is the source not a LclVar?
{
// If we don't have a LclVar we need to read exactly 3,5,6 or 7 bytes
// For now we use a GT_CPBLK to copy the exact size into a GT_LCL_VAR temp.
//
SetNeedsTemp(&arg);
}
break;
case 11:
case 13:
case 14:
case 15:
// Spill any GT_OBJ multireg structs that are difficult to extract
//
// When we have a GT_OBJ of a struct with the above sizes we would need
// to use 3 or 4 load instructions to load the exact size of this struct.
// Instead we spill the GT_OBJ into a new GT_LCL_VAR temp and this sequence
// will use a GT_CPBLK to copy the exact size into the GT_LCL_VAR temp.
// Then we can just load all 16 bytes of the GT_LCL_VAR temp when passing
// the argument.
//
SetNeedsTemp(&arg);
break;
default:
break;
}
}
#endif // !TARGET_ARM
}
}
#endif // FEATURE_MULTIREG_ARGS
}
// We only care because we can't spill structs and qmarks involve a lot of spilling, but
// if we don't have qmarks, then it doesn't matter.
// So check for Qmark's globally once here, instead of inside the loop.
//