-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
lowerxarch.cpp
9727 lines (8357 loc) · 359 KB
/
lowerxarch.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 Lowering for AMD64, x86 XX
XX XX
XX This encapsulates all the logic for lowering trees for the AMD64 XX
XX architecture. For a more detailed view of what is lowering, please XX
XX take a look at Lower.cpp XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifdef TARGET_XARCH // This file is only used for xarch
#include "jit.h"
#include "sideeffects.h"
#include "lower.h"
// xarch supports both ROL and ROR instructions so no lowering is required.
void Lowering::LowerRotate(GenTree* tree)
{
ContainCheckShiftRotate(tree->AsOp());
}
//------------------------------------------------------------------------
// LowerStoreLoc: Lower a store of a lclVar
//
// Arguments:
// storeLoc - the local store (GT_STORE_LCL_FLD or GT_STORE_LCL_VAR)
//
// Notes:
// This involves:
// - Handling of contained immediates.
// - Widening some small stores.
//
void Lowering::LowerStoreLoc(GenTreeLclVarCommon* storeLoc)
{
// Most small locals (the exception is dependently promoted fields) have 4 byte wide stack slots, so
// we can widen the store, if profitable. The widening is only (largely) profitable for 2 byte stores.
// We could widen bytes too but that would only be better when the constant is zero and reused, which
// we presume is not common enough.
//
if (storeLoc->OperIs(GT_STORE_LCL_VAR) && (genTypeSize(storeLoc) == 2) && storeLoc->Data()->IsCnsIntOrI())
{
if (!comp->lvaGetDesc(storeLoc)->lvIsStructField)
{
storeLoc->gtType = TYP_INT;
}
}
if (storeLoc->OperIs(GT_STORE_LCL_FLD))
{
// We should only encounter this for lclVars that are lvDoNotEnregister.
verifyLclFldDoNotEnregister(storeLoc->GetLclNum());
}
ContainCheckStoreLoc(storeLoc);
}
//------------------------------------------------------------------------
// LowerStoreIndir: Determine addressing mode for an indirection, and whether operands are contained.
//
// Arguments:
// node - The indirect store node (GT_STORE_IND) of interest
//
// Return Value:
// None.
//
void Lowering::LowerStoreIndir(GenTreeStoreInd* node)
{
// Mark all GT_STOREIND nodes to indicate that it is not known
// whether it represents a RMW memory op.
node->SetRMWStatusDefault();
if (!varTypeIsFloating(node))
{
// Perform recognition of trees with the following structure:
// StoreInd(addr, BinOp(expr, GT_IND(addr)))
// to be able to fold this into an instruction of the form
// BINOP [addr], register
// where register is the actual place where 'expr' is computed.
//
// SSE2 doesn't support RMW form of instructions.
if (LowerRMWMemOp(node))
{
return;
}
}
// Optimization: do not unnecessarily zero-extend the result of setcc.
if (varTypeIsByte(node) && (node->Data()->OperIsCompare() || node->Data()->OperIs(GT_SETCC)))
{
node->Data()->ChangeType(TYP_BYTE);
}
ContainCheckStoreIndir(node);
}
//----------------------------------------------------------------------------------------------
// Lowering::TryLowerMulWithConstant:
// Lowers a tree MUL(X, CNS) to LSH(X, CNS_SHIFT)
// or
// Lowers a tree MUL(X, CNS) to SUB(LSH(X, CNS_SHIFT), X)
// or
// Lowers a tree MUL(X, CNS) to ADD(LSH(X, CNS_SHIFT), X)
//
// Arguments:
// node - GT_MUL node of integral type
//
// Return Value:
// Returns the replacement node if one is created else nullptr indicating no replacement
//
// Notes:
// Performs containment checks on the replacement node if one is created
GenTree* Lowering::TryLowerMulWithConstant(GenTreeOp* node)
{
assert(node->OperIs(GT_MUL));
// Do not do these optimizations when min-opts enabled.
if (comp->opts.MinOpts())
return nullptr;
if (!varTypeIsIntegral(node))
return nullptr;
if (node->gtOverflow())
return nullptr;
GenTree* op1 = node->gtGetOp1();
GenTree* op2 = node->gtGetOp2();
if (op1->isContained() || op2->isContained())
return nullptr;
if (!op2->IsCnsIntOrI())
return nullptr;
GenTreeIntConCommon* cns = op2->AsIntConCommon();
ssize_t cnsVal = cns->IconValue();
// Use GT_LEA if cnsVal is 3, 5, or 9.
// These are handled in codegen.
if (cnsVal == 3 || cnsVal == 5 || cnsVal == 9)
return nullptr;
// Use GT_LSH if cnsVal is a power of two.
if (isPow2(cnsVal))
{
// Use shift for constant multiply when legal
unsigned int shiftAmount = genLog2(static_cast<uint64_t>(static_cast<size_t>(cnsVal)));
cns->SetIconValue(shiftAmount);
node->ChangeOper(GT_LSH);
ContainCheckShiftRotate(node);
return node;
}
// We do not do this optimization in X86 as it is not recommended.
#if TARGET_X86
return nullptr;
#endif // TARGET_X86
ssize_t cnsValPlusOne = cnsVal + 1;
ssize_t cnsValMinusOne = cnsVal - 1;
bool useSub = isPow2(cnsValPlusOne);
if (!useSub && !isPow2(cnsValMinusOne))
return nullptr;
LIR::Use op1Use(BlockRange(), &node->gtOp1, node);
op1 = ReplaceWithLclVar(op1Use);
if (useSub)
{
cnsVal = cnsValPlusOne;
node->ChangeOper(GT_SUB);
}
else
{
cnsVal = cnsValMinusOne;
node->ChangeOper(GT_ADD);
}
unsigned int shiftAmount = genLog2(static_cast<uint64_t>(static_cast<size_t>(cnsVal)));
cns->SetIconValue(shiftAmount);
node->gtOp1 = comp->gtNewOperNode(GT_LSH, node->gtType, op1, cns);
node->gtOp2 = comp->gtClone(op1);
BlockRange().Remove(op1);
BlockRange().Remove(cns);
BlockRange().InsertBefore(node, node->gtGetOp2());
BlockRange().InsertBefore(node, cns);
BlockRange().InsertBefore(node, op1);
BlockRange().InsertBefore(node, node->gtGetOp1());
ContainCheckBinary(node);
ContainCheckShiftRotate(node->gtGetOp1()->AsOp());
return node;
}
//------------------------------------------------------------------------
// LowerMul: Lower a GT_MUL/GT_MULHI/GT_MUL_LONG node.
//
// Currently only performs containment checks.
//
// Arguments:
// mul - The node to lower
//
// Return Value:
// The next node to lower.
//
GenTree* Lowering::LowerMul(GenTreeOp* mul)
{
assert(mul->OperIsMul());
if (mul->OperIs(GT_MUL))
{
GenTree* replacementNode = TryLowerMulWithConstant(mul);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
ContainCheckMul(mul);
return mul->gtNext;
}
//------------------------------------------------------------------------
// LowerBinaryArithmetic: lowers the given binary arithmetic node.
//
// Recognizes opportunities for using target-independent "combined" nodes
// Performs containment checks.
//
// Arguments:
// node - the arithmetic node to lower
//
// Returns:
// The next node to lower.
//
GenTree* Lowering::LowerBinaryArithmetic(GenTreeOp* binOp)
{
#ifdef FEATURE_HW_INTRINSICS
if (comp->opts.OptimizationEnabled() && varTypeIsIntegral(binOp))
{
if (binOp->OperIs(GT_AND))
{
GenTree* replacementNode = TryLowerAndOpToAndNot(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
replacementNode = TryLowerAndOpToResetLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
replacementNode = TryLowerAndOpToExtractLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
else if (binOp->OperIs(GT_XOR))
{
GenTree* replacementNode = TryLowerXorOpToGetMaskUpToLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
}
#endif
ContainCheckBinary(binOp);
return binOp->gtNext;
}
//------------------------------------------------------------------------
// LowerBlockStore: Lower a block store node
//
// Arguments:
// blkNode - The block store node to lower
//
void Lowering::LowerBlockStore(GenTreeBlk* blkNode)
{
TryCreateAddrMode(blkNode->Addr(), false, blkNode);
GenTree* dstAddr = blkNode->Addr();
GenTree* src = blkNode->Data();
unsigned size = blkNode->Size();
if (blkNode->OperIsInitBlkOp())
{
if (src->OperIs(GT_INIT_VAL))
{
src->SetContained();
src = src->AsUnOp()->gtGetOp1();
}
if (!blkNode->OperIs(GT_STORE_DYN_BLK) && (size <= comp->getUnrollThreshold(Compiler::UnrollKind::Memset)))
{
if (!src->OperIs(GT_CNS_INT))
{
// TODO-CQ: We could unroll even when the initialization value is not a constant
// by inserting a MUL init, 0x01010101 instruction. We need to determine if the
// extra latency that MUL introduces isn't worse that rep stosb. Likely not.
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
}
else
{
// The fill value of an initblk is interpreted to hold a
// value of (unsigned int8) however a constant of any size
// may practically reside on the evaluation stack. So extract
// the lower byte out of the initVal constant and replicate
// it to a larger constant whose size is sufficient to support
// the largest width store of the desired inline expansion.
ssize_t fill = src->AsIntCon()->IconValue() & 0xFF;
const bool canUseSimd = !blkNode->IsOnHeapAndContainsReferences() && comp->IsBaselineSimdIsaSupported();
if (size > comp->getUnrollThreshold(Compiler::UnrollKind::Memset, canUseSimd))
{
// It turns out we can't use SIMD so the default threshold is too big
goto TOO_BIG_TO_UNROLL;
}
if (canUseSimd && (size >= XMM_REGSIZE_BYTES))
{
// We're going to use SIMD (and only SIMD - we don't want to occupy a GPR register
// with a fill value just to handle the remainder when we can do that with
// an overlapped SIMD load).
src->SetContained();
}
else if (fill == 0)
{
// Leave as is - zero shouldn't be contained when we don't use SIMD.
}
#ifdef TARGET_AMD64
else if (size >= REGSIZE_BYTES)
{
fill *= 0x0101010101010101LL;
src->gtType = TYP_LONG;
}
#endif
else
{
fill *= 0x01010101;
}
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll;
src->AsIntCon()->SetIconValue(fill);
ContainBlockStoreAddress(blkNode, size, dstAddr, nullptr);
}
}
else
{
TOO_BIG_TO_UNROLL:
#ifdef TARGET_AMD64
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindHelper;
#else
// TODO-X86-CQ: Investigate whether a helper call would be beneficial on x86
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
#endif
}
}
else
{
assert(src->OperIs(GT_IND, GT_LCL_VAR, GT_LCL_FLD));
src->SetContained();
if (src->OperIs(GT_LCL_VAR))
{
// TODO-1stClassStructs: for now we can't work with STORE_BLOCK source in register.
const unsigned srcLclNum = src->AsLclVar()->GetLclNum();
comp->lvaSetVarDoNotEnregister(srcLclNum DEBUGARG(DoNotEnregisterReason::StoreBlkSrc));
}
ClassLayout* layout = blkNode->GetLayout();
bool doCpObj = !blkNode->OperIs(GT_STORE_DYN_BLK) && layout->HasGCPtr();
unsigned copyBlockUnrollLimit = comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy, false);
#ifndef JIT32_GCENCODER
if (doCpObj && (size <= copyBlockUnrollLimit))
{
// No write barriers are needed on the stack.
// If the layout contains a byref, then we know it must live on the stack.
if (dstAddr->OperIs(GT_LCL_ADDR) || layout->HasGCByRef())
{
// If the size is small enough to unroll then we need to mark the block as non-interruptible
// to actually allow unrolling. The generated code does not report GC references loaded in the
// temporary register(s) used for copying. This is not supported for the JIT32_GCENCODER.
doCpObj = false;
blkNode->gtBlkOpGcUnsafe = true;
}
}
#endif
if (doCpObj)
{
assert((dstAddr->TypeGet() == TYP_BYREF) || (dstAddr->TypeGet() == TYP_I_IMPL));
// If we have a long enough sequence of slots that do not require write barriers then
// we can use REP MOVSD/Q instead of a sequence of MOVSD/Q instructions. According to the
// Intel Manual, the sweet spot for small structs is between 4 to 12 slots of size where
// the entire operation takes 20 cycles and encodes in 5 bytes (loading RCX and REP MOVSD/Q).
unsigned nonGCSlots = 0;
if (dstAddr->OperIs(GT_LCL_ADDR))
{
// If the destination is on the stack then no write barriers are needed.
nonGCSlots = layout->GetSlotCount();
}
else
{
// Otherwise a write barrier is needed for every GC pointer in the layout
// so we need to check if there's a long enough sequence of non-GC slots.
unsigned slots = layout->GetSlotCount();
for (unsigned i = 0; i < slots; i++)
{
if (layout->IsGCPtr(i))
{
nonGCSlots = 0;
}
else
{
nonGCSlots++;
if (nonGCSlots >= CPOBJ_NONGC_SLOTS_LIMIT)
{
break;
}
}
}
}
if (nonGCSlots >= CPOBJ_NONGC_SLOTS_LIMIT)
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindCpObjRepInstr;
}
else
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindCpObjUnroll;
}
}
else if (blkNode->OperIs(GT_STORE_BLK) &&
(size <= comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy, !layout->HasGCPtr())))
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll;
if (src->OperIs(GT_IND))
{
ContainBlockStoreAddress(blkNode, size, src->AsIndir()->Addr(), src->AsIndir());
}
ContainBlockStoreAddress(blkNode, size, dstAddr, nullptr);
}
else
{
assert(blkNode->OperIs(GT_STORE_BLK, GT_STORE_DYN_BLK));
#ifdef TARGET_AMD64
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindHelper;
#else
// TODO-X86-CQ: Investigate whether a helper call would be beneficial on x86
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
#endif
}
}
assert(blkNode->gtBlkOpKind != GenTreeBlk::BlkOpKindInvalid);
#ifndef TARGET_X86
if ((MIN_ARG_AREA_FOR_CALL > 0) && (blkNode->gtBlkOpKind == GenTreeBlk::BlkOpKindHelper))
{
RequireOutgoingArgSpace(blkNode, MIN_ARG_AREA_FOR_CALL);
}
#endif
}
//------------------------------------------------------------------------
// ContainBlockStoreAddress: Attempt to contain an address used by an unrolled block store.
//
// Arguments:
// blkNode - the block store node
// size - the block size
// addr - the address node to try to contain
// addrParent - the parent of addr, in case this is checking containment of the source address.
//
void Lowering::ContainBlockStoreAddress(GenTreeBlk* blkNode, unsigned size, GenTree* addr, GenTree* addrParent)
{
assert(blkNode->OperIs(GT_STORE_BLK) && (blkNode->gtBlkOpKind == GenTreeBlk::BlkOpKindUnroll));
assert(size < INT32_MAX);
if (addr->OperIs(GT_LCL_ADDR))
{
addr->SetContained();
return;
}
if (!addr->OperIsAddrMode() && !TryCreateAddrMode(addr, true, blkNode))
{
return;
}
GenTreeAddrMode* addrMode = addr->AsAddrMode();
// On x64 the address mode displacement is signed so it must not exceed INT32_MAX. This check is
// an approximation since the last displacement we generate in an unrolled block operation can be
// up to 16 bytes lower than offset + size. But offsets large enough to hit this case are likely
// to be extremely rare for this to ever be a CQ issue.
// On x86 this shouldn't be needed but then again, offsets large enough to hit this are rare.
if (addrMode->Offset() > (INT32_MAX - static_cast<int>(size)))
{
return;
}
// Note that the parentNode is always the block node, even if we're dealing with the source address.
// The source address is not directly used by the block node but by an IND node and that IND node is
// always contained.
if (!IsInvariantInRange(addrMode, blkNode, addrParent))
{
return;
}
addrMode->SetContained();
}
//------------------------------------------------------------------------
// LowerPutArgStkOrSplit: Lower a GT_PUTARG_STK/GT_PUTARG_SPLIT.
//
// Arguments:
// putArgNode - The node of interest
//
void Lowering::LowerPutArgStkOrSplit(GenTreePutArgStk* putArgNode)
{
assert(putArgNode->OperIs(GT_PUTARG_STK)); // No split args on XArch.
LowerPutArgStk(putArgNode);
}
//------------------------------------------------------------------------
// LowerPutArgStk: Lower a GT_PUTARG_STK.
//
// Arguments:
// putArgStk - The node of interest
//
void Lowering::LowerPutArgStk(GenTreePutArgStk* putArgStk)
{
GenTree* src = putArgStk->Data();
bool srcIsLocal = src->OperIsLocalRead();
if (src->OperIs(GT_FIELD_LIST))
{
#ifdef TARGET_X86
GenTreeFieldList* fieldList = src->AsFieldList();
// The code generator will push these fields in reverse order by offset. Reorder the list here s.t. the order
// of uses is visible to LSRA.
assert(fieldList->Uses().IsSorted());
fieldList->Uses().Reverse();
// Containment checks.
for (GenTreeFieldList::Use& use : fieldList->Uses())
{
GenTree* const fieldNode = use.GetNode();
const var_types fieldType = use.GetType();
assert(!fieldNode->TypeIs(TYP_LONG));
// For x86 we must mark all integral fields as contained or reg-optional, and handle them
// accordingly in code generation, since we may have up to 8 fields, which cannot all be in
// registers to be consumed atomically by the call.
if (varTypeIsIntegralOrI(fieldNode))
{
if (IsContainableImmed(putArgStk, fieldNode))
{
MakeSrcContained(putArgStk, fieldNode);
}
else if (IsContainableMemoryOp(fieldNode) && IsSafeToContainMem(putArgStk, fieldNode))
{
MakeSrcContained(putArgStk, fieldNode);
}
else
{
// For the case where we cannot directly push the value, if we run out of registers,
// it would be better to defer computation until we are pushing the arguments rather
// than spilling, but this situation is not all that common, as most cases of FIELD_LIST
// are promoted structs, which do not not have a large number of fields, and of those
// most are lclVars or copy-propagated constants.
fieldNode->SetRegOptional();
}
}
}
// Set the copy kind.
// TODO-X86-CQ: Even if we are using push, if there are contiguous floating point fields, we should
// adjust the stack once for those fields. The latter is really best done in code generation, but
// this tuning should probably be undertaken as a whole.
// Also, if there are floating point fields, it may be better to use the "Unroll" mode
// of copying the struct as a whole, if the fields are not register candidates.
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
#endif // TARGET_X86
return;
}
#ifdef FEATURE_PUT_STRUCT_ARG_STK
if (src->TypeIs(TYP_STRUCT))
{
assert(src->OperIs(GT_BLK) || src->OperIsLocalRead());
ClassLayout* layout = src->GetLayout(comp);
var_types regType = layout->GetRegisterType();
if (regType == TYP_UNDEF)
{
// In case of a CpBlk we could use a helper call. In case of putarg_stk we
// can't do that since the helper call could kill some already set up outgoing args.
// TODO-Amd64-Unix: converge the code for putarg_stk with cpyblk/cpyobj.
// The cpyXXXX code is rather complex and this could cause it to be more complex, but
// it might be the right thing to do.
// If possible, widen the load, this results in more compact code.
unsigned loadSize = srcIsLocal ? roundUp(layout->GetSize(), TARGET_POINTER_SIZE) : layout->GetSize();
putArgStk->SetArgLoadSize(loadSize);
// TODO-X86-CQ: The helper call either is not supported on x86 or required more work
// (I don't know which).
if (!layout->HasGCPtr())
{
#ifdef TARGET_X86
// Codegen for "Kind::Push" will always load bytes in TARGET_POINTER_SIZE
// chunks. As such, we'll only use this path for correctly-sized sources.
if ((loadSize < XMM_REGSIZE_BYTES) && ((loadSize % TARGET_POINTER_SIZE) == 0))
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
}
else
#endif // TARGET_X86
if (loadSize <= comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy))
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Unroll;
}
else
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::RepInstr;
}
}
else // There are GC pointers.
{
#ifdef TARGET_X86
// On x86, we must use `push` to store GC references to the stack in order for the emitter to
// properly update the function's GC info. These `putargstk` nodes will generate a sequence of
// `push` instructions.
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
#else // !TARGET_X86
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::PartialRepInstr;
#endif // !TARGET_X86
}
if (src->OperIs(GT_LCL_VAR))
{
comp->lvaSetVarDoNotEnregister(src->AsLclVar()->GetLclNum()
DEBUGARG(DoNotEnregisterReason::IsStructArg));
}
// Always mark the OBJ/LCL_VAR/LCL_FLD as contained trees.
MakeSrcContained(putArgStk, src);
}
else
{
// The ABI allows upper bits of small struct args to remain undefined,
// so if possible, widen the load to avoid the sign/zero-extension.
if (varTypeIsSmall(regType) && srcIsLocal)
{
assert(genTypeSize(TYP_INT) <= putArgStk->GetStackByteSize());
regType = TYP_INT;
}
src->ChangeType(regType);
if (src->OperIs(GT_BLK))
{
src->SetOper(GT_IND);
LowerIndir(src->AsIndir());
}
}
}
if (src->TypeIs(TYP_STRUCT))
{
return;
}
#endif // FEATURE_PUT_STRUCT_ARG_STK
assert(!src->TypeIs(TYP_STRUCT));
// If the child of GT_PUTARG_STK is a constant, we don't need a register to
// move it to memory (stack location).
//
// On AMD64, we don't want to make 0 contained, because we can generate smaller code
// by zeroing a register and then storing it. E.g.:
// xor rdx, rdx
// mov gword ptr [rsp+28H], rdx
// is 2 bytes smaller than:
// mov gword ptr [rsp+28H], 0
//
// On x86, we push stack arguments; we don't use 'mov'. So:
// push 0
// is 1 byte smaller than:
// xor rdx, rdx
// push rdx
if (IsContainableImmed(putArgStk, src)
#if defined(TARGET_AMD64)
&& !src->IsIntegralConst(0)
#endif // TARGET_AMD64
)
{
MakeSrcContained(putArgStk, src);
}
#ifdef TARGET_X86
else if (genTypeSize(src) == TARGET_POINTER_SIZE)
{
// We can use "src" directly from memory with "push [mem]".
TryMakeSrcContainedOrRegOptional(putArgStk, src);
}
#endif // TARGET_X86
}
/* Lower GT_CAST(srcType, DstType) nodes.
*
* Casts from small int type to float/double are transformed as follows:
* GT_CAST(byte, float/double) = GT_CAST(GT_CAST(byte, int32), float/double)
* GT_CAST(sbyte, float/double) = GT_CAST(GT_CAST(sbyte, int32), float/double)
* GT_CAST(int16, float/double) = GT_CAST(GT_CAST(int16, int32), float/double)
* GT_CAST(uint16, float/double) = GT_CAST(GT_CAST(uint16, int32), float/double)
*
* SSE2 conversion instructions operate on signed integers. casts from Uint32/Uint64
* are morphed as follows by front-end and hence should not be seen here.
* GT_CAST(uint32, float/double) = GT_CAST(GT_CAST(uint32, long), float/double)
* GT_CAST(uint64, float) = GT_CAST(GT_CAST(uint64, double), float)
*
*
* Similarly casts from float/double to a smaller int type are transformed as follows:
* GT_CAST(float/double, byte) = GT_CAST(GT_CAST(float/double, int32), byte)
* GT_CAST(float/double, sbyte) = GT_CAST(GT_CAST(float/double, int32), sbyte)
* GT_CAST(float/double, int16) = GT_CAST(GT_CAST(double/double, int32), int16)
* GT_CAST(float/double, uint16) = GT_CAST(GT_CAST(double/double, int32), uint16)
*
* SSE2 has instructions to convert a float/double vlaue into a signed 32/64-bit
* integer. The above transformations help us to leverage those instructions.
*
* Note that for the following conversions we still depend on helper calls and
* don't expect to see them here.
* i) GT_CAST(float/double, uint64)
* ii) GT_CAST(float/double, int type with overflow detection)
*
* TODO-XArch-CQ: (Low-pri): Jit64 generates in-line code of 8 instructions for (i) above.
* There are hardly any occurrences of this conversion operation in platform
* assemblies or in CQ perf benchmarks (1 occurrence in corelib, microsoft.jscript,
* 1 occurrence in Roslyn and no occurrences in system, system.core, system.numerics
* system.windows.forms, scimark, fractals, bio mums). If we ever find evidence that
* doing this optimization is a win, should consider generating in-lined code.
*/
void Lowering::LowerCast(GenTree* tree)
{
assert(tree->OperGet() == GT_CAST);
GenTree* castOp = tree->AsCast()->CastOp();
var_types castToType = tree->CastToType();
var_types srcType = castOp->TypeGet();
var_types tmpType = TYP_UNDEF;
// force the srcType to unsigned if GT_UNSIGNED flag is set
if (tree->gtFlags & GTF_UNSIGNED)
{
srcType = varTypeToUnsigned(srcType);
}
// We should never see the following casts as they are expected to be lowered
// appropriately or converted into helper calls by front-end.
// srcType = float/double castToType = * and overflow detecting cast
// Reason: must be converted to a helper call
// srcType = float/double, castToType = ulong
// Reason: must be converted to a helper call
// srcType = uint castToType = float/double
// Reason: uint -> float/double = uint -> long -> float/double
// srcType = ulong castToType = float
// Reason: ulong -> float = ulong -> double -> float
if (varTypeIsFloating(srcType))
{
noway_assert(!tree->gtOverflow());
noway_assert(castToType != TYP_ULONG);
}
else if (srcType == TYP_UINT)
{
noway_assert(!varTypeIsFloating(castToType));
}
else if (srcType == TYP_ULONG)
{
assert(castToType != TYP_FLOAT || comp->compIsaSupportedDebugOnly(InstructionSet_AVX512F));
}
// Case of src is a small type and dst is a floating point type.
if (varTypeIsSmall(srcType) && varTypeIsFloating(castToType))
{
// These conversions can never be overflow detecting ones.
noway_assert(!tree->gtOverflow());
tmpType = TYP_INT;
}
// case of src is a floating point type and dst is a small type.
else if (varTypeIsFloating(srcType) && varTypeIsSmall(castToType))
{
tmpType = TYP_INT;
}
if (tmpType != TYP_UNDEF)
{
GenTree* tmp = comp->gtNewCastNode(tmpType, castOp, tree->IsUnsigned(), tmpType);
tmp->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->gtFlags &= ~GTF_UNSIGNED;
tree->AsOp()->gtOp1 = tmp;
BlockRange().InsertAfter(castOp, tmp);
ContainCheckCast(tmp->AsCast());
}
// Now determine if we have operands that should be contained.
ContainCheckCast(tree->AsCast());
}
#ifdef FEATURE_HW_INTRINSICS
//----------------------------------------------------------------------------------------------
// LowerHWIntrinsicCC: Lowers a hardware intrinsic node that produces a boolean value by
// setting the condition flags.
//
// Arguments:
// node - The hardware intrinsic node
// newIntrinsicId - The intrinsic id of the lowered intrinsic node
// condition - The condition code of the generated SETCC/JCC node
//
void Lowering::LowerHWIntrinsicCC(GenTreeHWIntrinsic* node, NamedIntrinsic newIntrinsicId, GenCondition condition)
{
GenTreeCC* cc = LowerNodeCC(node, condition);
assert((HWIntrinsicInfo::lookupNumArgs(newIntrinsicId) == 2) || (newIntrinsicId == NI_AVX512F_KORTEST));
node->ChangeHWIntrinsicId(newIntrinsicId);
node->gtType = TYP_VOID;
node->ClearUnusedValue();
bool swapOperands = false;
bool canSwapOperands = false;
switch (newIntrinsicId)
{
case NI_SSE_COMISS:
case NI_SSE_UCOMISS:
case NI_SSE2_COMISD:
case NI_SSE2_UCOMISD:
// In some cases we can generate better code if we swap the operands:
// - If the condition is not one of the "preferred" floating point conditions we can swap
// the operands and change the condition to avoid generating an extra JP/JNP branch.
// - If the first operand can be contained but the second cannot, we can swap operands in
// order to be able to contain the first operand and avoid the need for a temp reg.
// We can't handle both situations at the same time and since an extra branch is likely to
// be worse than an extra temp reg (x64 has a reasonable number of XMM registers) we'll favor
// the branch case:
// - If the condition is not preferred then swap, even if doing this will later prevent
// containment.
// - Allow swapping for containment purposes only if this doesn't result in a non-"preferred"
// condition being generated.
if ((cc != nullptr) && cc->gtCondition.PreferSwap())
{
swapOperands = true;
}
else
{
canSwapOperands = (cc == nullptr) || !GenCondition::Swap(cc->gtCondition).PreferSwap();
}
break;
case NI_SSE41_PTEST:
case NI_AVX_PTEST:
{
// If we need the Carry flag then we can't swap operands.
canSwapOperands = (cc == nullptr) || cc->gtCondition.Is(GenCondition::EQ, GenCondition::NE);
break;
}
case NI_AVX512F_KORTEST:
case NI_AVX512F_KTEST:
{
// No containment support, so no reason to swap operands
canSwapOperands = false;
break;
}
default:
unreached();
}
if (canSwapOperands)
{
bool op1SupportsRegOptional = false;
bool op2SupportsRegOptional = false;
if (!IsContainableHWIntrinsicOp(node, node->Op(2), &op2SupportsRegOptional) &&
IsContainableHWIntrinsicOp(node, node->Op(1), &op1SupportsRegOptional))
{
// Swap operands if op2 cannot be contained but op1 can.
swapOperands = true;
}
}
if (swapOperands)
{
std::swap(node->Op(1), node->Op(2));
if (cc != nullptr)
{
cc->gtCondition = GenCondition::Swap(cc->gtCondition);
}
}
}
//----------------------------------------------------------------------------------------------
// LowerFusedMultiplyAdd: Changes NI_FMA_MultiplyAddScalar produced by Math(F).FusedMultiplyAdd
// to a better FMA intrinsics if there are GT_NEG around in order to eliminate them.
//
// Arguments:
// node - The hardware intrinsic node
//
// Notes:
// Math(F).FusedMultiplyAdd is expanded into NI_FMA_MultiplyAddScalar and
// depending on additional GT_NEG nodes around it can be:
//
// x * y + z -> NI_FMA_MultiplyAddScalar
// x * -y + z -> NI_FMA_MultiplyAddNegatedScalar
// -x * y + z -> NI_FMA_MultiplyAddNegatedScalar
// -x * -y + z -> NI_FMA_MultiplyAddScalar
// x * y - z -> NI_FMA_MultiplySubtractScalar
// x * -y - z -> NI_FMA_MultiplySubtractNegatedScalar
// -x * y - z -> NI_FMA_MultiplySubtractNegatedScalar
// -x * -y - z -> NI_FMA_MultiplySubtractScalar
//
void Lowering::LowerFusedMultiplyAdd(GenTreeHWIntrinsic* node)
{
assert(node->GetHWIntrinsicId() == NI_FMA_MultiplyAddScalar);
GenTreeHWIntrinsic* createScalarOps[3];
for (size_t i = 1; i <= 3; i++)
{
GenTree* arg = node->Op(i);
if (!arg->OperIsHWIntrinsic() || (arg->AsHWIntrinsic()->GetHWIntrinsicId() != NI_Vector128_CreateScalarUnsafe))
{
return;
}
createScalarOps[i - 1] = arg->AsHWIntrinsic();
}
GenTree* argX = createScalarOps[0]->Op(1);
GenTree* argY = createScalarOps[1]->Op(1);
GenTree* argZ = createScalarOps[2]->Op(1);
const bool negMul = argX->OperIs(GT_NEG) != argY->OperIs(GT_NEG);
if (argX->OperIs(GT_NEG))
{
createScalarOps[0]->Op(1) = argX->gtGetOp1();
BlockRange().Remove(argX);
createScalarOps[0]->Op(1)->ClearContained();
ContainCheckHWIntrinsic(createScalarOps[0]);
}
if (argY->OperIs(GT_NEG))
{
createScalarOps[1]->Op(1) = argY->gtGetOp1();
BlockRange().Remove(argY);
createScalarOps[1]->Op(1)->ClearContained();