LLVM 23.0.0git
SystemZISelLowering.cpp
Go to the documentation of this file.
1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
17#include "llvm/ADT/SmallSet.h"
22#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsS390.h"
26#include "llvm/IR/Module.h"
32#include <cctype>
33#include <optional>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "systemz-lower"
38
39// Temporarily let this be disabled by default until all known problems
40// related to argument extensions are fixed.
42 "argext-abi-check", cl::init(false),
43 cl::desc("Verify that narrow int args are properly extended per the "
44 "SystemZ ABI."));
45
46namespace {
47// Represents information about a comparison.
48struct Comparison {
49 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
50 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
51 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
52
53 // The operands to the comparison.
54 SDValue Op0, Op1;
55
56 // Chain if this is a strict floating-point comparison.
57 SDValue Chain;
58
59 // The opcode that should be used to compare Op0 and Op1.
60 unsigned Opcode;
61
62 // A SystemZICMP value. Only used for integer comparisons.
63 unsigned ICmpType;
64
65 // The mask of CC values that Opcode can produce.
66 unsigned CCValid;
67
68 // The mask of CC values for which the original condition is true.
69 unsigned CCMask;
70};
71} // end anonymous namespace
72
73// Classify VT as either 32 or 64 bit.
74static bool is32Bit(EVT VT) {
75 switch (VT.getSimpleVT().SimpleTy) {
76 case MVT::i32:
77 return true;
78 case MVT::i64:
79 return false;
80 default:
81 llvm_unreachable("Unsupported type");
82 }
83}
84
85// Return a version of MachineOperand that can be safely used before the
86// final use.
88 if (Op.isReg())
89 Op.setIsKill(false);
90 return Op;
91}
92
94 const SystemZSubtarget &STI)
95 : TargetLowering(TM, STI), Subtarget(STI) {
96 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
97
98 auto *Regs = STI.getSpecialRegisters();
99
100 // Set up the register classes.
101 if (Subtarget.hasHighWord())
102 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
103 else
104 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
105 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
106 if (!useSoftFloat()) {
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
109 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
110 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
111 } else {
112 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
113 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
114 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
115 }
116 if (Subtarget.hasVectorEnhancements1())
117 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
118 else
119 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
120
121 if (Subtarget.hasVector()) {
122 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
123 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
124 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
125 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
126 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
127 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
128 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
129 }
130
131 if (Subtarget.hasVector())
132 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
133 }
134
135 // Compute derived properties from the register classes
136 computeRegisterProperties(Subtarget.getRegisterInfo());
137
138 // Set up special registers.
139 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
140
141 // TODO: It may be better to default to latency-oriented scheduling, however
142 // LLVM's current latency-oriented scheduler can't handle physreg definitions
143 // such as SystemZ has with CC, so set this to the register-pressure
144 // scheduler, because it can.
146
149
151
152 // Instructions are strings of 2-byte aligned 2-byte values.
154 // For performance reasons we prefer 16-byte alignment.
156
157 // Handle operations that are handled in a similar way for all types.
158 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
159 I <= MVT::LAST_FP_VALUETYPE;
160 ++I) {
162 if (isTypeLegal(VT)) {
163 // Lower SET_CC into an IPM-based sequence.
167
168 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
170
171 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
174 }
175 }
176
177 // Expand jump table branches as address arithmetic followed by an
178 // indirect jump.
180
181 // Expand BRCOND into a BR_CC (see above).
183
184 // Handle integer types except i128.
185 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
186 I <= MVT::LAST_INTEGER_VALUETYPE;
187 ++I) {
189 if (isTypeLegal(VT) && VT != MVT::i128) {
191
192 // Expand individual DIV and REMs into DIVREMs.
199
200 // Support addition/subtraction with overflow.
203
204 // Support addition/subtraction with carry.
207
208 // Support carry in as value rather than glue.
211
212 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
213 // available, or if the operand is constant.
215
216 // Use POPCNT on z196 and above.
217 if (Subtarget.hasPopulationCount())
219 else
221
222 // No special instructions for these.
225
226 // Use *MUL_LOHI where possible instead of MULH*.
231
232 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
233 // unsigned on z10 (only z196 and above have native support for
234 // unsigned conversions).
241 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
242 auto OpAction =
243 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
244 setOperationAction(Op, VT, OpAction);
245 }
246 }
247 }
248
249 // Handle i128 if legal.
250 if (isTypeLegal(MVT::i128)) {
251 // No special instructions for these.
258
259 // We may be able to use VSLDB/VSLD/VSRD for these.
262
263 // No special instructions for these before z17.
264 if (!Subtarget.hasVectorEnhancements3()) {
274 } else {
275 // Even if we do have a legal 128-bit multiply, we do not
276 // want 64-bit multiply-high operations to use it.
279 }
280
281 // Support addition/subtraction with carry.
286
287 // Use VPOPCT and add up partial results.
289
290 // Additional instructions available with z17.
291 if (Subtarget.hasVectorEnhancements3()) {
292 setOperationAction(ISD::ABS, MVT::i128, Legal);
293
295 MVT::i128, Legal);
296 }
297 }
298
299 // These need custom handling in order to handle the f16 conversions.
308
309 // Type legalization will convert 8- and 16-bit atomic operations into
310 // forms that operate on i32s (but still keeping the original memory VT).
311 // Lower them into full i32 operations.
323
324 // Whether or not i128 is not a legal type, we need to custom lower
325 // the atomic operations in order to exploit SystemZ instructions.
330
331 // Mark sign/zero extending atomic loads as legal, which will make
332 // DAGCombiner fold extensions into atomic loads if possible.
334 {MVT::i8, MVT::i16, MVT::i32}, Legal);
336 {MVT::i8, MVT::i16}, Legal);
338 MVT::i8, Legal);
339
340 // We can use the CC result of compare-and-swap to implement
341 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
345
347
348 // Traps are legal, as we will convert them to "j .+2".
349 setOperationAction(ISD::TRAP, MVT::Other, Legal);
350
351 // We have native support for a 64-bit CTLZ, via FLOGR.
355
356 // On z17 we have native support for a 64-bit CTTZ.
357 if (Subtarget.hasMiscellaneousExtensions4()) {
361 }
362
363 // On z15 we have native support for a 64-bit CTPOP.
364 if (Subtarget.hasMiscellaneousExtensions3()) {
367 }
368
369 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
371
372 // Expand 128 bit shifts without using a libcall.
376
377 // Also expand 256 bit shifts if i128 is a legal type.
378 if (isTypeLegal(MVT::i128)) {
382 }
383
384 // Handle bitcast from fp128 to i128.
385 if (!isTypeLegal(MVT::i128))
387
388 // We have native instructions for i8, i16 and i32 extensions, but not i1.
390 for (MVT VT : MVT::integer_valuetypes()) {
394 }
395
396 // Handle the various types of symbolic address.
402
403 // We need to handle dynamic allocations specially because of the
404 // 160-byte area at the bottom of the stack.
407
410
411 // Handle prefetches with PFD or PFDRL.
413
414 // Handle readcyclecounter with STCKF.
416
418 // Assume by default that all vector operations need to be expanded.
419 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
420 if (getOperationAction(Opcode, VT) == Legal)
421 setOperationAction(Opcode, VT, Expand);
422
423 // Likewise all truncating stores and extending loads.
424 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
425 setTruncStoreAction(VT, InnerVT, Expand);
428 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
429 }
430
431 if (isTypeLegal(VT)) {
432 // These operations are legal for anything that can be stored in a
433 // vector register, even if there is no native support for the format
434 // as such. In particular, we can do these for v4f32 even though there
435 // are no specific instructions for that format.
441
442 // Likewise, except that we need to replace the nodes with something
443 // more specific.
446 }
447 }
448
449 // Handle integer vector types.
451 if (isTypeLegal(VT)) {
452 // These operations have direct equivalents.
457 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
461 }
462 if (Subtarget.hasVectorEnhancements3() &&
463 VT != MVT::v16i8 && VT != MVT::v8i16) {
468 }
473 if (Subtarget.hasVectorEnhancements1())
475 else
479
480 // Convert a GPR scalar to a vector by inserting it into element 0.
482
483 // Use a series of unpacks for extensions.
486
487 // Detect shifts/rotates by a scalar amount and convert them into
488 // V*_BY_SCALAR.
493
494 // Add ISD::VECREDUCE_ADD as custom in order to implement
495 // it with VZERO+VSUM
497
498 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
499 // and inverting the result as necessary.
501
503 Legal);
504 }
505 }
506
507 if (Subtarget.hasVector()) {
508 // There should be no need to check for float types other than v2f64
509 // since <2 x f32> isn't a legal type.
518
527 }
528
529 if (Subtarget.hasVectorEnhancements2()) {
538
547 }
548
549 // Handle floating-point types.
550 if (!useSoftFloat()) {
551 // Promote all f16 operations to float, with some exceptions below.
552 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
553 setOperationAction(Opc, MVT::f16, Promote);
555 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
556 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
557 setTruncStoreAction(VT, MVT::f16, Expand);
558 }
560 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
564
565 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
566 setOperationAction(Op, MVT::f16, Legal);
567 }
568
569 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
570 I <= MVT::LAST_FP_VALUETYPE;
571 ++I) {
573 if (isTypeLegal(VT) && VT != MVT::f16) {
574 // We can use FI for FRINT.
576
577 // We can use the extended form of FI for other rounding operations.
578 if (Subtarget.hasFPExtension()) {
585 }
586
587 // No special instructions for these.
593
594 // Special treatment.
596
597 // Handle constrained floating-point operations.
606 if (Subtarget.hasFPExtension()) {
613 }
614
615 // Extension from f16 needs libcall.
618 }
619 }
620
621 // Handle floating-point vector types.
622 if (Subtarget.hasVector()) {
623 // Scalar-to-vector conversion is just a subreg.
627
628 // Some insertions and extractions can be done directly but others
629 // need to go via integers.
636
637 // These operations have direct equivalents.
638 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
639 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
640 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
641 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
642 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
643 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
644 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
645 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
646 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
649 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
653
654 // Handle constrained floating-point operations.
668
673 if (Subtarget.hasVectorEnhancements1()) {
676 }
677 }
678
679 // The vector enhancements facility 1 has instructions for these.
680 if (Subtarget.hasVectorEnhancements1()) {
681 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
682 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
683 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
684 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
685 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
686 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
687 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
689 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
692 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
696
697 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
704 }
705
706 // Handle constrained floating-point operations.
720 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
721 MVT::v4f32, MVT::v2f64 }) {
726 }
727 }
728
729 // We only have fused f128 multiply-addition on vector registers.
730 if (!Subtarget.hasVectorEnhancements1()) {
733 }
734
735 // We don't have a copysign instruction on vector registers.
736 if (Subtarget.hasVectorEnhancements1())
738
739 // Needed so that we don't try to implement f128 constant loads using
740 // a load-and-extend of a f80 constant (in cases where the constant
741 // would fit in an f80).
742 for (MVT VT : MVT::fp_valuetypes())
743 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
744
745 // We don't have extending load instruction on vector registers.
746 if (Subtarget.hasVectorEnhancements1()) {
747 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
748 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
749 }
750
751 // Floating-point truncation and stores need to be done separately.
752 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
753 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
754 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
755
756 // We have 64-bit FPR<->GPR moves, but need special handling for
757 // 32-bit forms.
758 if (!Subtarget.hasVector()) {
761 }
762
763 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
764 // structure, but VAEND is a no-op.
768
769 if (Subtarget.isTargetzOS()) {
770 // Handle address space casts between mixed sized pointers.
773 }
774
776
777 // Codes for which we want to perform some z-specific combinations.
781 ISD::LOAD,
794 ISD::SRL,
795 ISD::SRA,
796 ISD::MUL,
797 ISD::SDIV,
798 ISD::UDIV,
799 ISD::SREM,
800 ISD::UREM,
803
804 // Handle intrinsics.
807
808 // We're not using SJLJ for exception handling, but they're implemented
809 // solely to support use of __builtin_setjmp / __builtin_longjmp.
812
813 // We want to use MVC in preference to even a single load/store pair.
814 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
816
817 // Same with memmove.
818 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
820
821 // The main memset sequence is a byte store followed by an MVC.
822 // Two STC or MV..I stores win over that, but the kind of fused stores
823 // generated by target-independent code don't when the byte value is
824 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
825 // than "STC;MVC". Handle the choice in target-specific code instead.
826 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
828
829 // Default to having -disable-strictnode-mutation on
830 IsStrictFPEnabled = true;
831}
832
834 return Subtarget.hasSoftFloat();
835}
836
838 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
839 unsigned &NumIntermediates, MVT &RegisterVT) const {
840 // Pass fp16 vectors in VR(s).
841 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
842 IntermediateVT = RegisterVT = MVT::v8f16;
843 return NumIntermediates =
845 }
847 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
848}
849
852 EVT VT) const {
853 // 128-bit single-element vector types are passed like other vectors,
854 // not like their element type.
855 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
856 VT.getVectorNumElements() == 1)
857 return MVT::v16i8;
858 // Pass fp16 vectors in VR(s).
859 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
860 return MVT::v8f16;
861 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
862}
863
865 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
866 // Pass fp16 vectors in VR(s).
867 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
869 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
870}
871
873 LLVMContext &, EVT VT) const {
874 if (!VT.isVector())
875 return MVT::i32;
877}
878
880 const MachineFunction &MF, EVT VT) const {
881 if (useSoftFloat())
882 return false;
883
884 VT = VT.getScalarType();
885
886 if (!VT.isSimple())
887 return false;
888
889 switch (VT.getSimpleVT().SimpleTy) {
890 case MVT::f32:
891 case MVT::f64:
892 return true;
893 case MVT::f128:
894 return Subtarget.hasVectorEnhancements1();
895 default:
896 break;
897 }
898
899 return false;
900}
901
902// Return true if the constant can be generated with a vector instruction,
903// such as VGM, VGMB or VREPI.
905 const SystemZSubtarget &Subtarget) {
906 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
907 if (!Subtarget.hasVector() ||
908 (isFP128 && !Subtarget.hasVectorEnhancements1()))
909 return false;
910
911 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
912 // preferred way of creating all-zero and all-one vectors so give it
913 // priority over other methods below.
914 unsigned Mask = 0;
915 unsigned I = 0;
916 for (; I < SystemZ::VectorBytes; ++I) {
917 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
918 if (Byte == 0xff)
919 Mask |= 1ULL << I;
920 else if (Byte != 0)
921 break;
922 }
923 if (I == SystemZ::VectorBytes) {
924 Opcode = SystemZISD::BYTE_MASK;
925 OpVals.push_back(Mask);
927 return true;
928 }
929
930 if (SplatBitSize > 64)
931 return false;
932
933 auto TryValue = [&](uint64_t Value) -> bool {
934 // Try VECTOR REPLICATE IMMEDIATE
935 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
936 if (isInt<16>(SignedValue)) {
937 OpVals.push_back(((unsigned) SignedValue));
938 Opcode = SystemZISD::REPLICATE;
940 SystemZ::VectorBits / SplatBitSize);
941 return true;
942 }
943 // Try VECTOR GENERATE MASK
944 unsigned Start, End;
945 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
946 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
947 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
948 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
949 OpVals.push_back(Start - (64 - SplatBitSize));
950 OpVals.push_back(End - (64 - SplatBitSize));
951 Opcode = SystemZISD::ROTATE_MASK;
953 SystemZ::VectorBits / SplatBitSize);
954 return true;
955 }
956 return false;
957 };
958
959 // First try assuming that any undefined bits above the highest set bit
960 // and below the lowest set bit are 1s. This increases the likelihood of
961 // being able to use a sign-extended element value in VECTOR REPLICATE
962 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
963 uint64_t SplatBitsZ = SplatBits.getZExtValue();
964 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
965 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
966 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
967 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
968 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
969 if (TryValue(SplatBitsZ | Upper | Lower))
970 return true;
971
972 // Now try assuming that any undefined bits between the first and
973 // last defined set bits are set. This increases the chances of
974 // using a non-wraparound mask.
975 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
976 return TryValue(SplatBitsZ | Middle);
977}
978
980 if (IntImm.isSingleWord()) {
981 IntBits = APInt(128, IntImm.getZExtValue());
982 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
983 } else
984 IntBits = IntImm;
985 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
986
987 // Find the smallest splat.
988 SplatBits = IntImm;
989 unsigned Width = SplatBits.getBitWidth();
990 while (Width > 8) {
991 unsigned HalfSize = Width / 2;
992 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
993 APInt LowValue = SplatBits.trunc(HalfSize);
994
995 // If the two halves do not match, stop here.
996 if (HighValue != LowValue || 8 > HalfSize)
997 break;
998
999 SplatBits = HighValue;
1000 Width = HalfSize;
1001 }
1002 SplatUndef = 0;
1003 SplatBitSize = Width;
1004}
1005
1007 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1008 bool HasAnyUndefs;
1009
1010 // Get IntBits by finding the 128 bit splat.
1011 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1012 true);
1013
1014 // Get SplatBits by finding the 8 bit or greater splat.
1015 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1016 true);
1017}
1018
1020 bool ForCodeSize) const {
1021 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1022 if (Imm.isZero() || Imm.isNegZero())
1023 return true;
1024
1025 return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget);
1026}
1027
1030 MachineBasicBlock *MBB) const {
1031 DebugLoc DL = MI.getDebugLoc();
1032 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1033 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1034
1035 MachineFunction *MF = MBB->getParent();
1036 MachineRegisterInfo &MRI = MF->getRegInfo();
1037
1038 const BasicBlock *BB = MBB->getBasicBlock();
1039 MachineFunction::iterator I = ++MBB->getIterator();
1040
1041 Register DstReg = MI.getOperand(0).getReg();
1042 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1043 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1044 (void)TRI;
1045 Register MainDstReg = MRI.createVirtualRegister(RC);
1046 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1047
1048 MVT PVT = getPointerTy(MF->getDataLayout());
1049 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1050 // For v = setjmp(buf), we generate.
1051 // Algorithm:
1052 //
1053 // ---------
1054 // | thisMBB |
1055 // ---------
1056 // |
1057 // ------------------------
1058 // | |
1059 // ---------- ---------------
1060 // | mainMBB | | restoreMBB |
1061 // | v = 0 | | v = 1 |
1062 // ---------- ---------------
1063 // | |
1064 // -------------------------
1065 // |
1066 // -----------------------------
1067 // | sinkMBB |
1068 // | phi(v_mainMBB,v_restoreMBB) |
1069 // -----------------------------
1070 // thisMBB:
1071 // buf[FPOffset] = Frame Pointer if hasFP.
1072 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1073 // buf[BCOffset] = Backchain value if building with -mbackchain.
1074 // buf[SPOffset] = Stack Pointer.
1075 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1076 // SjLjSetup restoreMBB
1077 // mainMBB:
1078 // v_main = 0
1079 // sinkMBB:
1080 // v = phi(v_main, v_restore)
1081 // restoreMBB:
1082 // v_restore = 1
1083
1084 MachineBasicBlock *ThisMBB = MBB;
1085 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1086 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1087 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1088
1089 MF->insert(I, MainMBB);
1090 MF->insert(I, SinkMBB);
1091 MF->push_back(RestoreMBB);
1092 RestoreMBB->setMachineBlockAddressTaken();
1093
1095
1096 // Transfer the remainder of BB and its successor edges to sinkMBB.
1097 SinkMBB->splice(SinkMBB->begin(), MBB,
1098 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1100
1101 // thisMBB:
1102 const int64_t FPOffset = 0; // Slot 1.
1103 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1104 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1105 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1106
1107 // Buf address.
1108 Register BufReg = MI.getOperand(1).getReg();
1109
1110 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1111 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1112
1113 // Prepare IP for longjmp.
1114 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1115 .addMBB(RestoreMBB);
1116 // Store IP for return from jmp, slot 2, offset = 1.
1117 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1118 .addReg(LabelReg)
1119 .addReg(BufReg)
1120 .addImm(LabelOffset)
1121 .addReg(0);
1122
1123 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1124 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1125 if (HasFP) {
1126 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1127 .addReg(SpecialRegs->getFramePointerRegister())
1128 .addReg(BufReg)
1129 .addImm(FPOffset)
1130 .addReg(0);
1131 }
1132
1133 // Store SP.
1134 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1135 .addReg(SpecialRegs->getStackPointerRegister())
1136 .addReg(BufReg)
1137 .addImm(SPOffset)
1138 .addReg(0);
1139
1140 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1141 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1142 if (BackChain) {
1143 Register BCReg = MRI.createVirtualRegister(PtrRC);
1144 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1145 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1146 .addReg(SpecialRegs->getStackPointerRegister())
1147 .addImm(TFL->getBackchainOffset(*MF))
1148 .addReg(0);
1149
1150 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1151 .addReg(BCReg)
1152 .addReg(BufReg)
1153 .addImm(BCOffset)
1154 .addReg(0);
1155 }
1156
1157 // Setup.
1158 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1159 .addMBB(RestoreMBB);
1160
1161 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1162 MIB.addRegMask(RegInfo->getNoPreservedMask());
1163
1164 ThisMBB->addSuccessor(MainMBB);
1165 ThisMBB->addSuccessor(RestoreMBB);
1166
1167 // mainMBB:
1168 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1169 MainMBB->addSuccessor(SinkMBB);
1170
1171 // sinkMBB:
1172 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1173 .addReg(MainDstReg)
1174 .addMBB(MainMBB)
1175 .addReg(RestoreDstReg)
1176 .addMBB(RestoreMBB);
1177
1178 // restoreMBB.
1179 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1180 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1181 RestoreMBB->addSuccessor(SinkMBB);
1182
1183 MI.eraseFromParent();
1184
1185 return SinkMBB;
1186}
1187
1190 MachineBasicBlock *MBB) const {
1191
1192 DebugLoc DL = MI.getDebugLoc();
1193 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1194
1195 MachineFunction *MF = MBB->getParent();
1196 MachineRegisterInfo &MRI = MF->getRegInfo();
1197
1198 MVT PVT = getPointerTy(MF->getDataLayout());
1199 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1200 Register BufReg = MI.getOperand(0).getReg();
1201 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1202 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1203
1204 Register Tmp = MRI.createVirtualRegister(RC);
1205 Register BCReg = MRI.createVirtualRegister(RC);
1206
1208
1209 const int64_t FPOffset = 0;
1210 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1211 const int64_t BCOffset = 2 * PVT.getStoreSize();
1212 const int64_t SPOffset = 3 * PVT.getStoreSize();
1213 const int64_t LPOffset = 4 * PVT.getStoreSize();
1214
1215 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1216 .addReg(BufReg)
1217 .addImm(LabelOffset)
1218 .addReg(0);
1219
1220 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1221 SpecialRegs->getFramePointerRegister())
1222 .addReg(BufReg)
1223 .addImm(FPOffset)
1224 .addReg(0);
1225
1226 // We are restoring R13 even though we never stored in setjmp from llvm,
1227 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1228 // gcc setjmp and llvm longjmp.
1229 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1230 .addReg(BufReg)
1231 .addImm(LPOffset)
1232 .addReg(0);
1233
1234 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1235 if (BackChain) {
1236 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1237 .addReg(BufReg)
1238 .addImm(BCOffset)
1239 .addReg(0);
1240 }
1241
1242 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1243 SpecialRegs->getStackPointerRegister())
1244 .addReg(BufReg)
1245 .addImm(SPOffset)
1246 .addReg(0);
1247
1248 if (BackChain) {
1249 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1250 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1251 .addReg(BCReg)
1252 .addReg(SpecialRegs->getStackPointerRegister())
1253 .addImm(TFL->getBackchainOffset(*MF))
1254 .addReg(0);
1255 }
1256
1257 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1258
1259 MI.eraseFromParent();
1260 return MBB;
1261}
1262
1263/// Returns true if stack probing through inline assembly is requested.
1265 // If the function specifically requests inline stack probes, emit them.
1266 if (MF.getFunction().hasFnAttribute("probe-stack"))
1267 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1268 "inline-asm";
1269 return false;
1270}
1271
1276
1281
1284 const AtomicRMWInst *RMW) const {
1285 // Don't expand subword operations as they require special treatment.
1286 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1288
1289 // Don't expand if there is a target instruction available.
1290 if (Subtarget.hasInterlockedAccess1() &&
1291 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1298
1300}
1301
1303 // We can use CGFI or CLGFI.
1304 return isInt<32>(Imm) || isUInt<32>(Imm);
1305}
1306
1308 // We can use ALGFI or SLGFI.
1309 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1310}
1311
1313 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1314 // Unaligned accesses should never be slower than the expanded version.
1315 // We check specifically for aligned accesses in the few cases where
1316 // they are required.
1317 if (Fast)
1318 *Fast = 1;
1319 return true;
1320}
1321
1323 EVT VT = Y.getValueType();
1324
1325 // We can use NC(G)RK for types in GPRs ...
1326 if (VT == MVT::i32 || VT == MVT::i64)
1327 return Subtarget.hasMiscellaneousExtensions3();
1328
1329 // ... or VNC for types in VRs.
1330 if (VT.isVector() || VT == MVT::i128)
1331 return Subtarget.hasVector();
1332
1333 return false;
1334}
1335
1336// Information about the addressing mode for a memory access.
1338 // True if a long displacement is supported.
1340
1341 // True if use of index register is supported.
1343
1344 AddressingMode(bool LongDispl, bool IdxReg) :
1345 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1346};
1347
1348// Return the desired addressing mode for a Load which has only one use (in
1349// the same block) which is a Store.
1351 Type *Ty) {
1352 // With vector support a Load->Store combination may be combined to either
1353 // an MVC or vector operations and it seems to work best to allow the
1354 // vector addressing mode.
1355 if (HasVector)
1356 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1357
1358 // Otherwise only the MVC case is special.
1359 bool MVC = Ty->isIntegerTy(8);
1360 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1361}
1362
1363// Return the addressing mode which seems most desirable given an LLVM
1364// Instruction pointer.
1365static AddressingMode
1368 switch (II->getIntrinsicID()) {
1369 default: break;
1370 case Intrinsic::memset:
1371 case Intrinsic::memmove:
1372 case Intrinsic::memcpy:
1373 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1374 }
1375 }
1376
1377 if (isa<LoadInst>(I) && I->hasOneUse()) {
1378 auto *SingleUser = cast<Instruction>(*I->user_begin());
1379 if (SingleUser->getParent() == I->getParent()) {
1380 if (isa<ICmpInst>(SingleUser)) {
1381 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1382 if (C->getBitWidth() <= 64 &&
1383 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1384 // Comparison of memory with 16 bit signed / unsigned immediate
1385 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1386 } else if (isa<StoreInst>(SingleUser))
1387 // Load->Store
1388 return getLoadStoreAddrMode(HasVector, I->getType());
1389 }
1390 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1391 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1392 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1393 // Load->Store
1394 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1395 }
1396
1397 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1398
1399 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1400 // dependencies (LDE only supports small offsets).
1401 // * Utilize the vector registers to hold floating point
1402 // values (vector load / store instructions only support small
1403 // offsets).
1404
1405 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1406 I->getOperand(0)->getType());
1407 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1408 bool IsVectorAccess = MemAccessTy->isVectorTy();
1409
1410 // A store of an extracted vector element will be combined into a VSTE type
1411 // instruction.
1412 if (!IsVectorAccess && isa<StoreInst>(I)) {
1413 Value *DataOp = I->getOperand(0);
1414 if (isa<ExtractElementInst>(DataOp))
1415 IsVectorAccess = true;
1416 }
1417
1418 // A load which gets inserted into a vector element will be combined into a
1419 // VLE type instruction.
1420 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1421 User *LoadUser = *I->user_begin();
1422 if (isa<InsertElementInst>(LoadUser))
1423 IsVectorAccess = true;
1424 }
1425
1426 if (IsFPAccess || IsVectorAccess)
1427 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1428 }
1429
1430 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1431}
1432
1434 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1435 // Punt on globals for now, although they can be used in limited
1436 // RELATIVE LONG cases.
1437 if (AM.BaseGV)
1438 return false;
1439
1440 // Require a 20-bit signed offset.
1441 if (!isInt<20>(AM.BaseOffs))
1442 return false;
1443
1444 bool RequireD12 =
1445 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1446 AddressingMode SupportedAM(!RequireD12, true);
1447 if (I != nullptr)
1448 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1449
1450 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1451 return false;
1452
1453 if (!SupportedAM.IndexReg)
1454 // No indexing allowed.
1455 return AM.Scale == 0;
1456 else
1457 // Indexing is OK but no scale factor can be applied.
1458 return AM.Scale == 0 || AM.Scale == 1;
1459}
1460
1462 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1463 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1464 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1465
1466 assert(Limit != ~0U &&
1467 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1468
1469 if (Op.isZeroMemset())
1470 return false; // Memset zero: Use XC.
1471
1472 const int MVCFastLen = 16;
1473 // Use MVC up to 16 bytes. Small memset uses STC/MVI for first byte.
1474 if ((Op.isMemset() ? Op.size() - 1 : Op.size()) <= MVCFastLen)
1475 return false;
1476
1477 // Avoid unaligned VL/VST:s.
1478 if (!Op.isAligned(Align(8)) || (Op.size() >= 25 && Op.size() <= 31))
1479 return false;
1480
1482 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1483}
1484
1486 LLVMContext &Context, const MemOp &Op,
1487 const AttributeList &FuncAttributes) const {
1488 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1489}
1490
1491bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1492 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1493 return false;
1494 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1495 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1496 return FromBits > ToBits;
1497}
1498
1500 if (!FromVT.isInteger() || !ToVT.isInteger())
1501 return false;
1502 unsigned FromBits = FromVT.getFixedSizeInBits();
1503 unsigned ToBits = ToVT.getFixedSizeInBits();
1504 return FromBits > ToBits;
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// Inline asm support
1509//===----------------------------------------------------------------------===//
1510
1513 if (Constraint.size() == 1) {
1514 switch (Constraint[0]) {
1515 case 'a': // Address register
1516 case 'd': // Data register (equivalent to 'r')
1517 case 'f': // Floating-point register
1518 case 'h': // High-part register
1519 case 'r': // General-purpose register
1520 case 'v': // Vector register
1521 return C_RegisterClass;
1522
1523 case 'Q': // Memory with base and unsigned 12-bit displacement
1524 case 'R': // Likewise, plus an index
1525 case 'S': // Memory with base and signed 20-bit displacement
1526 case 'T': // Likewise, plus an index
1527 case 'm': // Equivalent to 'T'.
1528 return C_Memory;
1529
1530 case 'I': // Unsigned 8-bit constant
1531 case 'J': // Unsigned 12-bit constant
1532 case 'K': // Signed 16-bit constant
1533 case 'L': // Signed 20-bit displacement (on all targets we support)
1534 case 'M': // 0x7fffffff
1535 return C_Immediate;
1536
1537 default:
1538 break;
1539 }
1540 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1541 switch (Constraint[1]) {
1542 case 'Q': // Address with base and unsigned 12-bit displacement
1543 case 'R': // Likewise, plus an index
1544 case 'S': // Address with base and signed 20-bit displacement
1545 case 'T': // Likewise, plus an index
1546 return C_Address;
1547
1548 default:
1549 break;
1550 }
1551 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1552 if (StringRef("{@cc}").compare(Constraint) == 0)
1553 return C_Other;
1554 }
1555 return TargetLowering::getConstraintType(Constraint);
1556}
1557
1560 AsmOperandInfo &Info, const char *Constraint) const {
1562 Value *CallOperandVal = Info.CallOperandVal;
1563 // If we don't have a value, we can't do a match,
1564 // but allow it at the lowest weight.
1565 if (!CallOperandVal)
1566 return CW_Default;
1567 Type *type = CallOperandVal->getType();
1568 // Look at the constraint type.
1569 switch (*Constraint) {
1570 default:
1571 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1572 break;
1573
1574 case 'a': // Address register
1575 case 'd': // Data register (equivalent to 'r')
1576 case 'h': // High-part register
1577 case 'r': // General-purpose register
1578 Weight =
1579 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1580 break;
1581
1582 case 'f': // Floating-point register
1583 if (!useSoftFloat())
1584 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1585 break;
1586
1587 case 'v': // Vector register
1588 if (Subtarget.hasVector())
1589 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1590 : CW_Default;
1591 break;
1592
1593 case 'I': // Unsigned 8-bit constant
1594 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1595 if (isUInt<8>(C->getZExtValue()))
1596 Weight = CW_Constant;
1597 break;
1598
1599 case 'J': // Unsigned 12-bit constant
1600 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1601 if (isUInt<12>(C->getZExtValue()))
1602 Weight = CW_Constant;
1603 break;
1604
1605 case 'K': // Signed 16-bit constant
1606 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1607 if (isInt<16>(C->getSExtValue()))
1608 Weight = CW_Constant;
1609 break;
1610
1611 case 'L': // Signed 20-bit displacement (on all targets we support)
1612 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1613 if (isInt<20>(C->getSExtValue()))
1614 Weight = CW_Constant;
1615 break;
1616
1617 case 'M': // 0x7fffffff
1618 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1619 if (C->getZExtValue() == 0x7fffffff)
1620 Weight = CW_Constant;
1621 break;
1622 }
1623 return Weight;
1624}
1625
1626// Parse a "{tNNN}" register constraint for which the register type "t"
1627// has already been verified. MC is the class associated with "t" and
1628// Map maps 0-based register numbers to LLVM register numbers.
1629static std::pair<unsigned, const TargetRegisterClass *>
1631 const unsigned *Map, unsigned Size) {
1632 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1633 if (isdigit(Constraint[2])) {
1634 unsigned Index;
1635 bool Failed =
1636 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1637 if (!Failed && Index < Size && Map[Index])
1638 return std::make_pair(Map[Index], RC);
1639 }
1640 return std::make_pair(0U, nullptr);
1641}
1642
1643std::pair<unsigned, const TargetRegisterClass *>
1645 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1646 if (Constraint.size() == 1) {
1647 // GCC Constraint Letters
1648 switch (Constraint[0]) {
1649 default: break;
1650 case 'd': // Data register (equivalent to 'r')
1651 case 'r': // General-purpose register
1652 if (VT.getSizeInBits() == 64)
1653 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1654 else if (VT.getSizeInBits() == 128)
1655 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1656 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1657
1658 case 'a': // Address register
1659 if (VT == MVT::i64)
1660 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1661 else if (VT == MVT::i128)
1662 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1663 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1664
1665 case 'h': // High-part register (an LLVM extension)
1666 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1667
1668 case 'f': // Floating-point register
1669 if (!useSoftFloat()) {
1670 if (VT.getSizeInBits() == 16)
1671 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1672 else if (VT.getSizeInBits() == 64)
1673 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1674 else if (VT.getSizeInBits() == 128)
1675 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1676 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1677 }
1678 break;
1679
1680 case 'v': // Vector register
1681 if (Subtarget.hasVector()) {
1682 if (VT.getSizeInBits() == 16)
1683 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1684 if (VT.getSizeInBits() == 32)
1685 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1686 if (VT.getSizeInBits() == 64)
1687 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1688 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1689 }
1690 break;
1691 }
1692 }
1693 if (Constraint.starts_with("{")) {
1694
1695 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1696 // to check the size on.
1697 auto getVTSizeInBits = [&VT]() {
1698 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1699 };
1700
1701 // We need to override the default register parsing for GPRs and FPRs
1702 // because the interpretation depends on VT. The internal names of
1703 // the registers are also different from the external names
1704 // (F0D and F0S instead of F0, etc.).
1705 if (Constraint[1] == 'r') {
1706 if (getVTSizeInBits() == 32)
1707 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1709 if (getVTSizeInBits() == 128)
1710 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1712 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1714 }
1715 if (Constraint[1] == 'f') {
1716 if (useSoftFloat())
1717 return std::make_pair(
1718 0u, static_cast<const TargetRegisterClass *>(nullptr));
1719 if (getVTSizeInBits() == 16)
1720 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1722 if (getVTSizeInBits() == 32)
1723 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1725 if (getVTSizeInBits() == 128)
1726 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1728 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1730 }
1731 if (Constraint[1] == 'v') {
1732 if (!Subtarget.hasVector())
1733 return std::make_pair(
1734 0u, static_cast<const TargetRegisterClass *>(nullptr));
1735 if (getVTSizeInBits() == 16)
1736 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1738 if (getVTSizeInBits() == 32)
1739 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1741 if (getVTSizeInBits() == 64)
1742 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1744 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1746 }
1747 if (Constraint[1] == '@') {
1748 if (StringRef("{@cc}").compare(Constraint) == 0)
1749 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1750 }
1751 }
1752 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1753}
1754
1755// FIXME? Maybe this could be a TableGen attribute on some registers and
1756// this table could be generated automatically from RegInfo.
1759 const MachineFunction &MF) const {
1760 Register Reg =
1762 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1763 : SystemZ::NoRegister)
1764 .Case("r15",
1765 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1766 .Default(Register());
1767
1768 return Reg;
1769}
1770
1772 const Constant *PersonalityFn) const {
1773 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1774}
1775
1777 const Constant *PersonalityFn) const {
1778 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1779}
1780
1781// Convert condition code in CCReg to an i32 value.
1783 SDLoc DL(CCReg);
1784 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1785 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1786 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1787}
1788
1789// Lower @cc targets via setcc.
1791 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1792 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1793 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1794 return SDValue();
1795
1796 // Check that return type is valid.
1797 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1798 OpInfo.ConstraintVT.getSizeInBits() < 8)
1799 report_fatal_error("Glue output operand is of invalid type");
1800
1801 if (Glue.getNode()) {
1802 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1803 Chain = Glue.getValue(1);
1804 } else
1805 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1806 return getCCResult(DAG, Glue);
1807}
1808
1810 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1811 SelectionDAG &DAG) const {
1812 // Only support length 1 constraints for now.
1813 if (Constraint.size() == 1) {
1814 switch (Constraint[0]) {
1815 case 'I': // Unsigned 8-bit constant
1816 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1817 if (isUInt<8>(C->getZExtValue()))
1818 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1819 Op.getValueType()));
1820 return;
1821
1822 case 'J': // Unsigned 12-bit constant
1823 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1824 if (isUInt<12>(C->getZExtValue()))
1825 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1826 Op.getValueType()));
1827 return;
1828
1829 case 'K': // Signed 16-bit constant
1830 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1831 if (isInt<16>(C->getSExtValue()))
1832 Ops.push_back(DAG.getSignedTargetConstant(
1833 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1834 return;
1835
1836 case 'L': // Signed 20-bit displacement (on all targets we support)
1837 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1838 if (isInt<20>(C->getSExtValue()))
1839 Ops.push_back(DAG.getSignedTargetConstant(
1840 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1841 return;
1842
1843 case 'M': // 0x7fffffff
1844 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1845 if (C->getZExtValue() == 0x7fffffff)
1846 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1847 Op.getValueType()));
1848 return;
1849 }
1850 }
1852}
1853
1854//===----------------------------------------------------------------------===//
1855// Calling conventions
1856//===----------------------------------------------------------------------===//
1857
1858#define GET_CALLING_CONV_IMPL
1859#include "SystemZGenCallingConv.inc"
1860
1862 CallingConv::ID) const {
1863 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1864 SystemZ::R14D, 0 };
1865 return ScratchRegs;
1866}
1867
1869 Type *ToType) const {
1870 return isTruncateFree(FromType, ToType);
1871}
1872
1874 return CI->isTailCall();
1875}
1876
1877// Value is a value that has been passed to us in the location described by VA
1878// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1879// any loads onto Chain.
1881 CCValAssign &VA, SDValue Chain,
1882 SDValue Value) {
1883 // If the argument has been promoted from a smaller type, insert an
1884 // assertion to capture this.
1885 if (VA.getLocInfo() == CCValAssign::SExt)
1887 DAG.getValueType(VA.getValVT()));
1888 else if (VA.getLocInfo() == CCValAssign::ZExt)
1890 DAG.getValueType(VA.getValVT()));
1891
1892 if (VA.isExtInLoc())
1893 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1894 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1895 // If this is a short vector argument loaded from the stack,
1896 // extend from i64 to full vector size and then bitcast.
1897 assert(VA.getLocVT() == MVT::i64);
1898 assert(VA.getValVT().isVector());
1899 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1900 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1901 } else
1902 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1903 return Value;
1904}
1905
1906// Value is a value of type VA.getValVT() that we need to copy into
1907// the location described by VA. Return a copy of Value converted to
1908// VA.getValVT(). The caller is responsible for handling indirect values.
1910 CCValAssign &VA, SDValue Value) {
1911 switch (VA.getLocInfo()) {
1912 case CCValAssign::SExt:
1913 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1914 case CCValAssign::ZExt:
1915 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1916 case CCValAssign::AExt:
1917 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1918 case CCValAssign::BCvt: {
1919 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
1920 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
1921 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
1922 // For an f32 vararg we need to first promote it to an f64 and then
1923 // bitcast it to an i64.
1924 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
1925 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
1926 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
1927 ? MVT::v2i64
1928 : VA.getLocVT();
1929 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
1930 // For ELF, this is a short vector argument to be stored to the stack,
1931 // bitcast to v2i64 and then extract first element.
1932 if (BitCastToType == MVT::v2i64)
1933 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1934 DAG.getConstant(0, DL, MVT::i32));
1935 return Value;
1936 }
1937 case CCValAssign::Full:
1938 return Value;
1939 default:
1940 llvm_unreachable("Unhandled getLocInfo()");
1941 }
1942}
1943
1945 SDLoc DL(In);
1946 SDValue Lo, Hi;
1947 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
1948 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
1949 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
1950 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
1951 DAG.getConstant(64, DL, MVT::i32)));
1952 } else {
1953 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
1954 }
1955
1956 // FIXME: If v2i64 were a legal type, we could use it instead of
1957 // Untyped here. This might enable improved folding.
1958 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
1959 MVT::Untyped, Hi, Lo);
1960 return SDValue(Pair, 0);
1961}
1962
1964 SDLoc DL(In);
1965 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
1966 DL, MVT::i64, In);
1967 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
1968 DL, MVT::i64, In);
1969
1970 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
1971 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
1972 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
1973 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
1974 DAG.getConstant(64, DL, MVT::i32));
1975 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
1976 } else {
1977 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
1978 }
1979}
1980
1982 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
1983 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
1984 EVT ValueVT = Val.getValueType();
1985 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
1986 // Inline assembly operand.
1987 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
1988 return true;
1989 }
1990
1991 return false;
1992}
1993
1995 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
1996 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
1997 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
1998 // Inline assembly operand.
1999 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2000 return DAG.getBitcast(ValueVT, Res);
2001 }
2002
2003 return SDValue();
2004}
2005
2006// The first part of a split stack argument is at index I in Args (and
2007// ArgLocs). Return the type of a part and the number of them by reference.
2008template <class ArgTy>
2010 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2011 MVT &PartVT, unsigned &NumParts) {
2012 if (!Args[I].Flags.isSplit())
2013 return false;
2014 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2015 "ArgLocs havoc.");
2016 PartVT = ArgLocs[I].getValVT();
2017 NumParts = 1;
2018 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2019 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2020 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2021 ++NumParts;
2022 if (Args[PartIdx].Flags.isSplitEnd())
2023 break;
2024 }
2025 return true;
2026}
2027
2029 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2030 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2031 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2033 MachineFrameInfo &MFI = MF.getFrameInfo();
2034 MachineRegisterInfo &MRI = MF.getRegInfo();
2035 SystemZMachineFunctionInfo *FuncInfo =
2037 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2038 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2039
2040 // Assign locations to all of the incoming arguments.
2042 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2043 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2044 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2045
2046 unsigned NumFixedGPRs = 0;
2047 unsigned NumFixedFPRs = 0;
2048 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2049 SDValue ArgValue;
2050 CCValAssign &VA = ArgLocs[I];
2051 EVT LocVT = VA.getLocVT();
2052 if (VA.isRegLoc()) {
2053 // Arguments passed in registers
2054 const TargetRegisterClass *RC;
2055 switch (LocVT.getSimpleVT().SimpleTy) {
2056 default:
2057 // Integers smaller than i64 should be promoted to i64.
2058 llvm_unreachable("Unexpected argument type");
2059 case MVT::i32:
2060 NumFixedGPRs += 1;
2061 RC = &SystemZ::GR32BitRegClass;
2062 break;
2063 case MVT::i64:
2064 NumFixedGPRs += 1;
2065 RC = &SystemZ::GR64BitRegClass;
2066 break;
2067 case MVT::f16:
2068 NumFixedFPRs += 1;
2069 RC = &SystemZ::FP16BitRegClass;
2070 break;
2071 case MVT::f32:
2072 NumFixedFPRs += 1;
2073 RC = &SystemZ::FP32BitRegClass;
2074 break;
2075 case MVT::f64:
2076 NumFixedFPRs += 1;
2077 RC = &SystemZ::FP64BitRegClass;
2078 break;
2079 case MVT::f128:
2080 NumFixedFPRs += 2;
2081 RC = &SystemZ::FP128BitRegClass;
2082 break;
2083 case MVT::v16i8:
2084 case MVT::v8i16:
2085 case MVT::v4i32:
2086 case MVT::v2i64:
2087 case MVT::v8f16:
2088 case MVT::v4f32:
2089 case MVT::v2f64:
2090 RC = &SystemZ::VR128BitRegClass;
2091 break;
2092 }
2093
2094 Register VReg = MRI.createVirtualRegister(RC);
2095 MRI.addLiveIn(VA.getLocReg(), VReg);
2096 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2097 } else {
2098 assert(VA.isMemLoc() && "Argument not register or memory");
2099
2100 // Create the frame index object for this incoming parameter.
2101 // FIXME: Pre-include call frame size in the offset, should not
2102 // need to manually add it here.
2103 int64_t ArgSPOffset = VA.getLocMemOffset();
2104 if (Subtarget.isTargetXPLINK64()) {
2105 auto &XPRegs =
2106 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2107 ArgSPOffset += XPRegs.getCallFrameSize();
2108 }
2109 int FI =
2110 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2111
2112 // Create the SelectionDAG nodes corresponding to a load
2113 // from this parameter. Unpromoted ints and floats are
2114 // passed as right-justified 8-byte values.
2115 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2116 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2117 VA.getLocVT() == MVT::f16) {
2118 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2119 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2120 DAG.getIntPtrConstant(SlotOffs, DL));
2121 }
2122 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2124 }
2125
2126 // Convert the value of the argument register into the value that's
2127 // being passed.
2128 if (VA.getLocInfo() == CCValAssign::Indirect) {
2129 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2131 // If the original argument was split (e.g. i128), we need
2132 // to load all parts of it here (using the same address).
2133 MVT PartVT;
2134 unsigned NumParts;
2135 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2136 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2137 ++I;
2138 CCValAssign &PartVA = ArgLocs[I];
2139 unsigned PartOffset = Ins[I].PartOffset;
2140 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2141 DAG.getIntPtrConstant(PartOffset, DL));
2142 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2144 assert(PartOffset && "Offset should be non-zero.");
2145 }
2146 }
2147 } else
2148 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2149 }
2150
2151 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2152 // Save the number of non-varargs registers for later use by va_start, etc.
2153 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2154 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2155
2156 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2157 Subtarget.getSpecialRegisters());
2158
2159 // Likewise the address (in the form of a frame index) of where the
2160 // first stack vararg would be. The 1-byte size here is arbitrary.
2161 // FIXME: Pre-include call frame size in the offset, should not
2162 // need to manually add it here.
2163 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2164 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2165 FuncInfo->setVarArgsFrameIndex(FI);
2166 }
2167
2168 if (IsVarArg && Subtarget.isTargetELF()) {
2169 // Save the number of non-varargs registers for later use by va_start, etc.
2170 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2171 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2172
2173 // Likewise the address (in the form of a frame index) of where the
2174 // first stack vararg would be. The 1-byte size here is arbitrary.
2175 int64_t VarArgsOffset = CCInfo.getStackSize();
2176 FuncInfo->setVarArgsFrameIndex(
2177 MFI.CreateFixedObject(1, VarArgsOffset, true));
2178
2179 // ...and a similar frame index for the caller-allocated save area
2180 // that will be used to store the incoming registers.
2181 int64_t RegSaveOffset =
2182 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2183 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2184 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2185
2186 // Store the FPR varargs in the reserved frame slots. (We store the
2187 // GPRs as part of the prologue.)
2188 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2190 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2191 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2192 int FI =
2194 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2196 &SystemZ::FP64BitRegClass);
2197 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2198 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2200 }
2201 // Join the stores, which are independent of one another.
2202 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2203 ArrayRef(&MemOps[NumFixedFPRs],
2204 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2205 }
2206 }
2207
2208 if (Subtarget.isTargetXPLINK64()) {
2209 // Create virual register for handling incoming "ADA" special register (R5)
2210 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2211 Register ADAvReg = MRI.createVirtualRegister(RC);
2212 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2213 Subtarget.getSpecialRegisters());
2214 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2215 FuncInfo->setADAVirtualRegister(ADAvReg);
2216 }
2217 return Chain;
2218}
2219
2220static bool canUseSiblingCall(const CCState &ArgCCInfo,
2223 // Punt if there are any indirect or stack arguments, or if the call
2224 // needs the callee-saved argument register R6, or if the call uses
2225 // the callee-saved register arguments SwiftSelf and SwiftError.
2226 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2227 CCValAssign &VA = ArgLocs[I];
2229 return false;
2230 if (!VA.isRegLoc())
2231 return false;
2232 Register Reg = VA.getLocReg();
2233 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2234 return false;
2235 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2236 return false;
2237 }
2238 return true;
2239}
2240
2242 unsigned Offset, bool LoadAdr = false) {
2245 Register ADAvReg = MFI->getADAVirtualRegister();
2247
2248 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2249 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2250
2251 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2252 if (!LoadAdr)
2253 Result = DAG.getLoad(
2254 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2256
2257 return Result;
2258}
2259
2260// ADA access using Global value
2261// Note: for functions, address of descriptor is returned
2263 EVT PtrVT) {
2264 unsigned ADAtype;
2265 bool LoadAddr = false;
2266 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2267 bool IsFunction =
2268 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2269 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2270
2271 if (IsFunction) {
2272 if (IsInternal) {
2274 LoadAddr = true;
2275 } else
2277 } else {
2279 }
2280 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2281
2282 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2283}
2284
2285static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2286 SDLoc &DL, SDValue &Chain) {
2287 unsigned ADADelta = 0; // ADA offset in desc.
2288 unsigned EPADelta = 8; // EPA offset in desc.
2291
2292 // XPLink calling convention.
2293 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2294 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2295 G->getGlobal()->hasPrivateLinkage());
2296 if (IsInternal) {
2299 Register ADAvReg = MFI->getADAVirtualRegister();
2300 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2301 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2302 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2303 return true;
2304 } else {
2306 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2307 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2308 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2309 }
2310 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2312 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2313 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2314 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2315 } else {
2316 // Function pointer case
2317 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2318 DAG.getConstant(ADADelta, DL, PtrVT));
2319 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2321 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2322 DAG.getConstant(EPADelta, DL, PtrVT));
2323 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2325 }
2326 return false;
2327}
2328
2329SDValue
2331 SmallVectorImpl<SDValue> &InVals) const {
2332 SelectionDAG &DAG = CLI.DAG;
2333 SDLoc &DL = CLI.DL;
2335 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2337 SDValue Chain = CLI.Chain;
2338 SDValue Callee = CLI.Callee;
2339 bool &IsTailCall = CLI.IsTailCall;
2340 CallingConv::ID CallConv = CLI.CallConv;
2341 bool IsVarArg = CLI.IsVarArg;
2343 EVT PtrVT = getPointerTy(MF.getDataLayout());
2344 LLVMContext &Ctx = *DAG.getContext();
2345 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2346
2347 // FIXME: z/OS support to be added in later.
2348 if (Subtarget.isTargetXPLINK64())
2349 IsTailCall = false;
2350
2351 // Integer args <=32 bits should have an extension attribute.
2352 verifyNarrowIntegerArgs_Call(Outs, &MF.getFunction(), Callee);
2353
2354 // Analyze the operands of the call, assigning locations to each operand.
2356 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2357 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2358
2359 // We don't support GuaranteedTailCallOpt, only automatically-detected
2360 // sibling calls.
2361 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2362 IsTailCall = false;
2363
2364 // Get a count of how many bytes are to be pushed on the stack.
2365 unsigned NumBytes = ArgCCInfo.getStackSize();
2366
2367 // Mark the start of the call.
2368 if (!IsTailCall)
2369 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2370
2371 // Copy argument values to their designated locations.
2373 SmallVector<SDValue, 8> MemOpChains;
2374 SDValue StackPtr;
2375 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2376 CCValAssign &VA = ArgLocs[I];
2377 SDValue ArgValue = OutVals[I];
2378
2379 if (VA.getLocInfo() == CCValAssign::Indirect) {
2380 // Store the argument in a stack slot and pass its address.
2381 EVT SlotVT;
2382 MVT PartVT;
2383 unsigned NumParts = 1;
2384 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2385 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2386 else
2387 SlotVT = Outs[I].VT;
2388 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2389 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2390
2391 MachinePointerInfo StackPtrInfo =
2393 MemOpChains.push_back(
2394 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2395 // If the original argument was split (e.g. i128), we need
2396 // to store all parts of it here (and pass just one address).
2397 assert(Outs[I].PartOffset == 0);
2398 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2399 ++I;
2400 SDValue PartValue = OutVals[I];
2401 unsigned PartOffset = Outs[I].PartOffset;
2402 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2403 DAG.getIntPtrConstant(PartOffset, DL));
2404 MemOpChains.push_back(
2405 DAG.getStore(Chain, DL, PartValue, Address,
2406 StackPtrInfo.getWithOffset(PartOffset)));
2407 assert(PartOffset && "Offset should be non-zero.");
2408 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2409 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2410 }
2411 ArgValue = SpillSlot;
2412 } else
2413 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2414
2415 if (VA.isRegLoc()) {
2416 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2417 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2418 // and low values.
2419 if (VA.getLocVT() == MVT::i128)
2420 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2421 // Queue up the argument copies and emit them at the end.
2422 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2423 } else {
2424 assert(VA.isMemLoc() && "Argument not register or memory");
2425
2426 // Work out the address of the stack slot. Unpromoted ints and
2427 // floats are passed as right-justified 8-byte values.
2428 if (!StackPtr.getNode())
2429 StackPtr = DAG.getCopyFromReg(Chain, DL,
2430 Regs->getStackPointerRegister(), PtrVT);
2431 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2432 VA.getLocMemOffset();
2433 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2434 Offset += 4;
2435 else if (VA.getLocVT() == MVT::f16)
2436 Offset += 6;
2437 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2439
2440 // Emit the store.
2441 MemOpChains.push_back(
2442 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2443
2444 // Although long doubles or vectors are passed through the stack when
2445 // they are vararg (non-fixed arguments), if a long double or vector
2446 // occupies the third and fourth slot of the argument list GPR3 should
2447 // still shadow the third slot of the argument list.
2448 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2449 SDValue ShadowArgValue =
2450 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2451 DAG.getIntPtrConstant(1, DL));
2452 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2453 }
2454 }
2455 }
2456
2457 // Join the stores, which are independent of one another.
2458 if (!MemOpChains.empty())
2459 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2460
2461 // Accept direct calls by converting symbolic call addresses to the
2462 // associated Target* opcodes. Force %r1 to be used for indirect
2463 // tail calls.
2464 SDValue Glue;
2465
2466 if (Subtarget.isTargetXPLINK64()) {
2467 SDValue ADA;
2468 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2469 if (!IsBRASL) {
2470 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2471 ->getAddressOfCalleeRegister();
2472 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2473 Glue = Chain.getValue(1);
2474 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2475 }
2476 RegsToPass.push_back(std::make_pair(
2477 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2478 } else {
2479 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2480 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2481 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2482 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2483 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2484 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2485 } else if (IsTailCall) {
2486 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2487 Glue = Chain.getValue(1);
2488 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2489 }
2490 }
2491
2492 // Build a sequence of copy-to-reg nodes, chained and glued together.
2493 for (const auto &[Reg, N] : RegsToPass) {
2494 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2495 Glue = Chain.getValue(1);
2496 }
2497
2498 // The first call operand is the chain and the second is the target address.
2500 Ops.push_back(Chain);
2501 Ops.push_back(Callee);
2502
2503 // Add argument registers to the end of the list so that they are
2504 // known live into the call.
2505 for (const auto &[Reg, N] : RegsToPass)
2506 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2507
2508 // Add a register mask operand representing the call-preserved registers.
2509 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2510 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2511 assert(Mask && "Missing call preserved mask for calling convention");
2512 Ops.push_back(DAG.getRegisterMask(Mask));
2513
2514 // Glue the call to the argument copies, if any.
2515 if (Glue.getNode())
2516 Ops.push_back(Glue);
2517
2518 // Emit the call.
2519 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2520 if (IsTailCall) {
2521 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2522 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2523 return Ret;
2524 }
2525 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2526 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2527 Glue = Chain.getValue(1);
2528
2529 // Mark the end of the call, which is glued to the call itself.
2530 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2531 Glue = Chain.getValue(1);
2532
2533 // Assign locations to each value returned by this call.
2535 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2536 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2537
2538 // Copy all of the result registers out of their specified physreg.
2539 for (CCValAssign &VA : RetLocs) {
2540 // Copy the value out, gluing the copy to the end of the call sequence.
2541 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2542 VA.getLocVT(), Glue);
2543 Chain = RetValue.getValue(1);
2544 Glue = RetValue.getValue(2);
2545
2546 // Convert the value of the return register into the value that's
2547 // being returned.
2548 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2549 }
2550
2551 return Chain;
2552}
2553
2554// Generate a call taking the given operands as arguments and returning a
2555// result of type RetVT.
2557 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2558 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2559 bool DoesNotReturn, bool IsReturnValueUsed) const {
2561 Args.reserve(Ops.size());
2562
2563 for (SDValue Op : Ops) {
2565 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2566 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2567 Entry.IsZExt = !Entry.IsSExt;
2568 Args.push_back(Entry);
2569 }
2570
2571 SDValue Callee =
2572 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2573
2574 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2576 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2577 CLI.setDebugLoc(DL)
2578 .setChain(Chain)
2579 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2580 .setNoReturn(DoesNotReturn)
2581 .setDiscardResult(!IsReturnValueUsed)
2582 .setSExtResult(SignExtend)
2583 .setZExtResult(!SignExtend);
2584 return LowerCallTo(CLI);
2585}
2586
2588 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2589 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2590 const Type *RetTy) const {
2591 // Special case that we cannot easily detect in RetCC_SystemZ since
2592 // i128 may not be a legal type.
2593 for (auto &Out : Outs)
2594 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2595 return false;
2596
2598 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2599 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2600}
2601
2602SDValue
2604 bool IsVarArg,
2606 const SmallVectorImpl<SDValue> &OutVals,
2607 const SDLoc &DL, SelectionDAG &DAG) const {
2609
2610 // Integer args <=32 bits should have an extension attribute.
2611 verifyNarrowIntegerArgs_Ret(Outs, &MF.getFunction());
2612
2613 // Assign locations to each returned value.
2615 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2616 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2617
2618 // Quick exit for void returns
2619 if (RetLocs.empty())
2620 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2621
2622 if (CallConv == CallingConv::GHC)
2623 report_fatal_error("GHC functions return void only");
2624
2625 // Copy the result values into the output registers.
2626 SDValue Glue;
2628 RetOps.push_back(Chain);
2629 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2630 CCValAssign &VA = RetLocs[I];
2631 SDValue RetValue = OutVals[I];
2632
2633 // Make the return register live on exit.
2634 assert(VA.isRegLoc() && "Can only return in registers!");
2635
2636 // Promote the value as required.
2637 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2638
2639 // Chain and glue the copies together.
2640 Register Reg = VA.getLocReg();
2641 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2642 Glue = Chain.getValue(1);
2643 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2644 }
2645
2646 // Update chain and glue.
2647 RetOps[0] = Chain;
2648 if (Glue.getNode())
2649 RetOps.push_back(Glue);
2650
2651 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2652}
2653
2654// Return true if Op is an intrinsic node with chain that returns the CC value
2655// as its only (other) argument. Provide the associated SystemZISD opcode and
2656// the mask of valid CC values if so.
2657static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2658 unsigned &CCValid) {
2659 unsigned Id = Op.getConstantOperandVal(1);
2660 switch (Id) {
2661 case Intrinsic::s390_tbegin:
2662 Opcode = SystemZISD::TBEGIN;
2663 CCValid = SystemZ::CCMASK_TBEGIN;
2664 return true;
2665
2666 case Intrinsic::s390_tbegin_nofloat:
2667 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2668 CCValid = SystemZ::CCMASK_TBEGIN;
2669 return true;
2670
2671 case Intrinsic::s390_tend:
2672 Opcode = SystemZISD::TEND;
2673 CCValid = SystemZ::CCMASK_TEND;
2674 return true;
2675
2676 default:
2677 return false;
2678 }
2679}
2680
2681// Return true if Op is an intrinsic node without chain that returns the
2682// CC value as its final argument. Provide the associated SystemZISD
2683// opcode and the mask of valid CC values if so.
2684static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2685 unsigned Id = Op.getConstantOperandVal(0);
2686 switch (Id) {
2687 case Intrinsic::s390_vpkshs:
2688 case Intrinsic::s390_vpksfs:
2689 case Intrinsic::s390_vpksgs:
2690 Opcode = SystemZISD::PACKS_CC;
2691 CCValid = SystemZ::CCMASK_VCMP;
2692 return true;
2693
2694 case Intrinsic::s390_vpklshs:
2695 case Intrinsic::s390_vpklsfs:
2696 case Intrinsic::s390_vpklsgs:
2697 Opcode = SystemZISD::PACKLS_CC;
2698 CCValid = SystemZ::CCMASK_VCMP;
2699 return true;
2700
2701 case Intrinsic::s390_vceqbs:
2702 case Intrinsic::s390_vceqhs:
2703 case Intrinsic::s390_vceqfs:
2704 case Intrinsic::s390_vceqgs:
2705 case Intrinsic::s390_vceqqs:
2706 Opcode = SystemZISD::VICMPES;
2707 CCValid = SystemZ::CCMASK_VCMP;
2708 return true;
2709
2710 case Intrinsic::s390_vchbs:
2711 case Intrinsic::s390_vchhs:
2712 case Intrinsic::s390_vchfs:
2713 case Intrinsic::s390_vchgs:
2714 case Intrinsic::s390_vchqs:
2715 Opcode = SystemZISD::VICMPHS;
2716 CCValid = SystemZ::CCMASK_VCMP;
2717 return true;
2718
2719 case Intrinsic::s390_vchlbs:
2720 case Intrinsic::s390_vchlhs:
2721 case Intrinsic::s390_vchlfs:
2722 case Intrinsic::s390_vchlgs:
2723 case Intrinsic::s390_vchlqs:
2724 Opcode = SystemZISD::VICMPHLS;
2725 CCValid = SystemZ::CCMASK_VCMP;
2726 return true;
2727
2728 case Intrinsic::s390_vtm:
2729 Opcode = SystemZISD::VTM;
2730 CCValid = SystemZ::CCMASK_VCMP;
2731 return true;
2732
2733 case Intrinsic::s390_vfaebs:
2734 case Intrinsic::s390_vfaehs:
2735 case Intrinsic::s390_vfaefs:
2736 Opcode = SystemZISD::VFAE_CC;
2737 CCValid = SystemZ::CCMASK_ANY;
2738 return true;
2739
2740 case Intrinsic::s390_vfaezbs:
2741 case Intrinsic::s390_vfaezhs:
2742 case Intrinsic::s390_vfaezfs:
2743 Opcode = SystemZISD::VFAEZ_CC;
2744 CCValid = SystemZ::CCMASK_ANY;
2745 return true;
2746
2747 case Intrinsic::s390_vfeebs:
2748 case Intrinsic::s390_vfeehs:
2749 case Intrinsic::s390_vfeefs:
2750 Opcode = SystemZISD::VFEE_CC;
2751 CCValid = SystemZ::CCMASK_ANY;
2752 return true;
2753
2754 case Intrinsic::s390_vfeezbs:
2755 case Intrinsic::s390_vfeezhs:
2756 case Intrinsic::s390_vfeezfs:
2757 Opcode = SystemZISD::VFEEZ_CC;
2758 CCValid = SystemZ::CCMASK_ANY;
2759 return true;
2760
2761 case Intrinsic::s390_vfenebs:
2762 case Intrinsic::s390_vfenehs:
2763 case Intrinsic::s390_vfenefs:
2764 Opcode = SystemZISD::VFENE_CC;
2765 CCValid = SystemZ::CCMASK_ANY;
2766 return true;
2767
2768 case Intrinsic::s390_vfenezbs:
2769 case Intrinsic::s390_vfenezhs:
2770 case Intrinsic::s390_vfenezfs:
2771 Opcode = SystemZISD::VFENEZ_CC;
2772 CCValid = SystemZ::CCMASK_ANY;
2773 return true;
2774
2775 case Intrinsic::s390_vistrbs:
2776 case Intrinsic::s390_vistrhs:
2777 case Intrinsic::s390_vistrfs:
2778 Opcode = SystemZISD::VISTR_CC;
2780 return true;
2781
2782 case Intrinsic::s390_vstrcbs:
2783 case Intrinsic::s390_vstrchs:
2784 case Intrinsic::s390_vstrcfs:
2785 Opcode = SystemZISD::VSTRC_CC;
2786 CCValid = SystemZ::CCMASK_ANY;
2787 return true;
2788
2789 case Intrinsic::s390_vstrczbs:
2790 case Intrinsic::s390_vstrczhs:
2791 case Intrinsic::s390_vstrczfs:
2792 Opcode = SystemZISD::VSTRCZ_CC;
2793 CCValid = SystemZ::CCMASK_ANY;
2794 return true;
2795
2796 case Intrinsic::s390_vstrsb:
2797 case Intrinsic::s390_vstrsh:
2798 case Intrinsic::s390_vstrsf:
2799 Opcode = SystemZISD::VSTRS_CC;
2800 CCValid = SystemZ::CCMASK_ANY;
2801 return true;
2802
2803 case Intrinsic::s390_vstrszb:
2804 case Intrinsic::s390_vstrszh:
2805 case Intrinsic::s390_vstrszf:
2806 Opcode = SystemZISD::VSTRSZ_CC;
2807 CCValid = SystemZ::CCMASK_ANY;
2808 return true;
2809
2810 case Intrinsic::s390_vfcedbs:
2811 case Intrinsic::s390_vfcesbs:
2812 Opcode = SystemZISD::VFCMPES;
2813 CCValid = SystemZ::CCMASK_VCMP;
2814 return true;
2815
2816 case Intrinsic::s390_vfchdbs:
2817 case Intrinsic::s390_vfchsbs:
2818 Opcode = SystemZISD::VFCMPHS;
2819 CCValid = SystemZ::CCMASK_VCMP;
2820 return true;
2821
2822 case Intrinsic::s390_vfchedbs:
2823 case Intrinsic::s390_vfchesbs:
2824 Opcode = SystemZISD::VFCMPHES;
2825 CCValid = SystemZ::CCMASK_VCMP;
2826 return true;
2827
2828 case Intrinsic::s390_vftcidb:
2829 case Intrinsic::s390_vftcisb:
2830 Opcode = SystemZISD::VFTCI;
2831 CCValid = SystemZ::CCMASK_VCMP;
2832 return true;
2833
2834 case Intrinsic::s390_tdc:
2835 Opcode = SystemZISD::TDC;
2836 CCValid = SystemZ::CCMASK_TDC;
2837 return true;
2838
2839 default:
2840 return false;
2841 }
2842}
2843
2844// Emit an intrinsic with chain and an explicit CC register result.
2846 unsigned Opcode) {
2847 // Copy all operands except the intrinsic ID.
2848 unsigned NumOps = Op.getNumOperands();
2850 Ops.reserve(NumOps - 1);
2851 Ops.push_back(Op.getOperand(0));
2852 for (unsigned I = 2; I < NumOps; ++I)
2853 Ops.push_back(Op.getOperand(I));
2854
2855 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2856 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2857 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2858 SDValue OldChain = SDValue(Op.getNode(), 1);
2859 SDValue NewChain = SDValue(Intr.getNode(), 1);
2860 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2861 return Intr.getNode();
2862}
2863
2864// Emit an intrinsic with an explicit CC register result.
2866 unsigned Opcode) {
2867 // Copy all operands except the intrinsic ID.
2868 SDLoc DL(Op);
2869 unsigned NumOps = Op.getNumOperands();
2871 Ops.reserve(NumOps - 1);
2872 for (unsigned I = 1; I < NumOps; ++I) {
2873 SDValue CurrOper = Op.getOperand(I);
2874 if (CurrOper.getValueType() == MVT::f16) {
2875 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2876 "Unhandled intrinsic with f16 operand.");
2877 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2878 }
2879 Ops.push_back(CurrOper);
2880 }
2881
2882 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2883 return Intr.getNode();
2884}
2885
2886// CC is a comparison that will be implemented using an integer or
2887// floating-point comparison. Return the condition code mask for
2888// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2889// unsigned comparisons and clear for signed ones. In the floating-point
2890// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2892#define CONV(X) \
2893 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2894 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2895 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2896
2897 switch (CC) {
2898 default:
2899 llvm_unreachable("Invalid integer condition!");
2900
2901 CONV(EQ);
2902 CONV(NE);
2903 CONV(GT);
2904 CONV(GE);
2905 CONV(LT);
2906 CONV(LE);
2907
2908 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2910 }
2911#undef CONV
2912}
2913
2914// If C can be converted to a comparison against zero, adjust the operands
2915// as necessary.
2916static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2917 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2918 return;
2919
2920 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2921 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2922 return;
2923
2924 int64_t Value = ConstOp1->getSExtValue();
2925 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2926 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2927 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2928 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2929 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2930 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2931 }
2932}
2933
2934// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2935// adjust the operands as necessary.
2936static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2937 Comparison &C) {
2938 // For us to make any changes, it must a comparison between a single-use
2939 // load and a constant.
2940 if (!C.Op0.hasOneUse() ||
2941 C.Op0.getOpcode() != ISD::LOAD ||
2942 C.Op1.getOpcode() != ISD::Constant)
2943 return;
2944
2945 // We must have an 8- or 16-bit load.
2946 auto *Load = cast<LoadSDNode>(C.Op0);
2947 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
2948 if ((NumBits != 8 && NumBits != 16) ||
2949 NumBits != Load->getMemoryVT().getStoreSizeInBits())
2950 return;
2951
2952 // The load must be an extending one and the constant must be within the
2953 // range of the unextended value.
2954 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2955 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2956 return;
2957 uint64_t Value = ConstOp1->getZExtValue();
2958 uint64_t Mask = (1 << NumBits) - 1;
2959 if (Load->getExtensionType() == ISD::SEXTLOAD) {
2960 // Make sure that ConstOp1 is in range of C.Op0.
2961 int64_t SignedValue = ConstOp1->getSExtValue();
2962 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2963 return;
2964 if (C.ICmpType != SystemZICMP::SignedOnly) {
2965 // Unsigned comparison between two sign-extended values is equivalent
2966 // to unsigned comparison between two zero-extended values.
2967 Value &= Mask;
2968 } else if (NumBits == 8) {
2969 // Try to treat the comparison as unsigned, so that we can use CLI.
2970 // Adjust CCMask and Value as necessary.
2971 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2972 // Test whether the high bit of the byte is set.
2973 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2974 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2975 // Test whether the high bit of the byte is clear.
2976 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2977 else
2978 // No instruction exists for this combination.
2979 return;
2980 C.ICmpType = SystemZICMP::UnsignedOnly;
2981 }
2982 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2983 if (Value > Mask)
2984 return;
2985 // If the constant is in range, we can use any comparison.
2986 C.ICmpType = SystemZICMP::Any;
2987 } else
2988 return;
2989
2990 // Make sure that the first operand is an i32 of the right extension type.
2991 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2994 if (C.Op0.getValueType() != MVT::i32 ||
2995 Load->getExtensionType() != ExtType) {
2996 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2997 Load->getBasePtr(), Load->getPointerInfo(),
2998 Load->getMemoryVT(), Load->getAlign(),
2999 Load->getMemOperand()->getFlags());
3000 // Update the chain uses.
3001 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3002 }
3003
3004 // Make sure that the second operand is an i32 with the right value.
3005 if (C.Op1.getValueType() != MVT::i32 ||
3006 Value != ConstOp1->getZExtValue())
3007 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3008}
3009
3010// Return true if Op is either an unextended load, or a load suitable
3011// for integer register-memory comparisons of type ICmpType.
3012static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3013 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3014 if (Load) {
3015 // There are no instructions to compare a register with a memory byte.
3016 if (Load->getMemoryVT() == MVT::i8)
3017 return false;
3018 // Otherwise decide on extension type.
3019 switch (Load->getExtensionType()) {
3020 case ISD::NON_EXTLOAD:
3021 return true;
3022 case ISD::SEXTLOAD:
3023 return ICmpType != SystemZICMP::UnsignedOnly;
3024 case ISD::ZEXTLOAD:
3025 return ICmpType != SystemZICMP::SignedOnly;
3026 default:
3027 break;
3028 }
3029 }
3030 return false;
3031}
3032
3033// Return true if it is better to swap the operands of C.
3034static bool shouldSwapCmpOperands(const Comparison &C) {
3035 // If one side of the compare is a load of the stackguard reference value,
3036 // then that load should be Op1.
3037 if (C.Op0.isMachineOpcode() &&
3038 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3039 return true;
3040
3041 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3042 if (C.Op0.getValueType() == MVT::i128)
3043 return false;
3044 if (C.Op0.getValueType() == MVT::f128)
3045 return false;
3046
3047 // Always keep a floating-point constant second, since comparisons with
3048 // zero can use LOAD TEST and comparisons with other constants make a
3049 // natural memory operand.
3050 if (isa<ConstantFPSDNode>(C.Op1))
3051 return false;
3052
3053 // Never swap comparisons with zero since there are many ways to optimize
3054 // those later.
3055 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3056 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3057 return false;
3058
3059 // Also keep natural memory operands second if the loaded value is
3060 // only used here. Several comparisons have memory forms.
3061 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3062 return false;
3063
3064 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3065 // In that case we generally prefer the memory to be second.
3066 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3067 // The only exceptions are when the second operand is a constant and
3068 // we can use things like CHHSI.
3069 if (!ConstOp1)
3070 return true;
3071 // The unsigned memory-immediate instructions can handle 16-bit
3072 // unsigned integers.
3073 if (C.ICmpType != SystemZICMP::SignedOnly &&
3074 isUInt<16>(ConstOp1->getZExtValue()))
3075 return false;
3076 // The signed memory-immediate instructions can handle 16-bit
3077 // signed integers.
3078 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3079 isInt<16>(ConstOp1->getSExtValue()))
3080 return false;
3081 return true;
3082 }
3083
3084 // Try to promote the use of CGFR and CLGFR.
3085 unsigned Opcode0 = C.Op0.getOpcode();
3086 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3087 return true;
3088 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3089 return true;
3090 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3091 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3092 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3093 return true;
3094
3095 return false;
3096}
3097
3098// Check whether C tests for equality between X and Y and whether X - Y
3099// or Y - X is also computed. In that case it's better to compare the
3100// result of the subtraction against zero.
3102 Comparison &C) {
3103 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3104 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3105 for (SDNode *N : C.Op0->users()) {
3106 if (N->getOpcode() == ISD::SUB &&
3107 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3108 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3109 // Disable the nsw and nuw flags: the backend needs to handle
3110 // overflow as well during comparison elimination.
3111 N->dropFlags(SDNodeFlags::NoWrap);
3112 C.Op0 = SDValue(N, 0);
3113 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3114 return;
3115 }
3116 }
3117 }
3118}
3119
3120// Check whether C compares a floating-point value with zero and if that
3121// floating-point value is also negated. In this case we can use the
3122// negation to set CC, so avoiding separate LOAD AND TEST and
3123// LOAD (NEGATIVE/COMPLEMENT) instructions.
3124static void adjustForFNeg(Comparison &C) {
3125 // This optimization is invalid for strict comparisons, since FNEG
3126 // does not raise any exceptions.
3127 if (C.Chain)
3128 return;
3129 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3130 if (C1 && C1->isZero()) {
3131 for (SDNode *N : C.Op0->users()) {
3132 if (N->getOpcode() == ISD::FNEG) {
3133 C.Op0 = SDValue(N, 0);
3134 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3135 return;
3136 }
3137 }
3138 }
3139}
3140
3141// Check whether C compares (shl X, 32) with 0 and whether X is
3142// also sign-extended. In that case it is better to test the result
3143// of the sign extension using LTGFR.
3144//
3145// This case is important because InstCombine transforms a comparison
3146// with (sext (trunc X)) into a comparison with (shl X, 32).
3147static void adjustForLTGFR(Comparison &C) {
3148 // Check for a comparison between (shl X, 32) and 0.
3149 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3150 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3151 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3152 if (C1 && C1->getZExtValue() == 32) {
3153 SDValue ShlOp0 = C.Op0.getOperand(0);
3154 // See whether X has any SIGN_EXTEND_INREG uses.
3155 for (SDNode *N : ShlOp0->users()) {
3156 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3157 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3158 C.Op0 = SDValue(N, 0);
3159 return;
3160 }
3161 }
3162 }
3163 }
3164}
3165
3166// If C compares the truncation of an extending load, try to compare
3167// the untruncated value instead. This exposes more opportunities to
3168// reuse CC.
3169static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3170 Comparison &C) {
3171 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3172 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3173 C.Op1.getOpcode() == ISD::Constant &&
3174 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3175 C.Op1->getAsZExtVal() == 0) {
3176 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3177 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3178 C.Op0.getValueSizeInBits().getFixedValue()) {
3179 unsigned Type = L->getExtensionType();
3180 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3181 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3182 C.Op0 = C.Op0.getOperand(0);
3183 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3184 }
3185 }
3186 }
3187}
3188
3189// Adjust if a given Compare is a check of the stack guard against a stack
3190// guard instance on the stack. Specifically, this checks if:
3191// - The operands are a load of the stack guard, and a load from a stack slot
3192// - The original opcode is ICMP
3193// - ICMPType is compatible with unsigned comparison.
3195 Comparison &C) {
3196
3197 // Opcode must be ICMP.
3198 if (C.Opcode != SystemZISD::ICMP)
3199 return;
3200 // ICmpType must be Unsigned or Any.
3201 if (C.ICmpType == SystemZICMP::SignedOnly)
3202 return;
3203 // Op0 must be FrameIndex Load.
3204 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3205 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3206 return;
3207 // Op1 must be LOAD_STACK_GUARD.
3208 if (!C.Op1.isMachineOpcode() ||
3209 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3210 return;
3211
3212 // At this point we are sure that this is a proper CMP_STACKGUARD
3213 // case, update the opcode to reflect this.
3214 C.Opcode = SystemZISD::CMP_STACKGUARD;
3215 C.Op1 = SDValue();
3216}
3217
3218// Return true if shift operation N has an in-range constant shift value.
3219// Store it in ShiftVal if so.
3220static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3221 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222 if (!Shift)
3223 return false;
3224
3225 uint64_t Amount = Shift->getZExtValue();
3226 if (Amount >= N.getValueSizeInBits())
3227 return false;
3228
3229 ShiftVal = Amount;
3230 return true;
3231}
3232
3233// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3234// instruction and whether the CC value is descriptive enough to handle
3235// a comparison of type Opcode between the AND result and CmpVal.
3236// CCMask says which comparison result is being tested and BitSize is
3237// the number of bits in the operands. If TEST UNDER MASK can be used,
3238// return the corresponding CC mask, otherwise return 0.
3239static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3240 uint64_t Mask, uint64_t CmpVal,
3241 unsigned ICmpType) {
3242 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3243
3244 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3245 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3246 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3247 return 0;
3248
3249 // Work out the masks for the lowest and highest bits.
3251 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3252
3253 // Signed ordered comparisons are effectively unsigned if the sign
3254 // bit is dropped.
3255 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3256
3257 // Check for equality comparisons with 0, or the equivalent.
3258 if (CmpVal == 0) {
3259 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3261 if (CCMask == SystemZ::CCMASK_CMP_NE)
3263 }
3264 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3265 if (CCMask == SystemZ::CCMASK_CMP_LT)
3267 if (CCMask == SystemZ::CCMASK_CMP_GE)
3269 }
3270 if (EffectivelyUnsigned && CmpVal < Low) {
3271 if (CCMask == SystemZ::CCMASK_CMP_LE)
3273 if (CCMask == SystemZ::CCMASK_CMP_GT)
3275 }
3276
3277 // Check for equality comparisons with the mask, or the equivalent.
3278 if (CmpVal == Mask) {
3279 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3281 if (CCMask == SystemZ::CCMASK_CMP_NE)
3283 }
3284 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3285 if (CCMask == SystemZ::CCMASK_CMP_GT)
3287 if (CCMask == SystemZ::CCMASK_CMP_LE)
3289 }
3290 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3291 if (CCMask == SystemZ::CCMASK_CMP_GE)
3293 if (CCMask == SystemZ::CCMASK_CMP_LT)
3295 }
3296
3297 // Check for ordered comparisons with the top bit.
3298 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3299 if (CCMask == SystemZ::CCMASK_CMP_LE)
3301 if (CCMask == SystemZ::CCMASK_CMP_GT)
3303 }
3304 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3305 if (CCMask == SystemZ::CCMASK_CMP_LT)
3307 if (CCMask == SystemZ::CCMASK_CMP_GE)
3309 }
3310
3311 // If there are just two bits, we can do equality checks for Low and High
3312 // as well.
3313 if (Mask == Low + High) {
3314 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3316 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3318 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3320 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3322 }
3323
3324 // Looks like we've exhausted our options.
3325 return 0;
3326}
3327
3328// See whether C can be implemented as a TEST UNDER MASK instruction.
3329// Update the arguments with the TM version if so.
3331 Comparison &C) {
3332 // Use VECTOR TEST UNDER MASK for i128 operations.
3333 if (C.Op0.getValueType() == MVT::i128) {
3334 // We can use VTM for EQ/NE comparisons of x & y against 0.
3335 if (C.Op0.getOpcode() == ISD::AND &&
3336 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3337 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3338 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3339 if (Mask && Mask->getAPIntValue() == 0) {
3340 C.Opcode = SystemZISD::VTM;
3341 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3342 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3343 C.CCValid = SystemZ::CCMASK_VCMP;
3344 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3345 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3346 else
3347 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3348 }
3349 }
3350 return;
3351 }
3352
3353 // Check that we have a comparison with a constant.
3354 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3355 if (!ConstOp1)
3356 return;
3357 uint64_t CmpVal = ConstOp1->getZExtValue();
3358
3359 // Check whether the nonconstant input is an AND with a constant mask.
3360 Comparison NewC(C);
3361 uint64_t MaskVal;
3362 ConstantSDNode *Mask = nullptr;
3363 if (C.Op0.getOpcode() == ISD::AND) {
3364 NewC.Op0 = C.Op0.getOperand(0);
3365 NewC.Op1 = C.Op0.getOperand(1);
3366 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3367 if (!Mask)
3368 return;
3369 MaskVal = Mask->getZExtValue();
3370 } else {
3371 // There is no instruction to compare with a 64-bit immediate
3372 // so use TMHH instead if possible. We need an unsigned ordered
3373 // comparison with an i64 immediate.
3374 if (NewC.Op0.getValueType() != MVT::i64 ||
3375 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3376 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3377 NewC.ICmpType == SystemZICMP::SignedOnly)
3378 return;
3379 // Convert LE and GT comparisons into LT and GE.
3380 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3381 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3382 if (CmpVal == uint64_t(-1))
3383 return;
3384 CmpVal += 1;
3385 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3386 }
3387 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3388 // be masked off without changing the result.
3389 MaskVal = -(CmpVal & -CmpVal);
3390 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3391 }
3392 if (!MaskVal)
3393 return;
3394
3395 // Check whether the combination of mask, comparison value and comparison
3396 // type are suitable.
3397 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3398 unsigned NewCCMask, ShiftVal;
3399 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3400 NewC.Op0.getOpcode() == ISD::SHL &&
3401 isSimpleShift(NewC.Op0, ShiftVal) &&
3402 (MaskVal >> ShiftVal != 0) &&
3403 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3404 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3405 MaskVal >> ShiftVal,
3406 CmpVal >> ShiftVal,
3407 SystemZICMP::Any))) {
3408 NewC.Op0 = NewC.Op0.getOperand(0);
3409 MaskVal >>= ShiftVal;
3410 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3411 NewC.Op0.getOpcode() == ISD::SRL &&
3412 isSimpleShift(NewC.Op0, ShiftVal) &&
3413 (MaskVal << ShiftVal != 0) &&
3414 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3415 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3416 MaskVal << ShiftVal,
3417 CmpVal << ShiftVal,
3419 NewC.Op0 = NewC.Op0.getOperand(0);
3420 MaskVal <<= ShiftVal;
3421 } else {
3422 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3423 NewC.ICmpType);
3424 if (!NewCCMask)
3425 return;
3426 }
3427
3428 // Go ahead and make the change.
3429 C.Opcode = SystemZISD::TM;
3430 C.Op0 = NewC.Op0;
3431 if (Mask && Mask->getZExtValue() == MaskVal)
3432 C.Op1 = SDValue(Mask, 0);
3433 else
3434 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3435 C.CCValid = SystemZ::CCMASK_TM;
3436 C.CCMask = NewCCMask;
3437}
3438
3439// Implement i128 comparison in vector registers.
3440static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3441 Comparison &C) {
3442 if (C.Opcode != SystemZISD::ICMP)
3443 return;
3444 if (C.Op0.getValueType() != MVT::i128)
3445 return;
3446
3447 // Recognize vector comparison reductions.
3448 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3449 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3450 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3451 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3452 bool CmpNull = isNullConstant(C.Op1);
3453 SDValue Src = peekThroughBitcasts(C.Op0);
3454 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3455 Src = Src.getOperand(0);
3456 CmpNull = !CmpNull;
3457 }
3458 unsigned Opcode = 0;
3459 if (Src.hasOneUse()) {
3460 switch (Src.getOpcode()) {
3461 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3462 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3463 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3464 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3465 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3466 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3467 default: break;
3468 }
3469 }
3470 if (Opcode) {
3471 C.Opcode = Opcode;
3472 C.Op0 = Src->getOperand(0);
3473 C.Op1 = Src->getOperand(1);
3474 C.CCValid = SystemZ::CCMASK_VCMP;
3476 if (!CmpEq)
3477 C.CCMask ^= C.CCValid;
3478 return;
3479 }
3480 }
3481
3482 // Everything below here is not useful if we have native i128 compares.
3483 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3484 return;
3485
3486 // (In-)Equality comparisons can be implemented via VCEQGS.
3487 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3488 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3489 C.Opcode = SystemZISD::VICMPES;
3490 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3491 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3492 C.CCValid = SystemZ::CCMASK_VCMP;
3493 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3494 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3495 else
3496 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3497 return;
3498 }
3499
3500 // Normalize other comparisons to GT.
3501 bool Swap = false, Invert = false;
3502 switch (C.CCMask) {
3503 case SystemZ::CCMASK_CMP_GT: break;
3504 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3505 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3506 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3507 default: llvm_unreachable("Invalid integer condition!");
3508 }
3509 if (Swap)
3510 std::swap(C.Op0, C.Op1);
3511
3512 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3513 C.Opcode = SystemZISD::UCMP128HI;
3514 else
3515 C.Opcode = SystemZISD::SCMP128HI;
3516 C.CCValid = SystemZ::CCMASK_ANY;
3517 C.CCMask = SystemZ::CCMASK_1;
3518
3519 if (Invert)
3520 C.CCMask ^= C.CCValid;
3521}
3522
3523// See whether the comparison argument contains a redundant AND
3524// and remove it if so. This sometimes happens due to the generic
3525// BRCOND expansion.
3527 Comparison &C) {
3528 if (C.Op0.getOpcode() != ISD::AND)
3529 return;
3530 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3531 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3532 return;
3533 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3534 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3535 return;
3536
3537 C.Op0 = C.Op0.getOperand(0);
3538}
3539
3540// Return a Comparison that tests the condition-code result of intrinsic
3541// node Call against constant integer CC using comparison code Cond.
3542// Opcode is the opcode of the SystemZISD operation for the intrinsic
3543// and CCValid is the set of possible condition-code results.
3544static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3545 SDValue Call, unsigned CCValid, uint64_t CC,
3547 Comparison C(Call, SDValue(), SDValue());
3548 C.Opcode = Opcode;
3549 C.CCValid = CCValid;
3550 if (Cond == ISD::SETEQ)
3551 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3552 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3553 else if (Cond == ISD::SETNE)
3554 // ...and the inverse of that.
3555 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3556 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3557 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3558 // always true for CC>3.
3559 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3560 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3561 // ...and the inverse of that.
3562 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3563 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3564 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3565 // always true for CC>3.
3566 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3567 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3568 // ...and the inverse of that.
3569 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3570 else
3571 llvm_unreachable("Unexpected integer comparison type");
3572 C.CCMask &= CCValid;
3573 return C;
3574}
3575
3576// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3577static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3578 ISD::CondCode Cond, const SDLoc &DL,
3579 SDValue Chain = SDValue(),
3580 bool IsSignaling = false) {
3581 if (CmpOp1.getOpcode() == ISD::Constant) {
3582 assert(!Chain);
3583 unsigned Opcode, CCValid;
3584 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3585 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3586 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3587 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3588 CmpOp1->getAsZExtVal(), Cond);
3589 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3590 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3591 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3592 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3593 CmpOp1->getAsZExtVal(), Cond);
3594 }
3595 Comparison C(CmpOp0, CmpOp1, Chain);
3596 C.CCMask = CCMaskForCondCode(Cond);
3597 if (C.Op0.getValueType().isFloatingPoint()) {
3598 C.CCValid = SystemZ::CCMASK_FCMP;
3599 if (!C.Chain)
3600 C.Opcode = SystemZISD::FCMP;
3601 else if (!IsSignaling)
3602 C.Opcode = SystemZISD::STRICT_FCMP;
3603 else
3604 C.Opcode = SystemZISD::STRICT_FCMPS;
3606 } else {
3607 assert(!C.Chain);
3608 C.CCValid = SystemZ::CCMASK_ICMP;
3609 C.Opcode = SystemZISD::ICMP;
3610 // Choose the type of comparison. Equality and inequality tests can
3611 // use either signed or unsigned comparisons. The choice also doesn't
3612 // matter if both sign bits are known to be clear. In those cases we
3613 // want to give the main isel code the freedom to choose whichever
3614 // form fits best.
3615 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3616 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3617 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3618 C.ICmpType = SystemZICMP::Any;
3619 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3620 C.ICmpType = SystemZICMP::UnsignedOnly;
3621 else
3622 C.ICmpType = SystemZICMP::SignedOnly;
3623 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3624 adjustForRedundantAnd(DAG, DL, C);
3625 adjustZeroCmp(DAG, DL, C);
3626 adjustSubwordCmp(DAG, DL, C);
3627 adjustForSubtraction(DAG, DL, C);
3629 adjustICmpTruncate(DAG, DL, C);
3630 }
3631
3632 if (shouldSwapCmpOperands(C)) {
3633 std::swap(C.Op0, C.Op1);
3634 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3635 }
3636
3638 adjustICmp128(DAG, DL, C);
3640 return C;
3641}
3642
3643// Emit the comparison instruction described by C.
3644static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3645 if (!C.Op1.getNode()) {
3646 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3647 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3648 SDNode *Node;
3649 switch (C.Op0.getOpcode()) {
3651 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3652 return SDValue(Node, 0);
3654 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3655 return SDValue(Node, Node->getNumValues() - 1);
3656 default:
3657 llvm_unreachable("Invalid comparison operands");
3658 }
3659 }
3660 if (C.Opcode == SystemZISD::ICMP)
3661 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3662 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3663 if (C.Opcode == SystemZISD::TM) {
3664 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3666 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3667 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3668 }
3669 if (C.Opcode == SystemZISD::VICMPES ||
3670 C.Opcode == SystemZISD::VICMPHS ||
3671 C.Opcode == SystemZISD::VICMPHLS ||
3672 C.Opcode == SystemZISD::VFCMPES ||
3673 C.Opcode == SystemZISD::VFCMPHS ||
3674 C.Opcode == SystemZISD::VFCMPHES) {
3675 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3676 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3677 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3678 return SDValue(Val.getNode(), 1);
3679 }
3680 if (C.Chain) {
3681 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3682 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3683 }
3684 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3685}
3686
3687// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3688// 64 bits. Extend is the extension type to use. Store the high part
3689// in Hi and the low part in Lo.
3690static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3691 SDValue Op0, SDValue Op1, SDValue &Hi,
3692 SDValue &Lo) {
3693 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3694 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3695 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3696 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3697 DAG.getConstant(32, DL, MVT::i64));
3698 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3699 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3700}
3701
3702// Lower a binary operation that produces two VT results, one in each
3703// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3704// and Opcode performs the GR128 operation. Store the even register result
3705// in Even and the odd register result in Odd.
3706static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3707 unsigned Opcode, SDValue Op0, SDValue Op1,
3708 SDValue &Even, SDValue &Odd) {
3709 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
3710 bool Is32Bit = is32Bit(VT);
3711 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3712 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3713}
3714
3715// Return an i32 value that is 1 if the CC value produced by CCReg is
3716// in the mask CCMask and 0 otherwise. CC is known to have a value
3717// in CCValid, so other values can be ignored.
3718static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3719 unsigned CCValid, unsigned CCMask) {
3720 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3721 DAG.getConstant(0, DL, MVT::i32),
3722 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3723 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3724 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3725}
3726
3727// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3728// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3729// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3730// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3731// floating-point comparisons.
3734 switch (CC) {
3735 case ISD::SETOEQ:
3736 case ISD::SETEQ:
3737 switch (Mode) {
3738 case CmpMode::Int: return SystemZISD::VICMPE;
3739 case CmpMode::FP: return SystemZISD::VFCMPE;
3740 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3741 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3742 }
3743 llvm_unreachable("Bad mode");
3744
3745 case ISD::SETOGE:
3746 case ISD::SETGE:
3747 switch (Mode) {
3748 case CmpMode::Int: return 0;
3749 case CmpMode::FP: return SystemZISD::VFCMPHE;
3750 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3751 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3752 }
3753 llvm_unreachable("Bad mode");
3754
3755 case ISD::SETOGT:
3756 case ISD::SETGT:
3757 switch (Mode) {
3758 case CmpMode::Int: return SystemZISD::VICMPH;
3759 case CmpMode::FP: return SystemZISD::VFCMPH;
3760 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3761 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3762 }
3763 llvm_unreachable("Bad mode");
3764
3765 case ISD::SETUGT:
3766 switch (Mode) {
3767 case CmpMode::Int: return SystemZISD::VICMPHL;
3768 case CmpMode::FP: return 0;
3769 case CmpMode::StrictFP: return 0;
3770 case CmpMode::SignalingFP: return 0;
3771 }
3772 llvm_unreachable("Bad mode");
3773
3774 default:
3775 return 0;
3776 }
3777}
3778
3779// Return the SystemZISD vector comparison operation for CC or its inverse,
3780// or 0 if neither can be done directly. Indicate in Invert whether the
3781// result is for the inverse of CC. Mode is as above.
3783 bool &Invert) {
3784 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3785 Invert = false;
3786 return Opcode;
3787 }
3788
3789 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3790 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3791 Invert = true;
3792 return Opcode;
3793 }
3794
3795 return 0;
3796}
3797
3798// Return a v2f64 that contains the extended form of elements Start and Start+1
3799// of v4f32 value Op. If Chain is nonnull, return the strict form.
3800static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3801 SDValue Op, SDValue Chain) {
3802 int Mask[] = { Start, -1, Start + 1, -1 };
3803 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3804 if (Chain) {
3805 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3806 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3807 }
3808 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3809}
3810
3811// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3812// producing a result of type VT. If Chain is nonnull, return the strict form.
3813SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3814 const SDLoc &DL, EVT VT,
3815 SDValue CmpOp0,
3816 SDValue CmpOp1,
3817 SDValue Chain) const {
3818 // There is no hardware support for v4f32 (unless we have the vector
3819 // enhancements facility 1), so extend the vector into two v2f64s
3820 // and compare those.
3821 if (CmpOp0.getValueType() == MVT::v4f32 &&
3822 !Subtarget.hasVectorEnhancements1()) {
3823 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3824 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3825 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3826 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3827 if (Chain) {
3828 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3829 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3830 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3831 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3832 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3833 H1.getValue(1), L1.getValue(1),
3834 HRes.getValue(1), LRes.getValue(1) };
3835 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3836 SDValue Ops[2] = { Res, NewChain };
3837 return DAG.getMergeValues(Ops, DL);
3838 }
3839 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3840 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3841 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3842 }
3843 if (Chain) {
3844 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3845 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3846 }
3847 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3848}
3849
3850// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3851// an integer mask of type VT. If Chain is nonnull, we have a strict
3852// floating-point comparison. If in addition IsSignaling is true, we have
3853// a strict signaling floating-point comparison.
3854SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3855 const SDLoc &DL, EVT VT,
3856 ISD::CondCode CC,
3857 SDValue CmpOp0,
3858 SDValue CmpOp1,
3859 SDValue Chain,
3860 bool IsSignaling) const {
3861 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3862 assert (!Chain || IsFP);
3863 assert (!IsSignaling || Chain);
3864 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3865 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3866 bool Invert = false;
3867 SDValue Cmp;
3868 switch (CC) {
3869 // Handle tests for order using (or (ogt y x) (oge x y)).
3870 case ISD::SETUO:
3871 Invert = true;
3872 [[fallthrough]];
3873 case ISD::SETO: {
3874 assert(IsFP && "Unexpected integer comparison");
3875 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3876 DL, VT, CmpOp1, CmpOp0, Chain);
3877 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3878 DL, VT, CmpOp0, CmpOp1, Chain);
3879 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3880 if (Chain)
3881 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3882 LT.getValue(1), GE.getValue(1));
3883 break;
3884 }
3885
3886 // Handle <> tests using (or (ogt y x) (ogt x y)).
3887 case ISD::SETUEQ:
3888 Invert = true;
3889 [[fallthrough]];
3890 case ISD::SETONE: {
3891 assert(IsFP && "Unexpected integer comparison");
3892 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3893 DL, VT, CmpOp1, CmpOp0, Chain);
3894 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3895 DL, VT, CmpOp0, CmpOp1, Chain);
3896 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
3897 if (Chain)
3898 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3899 LT.getValue(1), GT.getValue(1));
3900 break;
3901 }
3902
3903 // Otherwise a single comparison is enough. It doesn't really
3904 // matter whether we try the inversion or the swap first, since
3905 // there are no cases where both work.
3906 default:
3907 // Optimize sign-bit comparisons to signed compares.
3908 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
3910 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3911 APInt Mask;
3912 if (CmpOp0.getOpcode() == ISD::AND
3913 && ISD::isConstantSplatVector(CmpOp0.getOperand(1).getNode(), Mask)
3914 && Mask == APInt::getSignMask(EltSize)) {
3915 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
3916 CmpOp0 = CmpOp0.getOperand(0);
3917 }
3918 }
3919 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3920 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
3921 else {
3923 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3924 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
3925 else
3926 llvm_unreachable("Unhandled comparison");
3927 }
3928 if (Chain)
3929 Chain = Cmp.getValue(1);
3930 break;
3931 }
3932 if (Invert) {
3933 SDValue Mask =
3934 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
3935 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
3936 }
3937 if (Chain && Chain.getNode() != Cmp.getNode()) {
3938 SDValue Ops[2] = { Cmp, Chain };
3939 Cmp = DAG.getMergeValues(Ops, DL);
3940 }
3941 return Cmp;
3942}
3943
3944SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
3945 SelectionDAG &DAG) const {
3946 SDValue CmpOp0 = Op.getOperand(0);
3947 SDValue CmpOp1 = Op.getOperand(1);
3948 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3949 SDLoc DL(Op);
3950 EVT VT = Op.getValueType();
3951 if (VT.isVector())
3952 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
3953
3954 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3955 SDValue CCReg = emitCmp(DAG, DL, C);
3956 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3957}
3958
3959SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
3960 SelectionDAG &DAG,
3961 bool IsSignaling) const {
3962 SDValue Chain = Op.getOperand(0);
3963 SDValue CmpOp0 = Op.getOperand(1);
3964 SDValue CmpOp1 = Op.getOperand(2);
3965 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
3966 SDLoc DL(Op);
3967 EVT VT = Op.getNode()->getValueType(0);
3968 if (VT.isVector()) {
3969 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
3970 Chain, IsSignaling);
3971 return Res.getValue(Op.getResNo());
3972 }
3973
3974 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
3975 SDValue CCReg = emitCmp(DAG, DL, C);
3976 CCReg->setFlags(Op->getFlags());
3977 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3978 SDValue Ops[2] = { Result, CCReg.getValue(1) };
3979 return DAG.getMergeValues(Ops, DL);
3980}
3981
3982SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3983 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3984 SDValue CmpOp0 = Op.getOperand(2);
3985 SDValue CmpOp1 = Op.getOperand(3);
3986 SDValue Dest = Op.getOperand(4);
3987 SDLoc DL(Op);
3988
3989 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3990 SDValue CCReg = emitCmp(DAG, DL, C);
3991 return DAG.getNode(
3992 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
3993 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3994 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
3995}
3996
3997// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
3998// allowing Pos and Neg to be wider than CmpOp.
3999static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4000 return (Neg.getOpcode() == ISD::SUB &&
4001 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4002 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4003 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4004 Pos.getOperand(0) == CmpOp)));
4005}
4006
4007// Return the absolute or negative absolute of Op; IsNegative decides which.
4009 bool IsNegative) {
4010 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4011 if (IsNegative)
4012 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4013 DAG.getConstant(0, DL, Op.getValueType()), Op);
4014 return Op;
4015}
4016
4018 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4019 EVT VT = MVT::i128;
4020 unsigned Op;
4021
4022 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4023 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4024 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4025 std::swap(TrueOp, FalseOp);
4026 C.CCMask ^= C.CCValid;
4027 }
4028 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4029 std::swap(C.Op0, C.Op1);
4030 C.CCMask = SystemZ::CCMASK_CMP_GT;
4031 }
4032 switch (C.CCMask) {
4034 Op = SystemZISD::VICMPE;
4035 break;
4037 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4038 Op = SystemZISD::VICMPHL;
4039 else
4040 Op = SystemZISD::VICMPH;
4041 break;
4042 default:
4043 llvm_unreachable("Unhandled comparison");
4044 break;
4045 }
4046
4047 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4048 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4049 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4050 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4051}
4052
4053SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4054 SelectionDAG &DAG) const {
4055 SDValue CmpOp0 = Op.getOperand(0);
4056 SDValue CmpOp1 = Op.getOperand(1);
4057 SDValue TrueOp = Op.getOperand(2);
4058 SDValue FalseOp = Op.getOperand(3);
4059 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4060 SDLoc DL(Op);
4061
4062 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4063 // legalizer, as it will be handled according to the type of the resulting
4064 // value. Extend them here if needed.
4065 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4066 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4067 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4068 }
4069
4070 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4071
4072 // Check for absolute and negative-absolute selections, including those
4073 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4074 // This check supplements the one in DAGCombiner.
4075 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4076 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4077 C.Op1.getOpcode() == ISD::Constant &&
4078 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4079 C.Op1->getAsZExtVal() == 0) {
4080 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4081 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4082 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4083 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4084 }
4085
4086 if (Subtarget.hasVectorEnhancements3() &&
4087 C.Opcode == SystemZISD::ICMP &&
4088 C.Op0.getValueType() == MVT::i128 &&
4089 TrueOp.getValueType() == MVT::i128) {
4090 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4091 }
4092
4093 SDValue CCReg = emitCmp(DAG, DL, C);
4094 SDValue Ops[] = {TrueOp, FalseOp,
4095 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4096 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4097
4098 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4099}
4100
4101SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4102 SelectionDAG &DAG) const {
4103 SDLoc DL(Node);
4104 const GlobalValue *GV = Node->getGlobal();
4105 int64_t Offset = Node->getOffset();
4106 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4108
4110 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4111 if (isInt<32>(Offset)) {
4112 // Assign anchors at 1<<12 byte boundaries.
4113 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4114 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4115 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4116
4117 // The offset can be folded into the address if it is aligned to a
4118 // halfword.
4119 Offset -= Anchor;
4120 if (Offset != 0 && (Offset & 1) == 0) {
4121 SDValue Full =
4122 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4123 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4124 Offset = 0;
4125 }
4126 } else {
4127 // Conservatively load a constant offset greater than 32 bits into a
4128 // register below.
4129 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4130 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4131 }
4132 } else if (Subtarget.isTargetELF()) {
4133 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4134 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4135 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4137 } else if (Subtarget.isTargetzOS()) {
4138 Result = getADAEntry(DAG, GV, DL, PtrVT);
4139 } else
4140 llvm_unreachable("Unexpected Subtarget");
4141
4142 // If there was a non-zero offset that we didn't fold, create an explicit
4143 // addition for it.
4144 if (Offset != 0)
4145 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4146 DAG.getSignedConstant(Offset, DL, PtrVT));
4147
4148 return Result;
4149}
4150
4151SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4152 SelectionDAG &DAG,
4153 unsigned Opcode,
4154 SDValue GOTOffset) const {
4155 SDLoc DL(Node);
4156 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4157 SDValue Chain = DAG.getEntryNode();
4158 SDValue Glue;
4159
4162 report_fatal_error("In GHC calling convention TLS is not supported");
4163
4164 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4165 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4166 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4167 Glue = Chain.getValue(1);
4168 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4169 Glue = Chain.getValue(1);
4170
4171 // The first call operand is the chain and the second is the TLS symbol.
4173 Ops.push_back(Chain);
4174 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4175 Node->getValueType(0),
4176 0, 0));
4177
4178 // Add argument registers to the end of the list so that they are
4179 // known live into the call.
4180 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4181 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4182
4183 // Add a register mask operand representing the call-preserved registers.
4184 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4185 const uint32_t *Mask =
4186 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4187 assert(Mask && "Missing call preserved mask for calling convention");
4188 Ops.push_back(DAG.getRegisterMask(Mask));
4189
4190 // Glue the call to the argument copies.
4191 Ops.push_back(Glue);
4192
4193 // Emit the call.
4194 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4195 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4196 Glue = Chain.getValue(1);
4197
4198 // Copy the return value from %r2.
4199 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4200}
4201
4202SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4203 SelectionDAG &DAG) const {
4204 SDValue Chain = DAG.getEntryNode();
4205 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4206
4207 // The high part of the thread pointer is in access register 0.
4208 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4209 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4210
4211 // The low part of the thread pointer is in access register 1.
4212 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4213 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4214
4215 // Merge them into a single 64-bit address.
4216 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4217 DAG.getConstant(32, DL, PtrVT));
4218 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4219}
4220
4221SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4222 SelectionDAG &DAG) const {
4223 if (DAG.getTarget().useEmulatedTLS())
4224 return LowerToTLSEmulatedModel(Node, DAG);
4225 SDLoc DL(Node);
4226 const GlobalValue *GV = Node->getGlobal();
4227 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4228 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4229
4232 report_fatal_error("In GHC calling convention TLS is not supported");
4233
4234 SDValue TP = lowerThreadPointer(DL, DAG);
4235
4236 // Get the offset of GA from the thread pointer, based on the TLS model.
4238 switch (model) {
4240 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4241 SystemZConstantPoolValue *CPV =
4243
4244 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4245 Offset = DAG.getLoad(
4246 PtrVT, DL, DAG.getEntryNode(), Offset,
4248
4249 // Call __tls_get_offset to retrieve the offset.
4250 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4251 break;
4252 }
4253
4255 // Load the GOT offset of the module ID.
4256 SystemZConstantPoolValue *CPV =
4258
4259 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4260 Offset = DAG.getLoad(
4261 PtrVT, DL, DAG.getEntryNode(), Offset,
4263
4264 // Call __tls_get_offset to retrieve the module base offset.
4265 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4266
4267 // Note: The SystemZLDCleanupPass will remove redundant computations
4268 // of the module base offset. Count total number of local-dynamic
4269 // accesses to trigger execution of that pass.
4270 SystemZMachineFunctionInfo* MFI =
4271 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4273
4274 // Add the per-symbol offset.
4276
4277 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4278 DTPOffset = DAG.getLoad(
4279 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4281
4282 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4283 break;
4284 }
4285
4286 case TLSModel::InitialExec: {
4287 // Load the offset from the GOT.
4288 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4290 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4291 Offset =
4292 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4294 break;
4295 }
4296
4297 case TLSModel::LocalExec: {
4298 // Force the offset into the constant pool and load it from there.
4299 SystemZConstantPoolValue *CPV =
4301
4302 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4303 Offset = DAG.getLoad(
4304 PtrVT, DL, DAG.getEntryNode(), Offset,
4306 break;
4307 }
4308 }
4309
4310 // Add the base and offset together.
4311 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4312}
4313
4314SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4315 SelectionDAG &DAG) const {
4316 SDLoc DL(Node);
4317 const BlockAddress *BA = Node->getBlockAddress();
4318 int64_t Offset = Node->getOffset();
4319 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4320
4321 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4322 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4323 return Result;
4324}
4325
4326SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4327 SelectionDAG &DAG) const {
4328 SDLoc DL(JT);
4329 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4330 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4331
4332 // Use LARL to load the address of the table.
4333 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4334}
4335
4336SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4337 SelectionDAG &DAG) const {
4338 SDLoc DL(CP);
4339 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4340
4343 Result =
4344 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4345 else
4346 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4347 CP->getOffset());
4348
4349 // Use LARL to load the address of the constant pool entry.
4350 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4351}
4352
4353SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4354 SelectionDAG &DAG) const {
4355 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4356 MachineFunction &MF = DAG.getMachineFunction();
4357 MachineFrameInfo &MFI = MF.getFrameInfo();
4358 MFI.setFrameAddressIsTaken(true);
4359
4360 SDLoc DL(Op);
4361 unsigned Depth = Op.getConstantOperandVal(0);
4362 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4363
4364 // By definition, the frame address is the address of the back chain. (In
4365 // the case of packed stack without backchain, return the address where the
4366 // backchain would have been stored. This will either be an unused space or
4367 // contain a saved register).
4368 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4369 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4370
4371 if (Depth > 0) {
4372 // FIXME The frontend should detect this case.
4373 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4374 report_fatal_error("Unsupported stack frame traversal count");
4375
4376 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4377 while (Depth--) {
4378 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4379 MachinePointerInfo());
4380 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4381 }
4382 }
4383
4384 return BackChain;
4385}
4386
4387SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4388 SelectionDAG &DAG) const {
4389 MachineFunction &MF = DAG.getMachineFunction();
4390 MachineFrameInfo &MFI = MF.getFrameInfo();
4391 MFI.setReturnAddressIsTaken(true);
4392
4393 SDLoc DL(Op);
4394 unsigned Depth = Op.getConstantOperandVal(0);
4395 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4396
4397 if (Depth > 0) {
4398 // FIXME The frontend should detect this case.
4399 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4400 report_fatal_error("Unsupported stack frame traversal count");
4401
4402 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4403 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4404 int Offset = TFL->getReturnAddressOffset(MF);
4405 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4406 DAG.getSignedConstant(Offset, DL, PtrVT));
4407 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4408 MachinePointerInfo());
4409 }
4410
4411 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4412 // implicit live-in.
4413 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4415 &SystemZ::GR64BitRegClass);
4416 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4417}
4418
4419SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4420 SelectionDAG &DAG) const {
4421 SDLoc DL(Op);
4422 SDValue In = Op.getOperand(0);
4423 EVT InVT = In.getValueType();
4424 EVT ResVT = Op.getValueType();
4425
4426 // Convert loads directly. This is normally done by DAGCombiner,
4427 // but we need this case for bitcasts that are created during lowering
4428 // and which are then lowered themselves.
4429 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4430 if (ISD::isNormalLoad(LoadN)) {
4431 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4432 LoadN->getBasePtr(), LoadN->getMemOperand());
4433 // Update the chain uses.
4434 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4435 return NewLoad;
4436 }
4437
4438 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4439 SDValue In64;
4440 if (Subtarget.hasHighWord()) {
4441 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4442 MVT::i64);
4443 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4444 MVT::i64, SDValue(U64, 0), In);
4445 } else {
4446 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4447 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4448 DAG.getConstant(32, DL, MVT::i64));
4449 }
4450 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4451 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4452 DL, MVT::f32, Out64);
4453 }
4454 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4455 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4456 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4457 MVT::f64, SDValue(U64, 0), In);
4458 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4459 if (Subtarget.hasHighWord())
4460 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4461 MVT::i32, Out64);
4462 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4463 DAG.getConstant(32, DL, MVT::i64));
4464 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4465 }
4466 llvm_unreachable("Unexpected bitcast combination");
4467}
4468
4469SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4470 SelectionDAG &DAG) const {
4471
4472 if (Subtarget.isTargetXPLINK64())
4473 return lowerVASTART_XPLINK(Op, DAG);
4474 else
4475 return lowerVASTART_ELF(Op, DAG);
4476}
4477
4478SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4479 SelectionDAG &DAG) const {
4480 MachineFunction &MF = DAG.getMachineFunction();
4481 SystemZMachineFunctionInfo *FuncInfo =
4482 MF.getInfo<SystemZMachineFunctionInfo>();
4483
4484 SDLoc DL(Op);
4485
4486 // vastart just stores the address of the VarArgsFrameIndex slot into the
4487 // memory location argument.
4488 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4489 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4490 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4491 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4492 MachinePointerInfo(SV));
4493}
4494
4495SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4496 SelectionDAG &DAG) const {
4497 MachineFunction &MF = DAG.getMachineFunction();
4498 SystemZMachineFunctionInfo *FuncInfo =
4499 MF.getInfo<SystemZMachineFunctionInfo>();
4500 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4501
4502 SDValue Chain = Op.getOperand(0);
4503 SDValue Addr = Op.getOperand(1);
4504 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4505 SDLoc DL(Op);
4506
4507 // The initial values of each field.
4508 const unsigned NumFields = 4;
4509 SDValue Fields[NumFields] = {
4510 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4511 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4512 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4513 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4514 };
4515
4516 // Store each field into its respective slot.
4517 SDValue MemOps[NumFields];
4518 unsigned Offset = 0;
4519 for (unsigned I = 0; I < NumFields; ++I) {
4520 SDValue FieldAddr = Addr;
4521 if (Offset != 0)
4522 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4524 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4525 MachinePointerInfo(SV, Offset));
4526 Offset += 8;
4527 }
4528 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4529}
4530
4531SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4532 SelectionDAG &DAG) const {
4533 SDValue Chain = Op.getOperand(0);
4534 SDValue DstPtr = Op.getOperand(1);
4535 SDValue SrcPtr = Op.getOperand(2);
4536 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4537 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4538 SDLoc DL(Op);
4539
4540 uint32_t Sz =
4541 Subtarget.isTargetXPLINK64() ? getTargetMachine().getPointerSize(0) : 32;
4542 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4543 Align(8), Align(8), /*isVolatile*/ false,
4544 /*AlwaysInline*/ false,
4545 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4546 MachinePointerInfo(SrcSV));
4547}
4548
4549SDValue
4550SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4551 SelectionDAG &DAG) const {
4552 if (Subtarget.isTargetXPLINK64())
4553 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4554 else
4555 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4556}
4557
4558SDValue
4559SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4560 SelectionDAG &DAG) const {
4561 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4562 MachineFunction &MF = DAG.getMachineFunction();
4563 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4564 SDValue Chain = Op.getOperand(0);
4565 SDValue Size = Op.getOperand(1);
4566 SDValue Align = Op.getOperand(2);
4567 SDLoc DL(Op);
4568
4569 // If user has set the no alignment function attribute, ignore
4570 // alloca alignments.
4571 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4572
4573 uint64_t StackAlign = TFI->getStackAlignment();
4574 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4575 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4576
4577 SDValue NeededSpace = Size;
4578
4579 // Add extra space for alignment if needed.
4580 EVT PtrVT = getPointerTy(MF.getDataLayout());
4581 if (ExtraAlignSpace)
4582 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4583 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4584
4585 bool IsSigned = false;
4586 bool DoesNotReturn = false;
4587 bool IsReturnValueUsed = false;
4588 EVT VT = Op.getValueType();
4589 SDValue AllocaCall =
4590 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4591 CallingConv::C, IsSigned, DL, DoesNotReturn,
4592 IsReturnValueUsed)
4593 .first;
4594
4595 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4596 // to end of call in order to ensure it isn't broken up from the call
4597 // sequence.
4598 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4599 Register SPReg = Regs.getStackPointerRegister();
4600 Chain = AllocaCall.getValue(1);
4601 SDValue Glue = AllocaCall.getValue(2);
4602 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4603 Chain = NewSPRegNode.getValue(1);
4604
4605 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4606 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4607 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4608
4609 // Dynamically realign if needed.
4610 if (ExtraAlignSpace) {
4611 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4612 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4613 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4614 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4615 }
4616
4617 SDValue Ops[2] = {Result, Chain};
4618 return DAG.getMergeValues(Ops, DL);
4619}
4620
4621SDValue
4622SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4623 SelectionDAG &DAG) const {
4624 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4625 MachineFunction &MF = DAG.getMachineFunction();
4626 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4627 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4628
4629 SDValue Chain = Op.getOperand(0);
4630 SDValue Size = Op.getOperand(1);
4631 SDValue Align = Op.getOperand(2);
4632 SDLoc DL(Op);
4633
4634 // If user has set the no alignment function attribute, ignore
4635 // alloca alignments.
4636 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4637
4638 uint64_t StackAlign = TFI->getStackAlignment();
4639 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4640 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4641
4643 SDValue NeededSpace = Size;
4644
4645 // Get a reference to the stack pointer.
4646 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4647
4648 // If we need a backchain, save it now.
4649 SDValue Backchain;
4650 if (StoreBackchain)
4651 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4652 MachinePointerInfo());
4653
4654 // Add extra space for alignment if needed.
4655 if (ExtraAlignSpace)
4656 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4657 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4658
4659 // Get the new stack pointer value.
4660 SDValue NewSP;
4661 if (hasInlineStackProbe(MF)) {
4662 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4663 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4664 Chain = NewSP.getValue(1);
4665 }
4666 else {
4667 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4668 // Copy the new stack pointer back.
4669 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4670 }
4671
4672 // The allocated data lives above the 160 bytes allocated for the standard
4673 // frame, plus any outgoing stack arguments. We don't know how much that
4674 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4675 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4676 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4677
4678 // Dynamically realign if needed.
4679 if (RequiredAlign > StackAlign) {
4680 Result =
4681 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4682 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4683 Result =
4684 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4685 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4686 }
4687
4688 if (StoreBackchain)
4689 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4690 MachinePointerInfo());
4691
4692 SDValue Ops[2] = { Result, Chain };
4693 return DAG.getMergeValues(Ops, DL);
4694}
4695
4696SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4697 SDValue Op, SelectionDAG &DAG) const {
4698 SDLoc DL(Op);
4699
4700 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4701}
4702
4703SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4704 SelectionDAG &DAG,
4705 unsigned Opcode) const {
4706 EVT VT = Op.getValueType();
4707 SDLoc DL(Op);
4708 SDValue Even, Odd;
4709
4710 // This custom expander is only used on z17 and later for 64-bit types.
4711 assert(!is32Bit(VT));
4712 assert(Subtarget.hasMiscellaneousExtensions2());
4713
4714 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4715 // the high result in the even register. Return the latter.
4716 lowerGR128Binary(DAG, DL, VT, Opcode,
4717 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4718 return Even;
4719}
4720
4721SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4722 SelectionDAG &DAG) const {
4723 EVT VT = Op.getValueType();
4724 SDLoc DL(Op);
4725 SDValue Ops[2];
4726 if (is32Bit(VT))
4727 // Just do a normal 64-bit multiplication and extract the results.
4728 // We define this so that it can be used for constant division.
4729 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4730 Op.getOperand(1), Ops[1], Ops[0]);
4731 else if (Subtarget.hasMiscellaneousExtensions2())
4732 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4733 // the high result in the even register. ISD::SMUL_LOHI is defined to
4734 // return the low half first, so the results are in reverse order.
4735 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4736 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4737 else {
4738 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4739 //
4740 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4741 //
4742 // but using the fact that the upper halves are either all zeros
4743 // or all ones:
4744 //
4745 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4746 //
4747 // and grouping the right terms together since they are quicker than the
4748 // multiplication:
4749 //
4750 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4751 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4752 SDValue LL = Op.getOperand(0);
4753 SDValue RL = Op.getOperand(1);
4754 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4755 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4756 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4757 // the high result in the even register. ISD::SMUL_LOHI is defined to
4758 // return the low half first, so the results are in reverse order.
4759 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4760 LL, RL, Ops[1], Ops[0]);
4761 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4762 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4763 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4764 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4765 }
4766 return DAG.getMergeValues(Ops, DL);
4767}
4768
4769SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4770 SelectionDAG &DAG) const {
4771 EVT VT = Op.getValueType();
4772 SDLoc DL(Op);
4773 SDValue Ops[2];
4774 if (is32Bit(VT))
4775 // Just do a normal 64-bit multiplication and extract the results.
4776 // We define this so that it can be used for constant division.
4777 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4778 Op.getOperand(1), Ops[1], Ops[0]);
4779 else
4780 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4781 // the high result in the even register. ISD::UMUL_LOHI is defined to
4782 // return the low half first, so the results are in reverse order.
4783 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4784 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4785 return DAG.getMergeValues(Ops, DL);
4786}
4787
4788SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4789 SelectionDAG &DAG) const {
4790 SDValue Op0 = Op.getOperand(0);
4791 SDValue Op1 = Op.getOperand(1);
4792 EVT VT = Op.getValueType();
4793 SDLoc DL(Op);
4794
4795 // We use DSGF for 32-bit division. This means the first operand must
4796 // always be 64-bit, and the second operand should be 32-bit whenever
4797 // that is possible, to improve performance.
4798 if (is32Bit(VT))
4799 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4800 else if (DAG.ComputeNumSignBits(Op1) > 32)
4801 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4802
4803 // DSG(F) returns the remainder in the even register and the
4804 // quotient in the odd register.
4805 SDValue Ops[2];
4806 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4807 return DAG.getMergeValues(Ops, DL);
4808}
4809
4810SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4811 SelectionDAG &DAG) const {
4812 EVT VT = Op.getValueType();
4813 SDLoc DL(Op);
4814
4815 // DL(G) returns the remainder in the even register and the
4816 // quotient in the odd register.
4817 SDValue Ops[2];
4818 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4819 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4820 return DAG.getMergeValues(Ops, DL);
4821}
4822
4823SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4824 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4825
4826 // Get the known-zero masks for each operand.
4827 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4828 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4829 DAG.computeKnownBits(Ops[1])};
4830
4831 // See if the upper 32 bits of one operand and the lower 32 bits of the
4832 // other are known zero. They are the low and high operands respectively.
4833 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4834 Known[1].Zero.getZExtValue() };
4835 unsigned High, Low;
4836 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4837 High = 1, Low = 0;
4838 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4839 High = 0, Low = 1;
4840 else
4841 return Op;
4842
4843 SDValue LowOp = Ops[Low];
4844 SDValue HighOp = Ops[High];
4845
4846 // If the high part is a constant, we're better off using IILH.
4847 if (HighOp.getOpcode() == ISD::Constant)
4848 return Op;
4849
4850 // If the low part is a constant that is outside the range of LHI,
4851 // then we're better off using IILF.
4852 if (LowOp.getOpcode() == ISD::Constant) {
4853 int64_t Value = int32_t(LowOp->getAsZExtVal());
4854 if (!isInt<16>(Value))
4855 return Op;
4856 }
4857
4858 // Check whether the high part is an AND that doesn't change the
4859 // high 32 bits and just masks out low bits. We can skip it if so.
4860 if (HighOp.getOpcode() == ISD::AND &&
4861 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4862 SDValue HighOp0 = HighOp.getOperand(0);
4863 uint64_t Mask = HighOp.getConstantOperandVal(1);
4864 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4865 HighOp = HighOp0;
4866 }
4867
4868 // Take advantage of the fact that all GR32 operations only change the
4869 // low 32 bits by truncating Low to an i32 and inserting it directly
4870 // using a subreg. The interesting cases are those where the truncation
4871 // can be folded.
4872 SDLoc DL(Op);
4873 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4874 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4875 MVT::i64, HighOp, Low32);
4876}
4877
4878// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4879SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4880 SelectionDAG &DAG) const {
4881 SDNode *N = Op.getNode();
4882 SDValue LHS = N->getOperand(0);
4883 SDValue RHS = N->getOperand(1);
4884 SDLoc DL(N);
4885
4886 if (N->getValueType(0) == MVT::i128) {
4887 unsigned BaseOp = 0;
4888 unsigned FlagOp = 0;
4889 bool IsBorrow = false;
4890 switch (Op.getOpcode()) {
4891 default: llvm_unreachable("Unknown instruction!");
4892 case ISD::UADDO:
4893 BaseOp = ISD::ADD;
4894 FlagOp = SystemZISD::VACC;
4895 break;
4896 case ISD::USUBO:
4897 BaseOp = ISD::SUB;
4898 FlagOp = SystemZISD::VSCBI;
4899 IsBorrow = true;
4900 break;
4901 }
4902 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
4903 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
4904 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
4905 DAG.getValueType(MVT::i1));
4906 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
4907 if (IsBorrow)
4908 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
4909 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
4910 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
4911 }
4912
4913 unsigned BaseOp = 0;
4914 unsigned CCValid = 0;
4915 unsigned CCMask = 0;
4916
4917 switch (Op.getOpcode()) {
4918 default: llvm_unreachable("Unknown instruction!");
4919 case ISD::SADDO:
4920 BaseOp = SystemZISD::SADDO;
4921 CCValid = SystemZ::CCMASK_ARITH;
4923 break;
4924 case ISD::SSUBO:
4925 BaseOp = SystemZISD::SSUBO;
4926 CCValid = SystemZ::CCMASK_ARITH;
4928 break;
4929 case ISD::UADDO:
4930 BaseOp = SystemZISD::UADDO;
4931 CCValid = SystemZ::CCMASK_LOGICAL;
4933 break;
4934 case ISD::USUBO:
4935 BaseOp = SystemZISD::USUBO;
4936 CCValid = SystemZ::CCMASK_LOGICAL;
4938 break;
4939 }
4940
4941 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
4942 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
4943
4944 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
4945 if (N->getValueType(1) == MVT::i1)
4946 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
4947
4948 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
4949}
4950
4951static bool isAddCarryChain(SDValue Carry) {
4952 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
4953 Carry->getValueType(0) != MVT::i128)
4954 Carry = Carry.getOperand(2);
4955 return Carry.getOpcode() == ISD::UADDO &&
4956 Carry->getValueType(0) != MVT::i128;
4957}
4958
4959static bool isSubBorrowChain(SDValue Carry) {
4960 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
4961 Carry->getValueType(0) != MVT::i128)
4962 Carry = Carry.getOperand(2);
4963 return Carry.getOpcode() == ISD::USUBO &&
4964 Carry->getValueType(0) != MVT::i128;
4965}
4966
4967// Lower UADDO_CARRY/USUBO_CARRY nodes.
4968SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
4969 SelectionDAG &DAG) const {
4970
4971 SDNode *N = Op.getNode();
4972 MVT VT = N->getSimpleValueType(0);
4973
4974 // Let legalize expand this if it isn't a legal type yet.
4975 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
4976 return SDValue();
4977
4978 SDValue LHS = N->getOperand(0);
4979 SDValue RHS = N->getOperand(1);
4980 SDValue Carry = Op.getOperand(2);
4981 SDLoc DL(N);
4982
4983 if (VT == MVT::i128) {
4984 unsigned BaseOp = 0;
4985 unsigned FlagOp = 0;
4986 bool IsBorrow = false;
4987 switch (Op.getOpcode()) {
4988 default: llvm_unreachable("Unknown instruction!");
4989 case ISD::UADDO_CARRY:
4990 BaseOp = SystemZISD::VAC;
4991 FlagOp = SystemZISD::VACCC;
4992 break;
4993 case ISD::USUBO_CARRY:
4994 BaseOp = SystemZISD::VSBI;
4995 FlagOp = SystemZISD::VSBCBI;
4996 IsBorrow = true;
4997 break;
4998 }
4999 if (IsBorrow)
5000 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5001 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5002 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5003 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5004 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5005 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5006 DAG.getValueType(MVT::i1));
5007 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5008 if (IsBorrow)
5009 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5010 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5011 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5012 }
5013
5014 unsigned BaseOp = 0;
5015 unsigned CCValid = 0;
5016 unsigned CCMask = 0;
5017
5018 switch (Op.getOpcode()) {
5019 default: llvm_unreachable("Unknown instruction!");
5020 case ISD::UADDO_CARRY:
5021 if (!isAddCarryChain(Carry))
5022 return SDValue();
5023
5024 BaseOp = SystemZISD::ADDCARRY;
5025 CCValid = SystemZ::CCMASK_LOGICAL;
5027 break;
5028 case ISD::USUBO_CARRY:
5029 if (!isSubBorrowChain(Carry))
5030 return SDValue();
5031
5032 BaseOp = SystemZISD::SUBCARRY;
5033 CCValid = SystemZ::CCMASK_LOGICAL;
5035 break;
5036 }
5037
5038 // Set the condition code from the carry flag.
5039 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5040 DAG.getConstant(CCValid, DL, MVT::i32),
5041 DAG.getConstant(CCMask, DL, MVT::i32));
5042
5043 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5044 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5045
5046 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5047 if (N->getValueType(1) == MVT::i1)
5048 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5049
5050 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5051}
5052
5053SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5054 SelectionDAG &DAG) const {
5055 EVT VT = Op.getValueType();
5056 SDLoc DL(Op);
5057 Op = Op.getOperand(0);
5058
5059 if (VT.getScalarSizeInBits() == 128) {
5060 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5061 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5062 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5063 DAG.getConstant(0, DL, MVT::i64));
5064 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5065 return Op;
5066 }
5067
5068 // Handle vector types via VPOPCT.
5069 if (VT.isVector()) {
5070 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5071 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5072 switch (VT.getScalarSizeInBits()) {
5073 case 8:
5074 break;
5075 case 16: {
5076 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5077 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5078 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5079 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5080 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5081 break;
5082 }
5083 case 32: {
5084 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5085 DAG.getConstant(0, DL, MVT::i32));
5086 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5087 break;
5088 }
5089 case 64: {
5090 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5091 DAG.getConstant(0, DL, MVT::i32));
5092 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5093 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5094 break;
5095 }
5096 default:
5097 llvm_unreachable("Unexpected type");
5098 }
5099 return Op;
5100 }
5101
5102 // Get the known-zero mask for the operand.
5103 KnownBits Known = DAG.computeKnownBits(Op);
5104 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5105 if (NumSignificantBits == 0)
5106 return DAG.getConstant(0, DL, VT);
5107
5108 // Skip known-zero high parts of the operand.
5109 int64_t OrigBitSize = VT.getSizeInBits();
5110 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5111 BitSize = std::min(BitSize, OrigBitSize);
5112
5113 // The POPCNT instruction counts the number of bits in each byte.
5114 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5115 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5116 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5117
5118 // Add up per-byte counts in a binary tree. All bits of Op at
5119 // position larger than BitSize remain zero throughout.
5120 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5121 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5122 if (BitSize != OrigBitSize)
5123 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5124 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5125 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5126 }
5127
5128 // Extract overall result from high byte.
5129 if (BitSize > 8)
5130 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5131 DAG.getConstant(BitSize - 8, DL, VT));
5132
5133 return Op;
5134}
5135
5136SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5137 SelectionDAG &DAG) const {
5138 SDLoc DL(Op);
5139 AtomicOrdering FenceOrdering =
5140 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5141 SyncScope::ID FenceSSID =
5142 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5143
5144 // The only fence that needs an instruction is a sequentially-consistent
5145 // cross-thread fence.
5146 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5147 FenceSSID == SyncScope::System) {
5148 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5149 Op.getOperand(0)),
5150 0);
5151 }
5152
5153 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5154 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5155}
5156
5157SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5158 SelectionDAG &DAG) const {
5159 EVT RegVT = Op.getValueType();
5160 if (RegVT.getSizeInBits() == 128)
5161 return lowerATOMIC_LDST_I128(Op, DAG);
5162 return lowerLoadF16(Op, DAG);
5163}
5164
5165SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5166 SelectionDAG &DAG) const {
5167 auto *Node = cast<AtomicSDNode>(Op.getNode());
5168 if (Node->getMemoryVT().getSizeInBits() == 128)
5169 return lowerATOMIC_LDST_I128(Op, DAG);
5170 return lowerStoreF16(Op, DAG);
5171}
5172
5173SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5174 SelectionDAG &DAG) const {
5175 auto *Node = cast<AtomicSDNode>(Op.getNode());
5176 assert(
5177 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5178 "Only custom lowering i128 or f128.");
5179 // Use same code to handle both legal and non-legal i128 types.
5181 LowerOperationWrapper(Node, Results, DAG);
5182 return DAG.getMergeValues(Results, SDLoc(Op));
5183}
5184
5185// Prepare for a Compare And Swap for a subword operation. This needs to be
5186// done in memory with 4 bytes at natural alignment.
5188 SDValue &AlignedAddr, SDValue &BitShift,
5189 SDValue &NegBitShift) {
5190 EVT PtrVT = Addr.getValueType();
5191 EVT WideVT = MVT::i32;
5192
5193 // Get the address of the containing word.
5194 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5195 DAG.getSignedConstant(-4, DL, PtrVT));
5196
5197 // Get the number of bits that the word must be rotated left in order
5198 // to bring the field to the top bits of a GR32.
5199 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5200 DAG.getConstant(3, DL, PtrVT));
5201 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5202
5203 // Get the complementing shift amount, for rotating a field in the top
5204 // bits back to its proper position.
5205 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5206 DAG.getConstant(0, DL, WideVT), BitShift);
5207
5208}
5209
5210// Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
5211// two into the fullword ATOMIC_LOADW_* operation given by Opcode.
5212SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
5213 SelectionDAG &DAG,
5214 unsigned Opcode) const {
5215 auto *Node = cast<AtomicSDNode>(Op.getNode());
5216
5217 // 32-bit operations need no special handling.
5218 EVT NarrowVT = Node->getMemoryVT();
5219 EVT WideVT = MVT::i32;
5220 if (NarrowVT == WideVT)
5221 return Op;
5222
5223 int64_t BitSize = NarrowVT.getSizeInBits();
5224 SDValue ChainIn = Node->getChain();
5225 SDValue Addr = Node->getBasePtr();
5226 SDValue Src2 = Node->getVal();
5227 MachineMemOperand *MMO = Node->getMemOperand();
5228 SDLoc DL(Node);
5229
5230 // Convert atomic subtracts of constants into additions.
5231 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5232 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5233 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5234 Src2 = DAG.getSignedConstant(-Const->getSExtValue(), DL,
5235 Src2.getValueType());
5236 }
5237
5238 SDValue AlignedAddr, BitShift, NegBitShift;
5239 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5240
5241 // Extend the source operand to 32 bits and prepare it for the inner loop.
5242 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5243 // operations require the source to be shifted in advance. (This shift
5244 // can be folded if the source is constant.) For AND and NAND, the lower
5245 // bits must be set, while for other opcodes they should be left clear.
5246 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5247 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5248 DAG.getConstant(32 - BitSize, DL, WideVT));
5249 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5250 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5251 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5252 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5253
5254 // Construct the ATOMIC_LOADW_* node.
5255 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5256 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5257 DAG.getConstant(BitSize, DL, WideVT) };
5258 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5259 NarrowVT, MMO);
5260
5261 // Rotate the result of the final CS so that the field is in the lower
5262 // bits of a GR32, then truncate it.
5263 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5264 DAG.getConstant(BitSize, DL, WideVT));
5265 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5266
5267 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
5268 return DAG.getMergeValues(RetOps, DL);
5269}
5270
5271// Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations into
5272// ATOMIC_LOADW_SUBs and convert 32- and 64-bit operations into additions.
5273SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5274 SelectionDAG &DAG) const {
5275 auto *Node = cast<AtomicSDNode>(Op.getNode());
5276 EVT MemVT = Node->getMemoryVT();
5277 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
5278 // A full-width operation: negate and use LAA(G).
5279 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5280 assert(Subtarget.hasInterlockedAccess1() &&
5281 "Should have been expanded by AtomicExpand pass.");
5282 SDValue Src2 = Node->getVal();
5283 SDLoc DL(Src2);
5284 SDValue NegSrc2 =
5285 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5286 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
5287 Node->getChain(), Node->getBasePtr(), NegSrc2,
5288 Node->getMemOperand());
5289 }
5290
5291 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
5292}
5293
5294// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5295SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5296 SelectionDAG &DAG) const {
5297 auto *Node = cast<AtomicSDNode>(Op.getNode());
5298 SDValue ChainIn = Node->getOperand(0);
5299 SDValue Addr = Node->getOperand(1);
5300 SDValue CmpVal = Node->getOperand(2);
5301 SDValue SwapVal = Node->getOperand(3);
5302 MachineMemOperand *MMO = Node->getMemOperand();
5303 SDLoc DL(Node);
5304
5305 if (Node->getMemoryVT() == MVT::i128) {
5306 // Use same code to handle both legal and non-legal i128 types.
5308 LowerOperationWrapper(Node, Results, DAG);
5309 return DAG.getMergeValues(Results, DL);
5310 }
5311
5312 // We have native support for 32-bit and 64-bit compare and swap, but we
5313 // still need to expand extracting the "success" result from the CC.
5314 EVT NarrowVT = Node->getMemoryVT();
5315 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5316 if (NarrowVT == WideVT) {
5317 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5318 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5319 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5320 DL, Tys, Ops, NarrowVT, MMO);
5321 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5323
5324 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5325 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5326 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5327 return SDValue();
5328 }
5329
5330 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5331 // via a fullword ATOMIC_CMP_SWAPW operation.
5332 int64_t BitSize = NarrowVT.getSizeInBits();
5333
5334 SDValue AlignedAddr, BitShift, NegBitShift;
5335 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5336
5337 // Construct the ATOMIC_CMP_SWAPW node.
5338 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5339 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5340 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5341 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5342 VTList, Ops, NarrowVT, MMO);
5343 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5345
5346 // emitAtomicCmpSwapW() will zero extend the result (original value).
5347 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5348 DAG.getValueType(NarrowVT));
5349 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5350 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5351 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5352 return SDValue();
5353}
5354
5356SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5357 // Because of how we convert atomic_load and atomic_store to normal loads and
5358 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5359 // since DAGCombine hasn't been updated to account for atomic, but non
5360 // volatile loads. (See D57601)
5361 if (auto *SI = dyn_cast<StoreInst>(&I))
5362 if (SI->isAtomic())
5364 if (auto *LI = dyn_cast<LoadInst>(&I))
5365 if (LI->isAtomic())
5367 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5368 if (AI->isAtomic())
5370 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5371 if (AI->isAtomic())
5374}
5375
5376SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5377 SelectionDAG &DAG) const {
5378 MachineFunction &MF = DAG.getMachineFunction();
5379 auto *Regs = Subtarget.getSpecialRegisters();
5381 report_fatal_error("Variable-sized stack allocations are not supported "
5382 "in GHC calling convention");
5383 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5384 Regs->getStackPointerRegister(), Op.getValueType());
5385}
5386
5387SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5388 SelectionDAG &DAG) const {
5389 MachineFunction &MF = DAG.getMachineFunction();
5390 auto *Regs = Subtarget.getSpecialRegisters();
5391 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5392
5394 report_fatal_error("Variable-sized stack allocations are not supported "
5395 "in GHC calling convention");
5396
5397 SDValue Chain = Op.getOperand(0);
5398 SDValue NewSP = Op.getOperand(1);
5399 SDValue Backchain;
5400 SDLoc DL(Op);
5401
5402 if (StoreBackchain) {
5403 SDValue OldSP = DAG.getCopyFromReg(
5404 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5405 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5406 MachinePointerInfo());
5407 }
5408
5409 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5410
5411 if (StoreBackchain)
5412 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5413 MachinePointerInfo());
5414
5415 return Chain;
5416}
5417
5418SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5419 SelectionDAG &DAG) const {
5420 bool IsData = Op.getConstantOperandVal(4);
5421 if (!IsData)
5422 // Just preserve the chain.
5423 return Op.getOperand(0);
5424
5425 SDLoc DL(Op);
5426 bool IsWrite = Op.getConstantOperandVal(2);
5427 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5428 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5429 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5430 Op.getOperand(1)};
5431 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5432 Node->getVTList(), Ops,
5433 Node->getMemoryVT(), Node->getMemOperand());
5434}
5435
5436SDValue
5437SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5438 SelectionDAG &DAG) const {
5439 unsigned Opcode, CCValid;
5440 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5441 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5442 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5443 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5444 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5445 return SDValue();
5446 }
5447
5448 return SDValue();
5449}
5450
5451SDValue
5452SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5453 SelectionDAG &DAG) const {
5454 unsigned Opcode, CCValid;
5455 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5456 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5457 if (Op->getNumValues() == 1)
5458 return getCCResult(DAG, SDValue(Node, 0));
5459 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5460 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5461 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5462 }
5463
5464 unsigned Id = Op.getConstantOperandVal(0);
5465 switch (Id) {
5466 case Intrinsic::thread_pointer:
5467 return lowerThreadPointer(SDLoc(Op), DAG);
5468
5469 case Intrinsic::s390_vpdi:
5470 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5471 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5472
5473 case Intrinsic::s390_vperm:
5474 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5475 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5476
5477 case Intrinsic::s390_vuphb:
5478 case Intrinsic::s390_vuphh:
5479 case Intrinsic::s390_vuphf:
5480 case Intrinsic::s390_vuphg:
5481 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5482 Op.getOperand(1));
5483
5484 case Intrinsic::s390_vuplhb:
5485 case Intrinsic::s390_vuplhh:
5486 case Intrinsic::s390_vuplhf:
5487 case Intrinsic::s390_vuplhg:
5488 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5489 Op.getOperand(1));
5490
5491 case Intrinsic::s390_vuplb:
5492 case Intrinsic::s390_vuplhw:
5493 case Intrinsic::s390_vuplf:
5494 case Intrinsic::s390_vuplg:
5495 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5496 Op.getOperand(1));
5497
5498 case Intrinsic::s390_vupllb:
5499 case Intrinsic::s390_vupllh:
5500 case Intrinsic::s390_vupllf:
5501 case Intrinsic::s390_vupllg:
5502 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5503 Op.getOperand(1));
5504
5505 case Intrinsic::s390_vsumb:
5506 case Intrinsic::s390_vsumh:
5507 case Intrinsic::s390_vsumgh:
5508 case Intrinsic::s390_vsumgf:
5509 case Intrinsic::s390_vsumqf:
5510 case Intrinsic::s390_vsumqg:
5511 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5512 Op.getOperand(1), Op.getOperand(2));
5513
5514 case Intrinsic::s390_vaq:
5515 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5516 Op.getOperand(1), Op.getOperand(2));
5517 case Intrinsic::s390_vaccb:
5518 case Intrinsic::s390_vacch:
5519 case Intrinsic::s390_vaccf:
5520 case Intrinsic::s390_vaccg:
5521 case Intrinsic::s390_vaccq:
5522 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5523 Op.getOperand(1), Op.getOperand(2));
5524 case Intrinsic::s390_vacq:
5525 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5526 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5527 case Intrinsic::s390_vacccq:
5528 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5529 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5530
5531 case Intrinsic::s390_vsq:
5532 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5533 Op.getOperand(1), Op.getOperand(2));
5534 case Intrinsic::s390_vscbib:
5535 case Intrinsic::s390_vscbih:
5536 case Intrinsic::s390_vscbif:
5537 case Intrinsic::s390_vscbig:
5538 case Intrinsic::s390_vscbiq:
5539 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5540 Op.getOperand(1), Op.getOperand(2));
5541 case Intrinsic::s390_vsbiq:
5542 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5543 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5544 case Intrinsic::s390_vsbcbiq:
5545 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5546 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5547
5548 case Intrinsic::s390_vmhb:
5549 case Intrinsic::s390_vmhh:
5550 case Intrinsic::s390_vmhf:
5551 case Intrinsic::s390_vmhg:
5552 case Intrinsic::s390_vmhq:
5553 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5554 Op.getOperand(1), Op.getOperand(2));
5555 case Intrinsic::s390_vmlhb:
5556 case Intrinsic::s390_vmlhh:
5557 case Intrinsic::s390_vmlhf:
5558 case Intrinsic::s390_vmlhg:
5559 case Intrinsic::s390_vmlhq:
5560 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5561 Op.getOperand(1), Op.getOperand(2));
5562
5563 case Intrinsic::s390_vmahb:
5564 case Intrinsic::s390_vmahh:
5565 case Intrinsic::s390_vmahf:
5566 case Intrinsic::s390_vmahg:
5567 case Intrinsic::s390_vmahq:
5568 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5569 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5570 case Intrinsic::s390_vmalhb:
5571 case Intrinsic::s390_vmalhh:
5572 case Intrinsic::s390_vmalhf:
5573 case Intrinsic::s390_vmalhg:
5574 case Intrinsic::s390_vmalhq:
5575 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5577
5578 case Intrinsic::s390_vmeb:
5579 case Intrinsic::s390_vmeh:
5580 case Intrinsic::s390_vmef:
5581 case Intrinsic::s390_vmeg:
5582 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5583 Op.getOperand(1), Op.getOperand(2));
5584 case Intrinsic::s390_vmleb:
5585 case Intrinsic::s390_vmleh:
5586 case Intrinsic::s390_vmlef:
5587 case Intrinsic::s390_vmleg:
5588 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5589 Op.getOperand(1), Op.getOperand(2));
5590 case Intrinsic::s390_vmob:
5591 case Intrinsic::s390_vmoh:
5592 case Intrinsic::s390_vmof:
5593 case Intrinsic::s390_vmog:
5594 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5595 Op.getOperand(1), Op.getOperand(2));
5596 case Intrinsic::s390_vmlob:
5597 case Intrinsic::s390_vmloh:
5598 case Intrinsic::s390_vmlof:
5599 case Intrinsic::s390_vmlog:
5600 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5601 Op.getOperand(1), Op.getOperand(2));
5602
5603 case Intrinsic::s390_vmaeb:
5604 case Intrinsic::s390_vmaeh:
5605 case Intrinsic::s390_vmaef:
5606 case Intrinsic::s390_vmaeg:
5607 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5608 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5609 Op.getOperand(1), Op.getOperand(2)),
5610 Op.getOperand(3));
5611 case Intrinsic::s390_vmaleb:
5612 case Intrinsic::s390_vmaleh:
5613 case Intrinsic::s390_vmalef:
5614 case Intrinsic::s390_vmaleg:
5615 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5616 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5617 Op.getOperand(1), Op.getOperand(2)),
5618 Op.getOperand(3));
5619 case Intrinsic::s390_vmaob:
5620 case Intrinsic::s390_vmaoh:
5621 case Intrinsic::s390_vmaof:
5622 case Intrinsic::s390_vmaog:
5623 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5624 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5625 Op.getOperand(1), Op.getOperand(2)),
5626 Op.getOperand(3));
5627 case Intrinsic::s390_vmalob:
5628 case Intrinsic::s390_vmaloh:
5629 case Intrinsic::s390_vmalof:
5630 case Intrinsic::s390_vmalog:
5631 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5632 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5633 Op.getOperand(1), Op.getOperand(2)),
5634 Op.getOperand(3));
5635 }
5636
5637 return SDValue();
5638}
5639
5640namespace {
5641// Says that SystemZISD operation Opcode can be used to perform the equivalent
5642// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5643// Operand is the constant third operand, otherwise it is the number of
5644// bytes in each element of the result.
5645struct Permute {
5646 unsigned Opcode;
5647 unsigned Operand;
5648 unsigned char Bytes[SystemZ::VectorBytes];
5649};
5650}
5651
5652static const Permute PermuteForms[] = {
5653 // VMRHG
5654 { SystemZISD::MERGE_HIGH, 8,
5655 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5656 // VMRHF
5657 { SystemZISD::MERGE_HIGH, 4,
5658 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5659 // VMRHH
5660 { SystemZISD::MERGE_HIGH, 2,
5661 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5662 // VMRHB
5663 { SystemZISD::MERGE_HIGH, 1,
5664 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5665 // VMRLG
5666 { SystemZISD::MERGE_LOW, 8,
5667 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5668 // VMRLF
5669 { SystemZISD::MERGE_LOW, 4,
5670 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5671 // VMRLH
5672 { SystemZISD::MERGE_LOW, 2,
5673 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5674 // VMRLB
5675 { SystemZISD::MERGE_LOW, 1,
5676 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5677 // VPKG
5678 { SystemZISD::PACK, 4,
5679 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5680 // VPKF
5681 { SystemZISD::PACK, 2,
5682 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5683 // VPKH
5684 { SystemZISD::PACK, 1,
5685 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5686 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5687 { SystemZISD::PERMUTE_DWORDS, 4,
5688 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5689 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5690 { SystemZISD::PERMUTE_DWORDS, 1,
5691 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5692};
5693
5694// Called after matching a vector shuffle against a particular pattern.
5695// Both the original shuffle and the pattern have two vector operands.
5696// OpNos[0] is the operand of the original shuffle that should be used for
5697// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5698// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5699// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5700// for operands 0 and 1 of the pattern.
5701static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5702 if (OpNos[0] < 0) {
5703 if (OpNos[1] < 0)
5704 return false;
5705 OpNo0 = OpNo1 = OpNos[1];
5706 } else if (OpNos[1] < 0) {
5707 OpNo0 = OpNo1 = OpNos[0];
5708 } else {
5709 OpNo0 = OpNos[0];
5710 OpNo1 = OpNos[1];
5711 }
5712 return true;
5713}
5714
5715// Bytes is a VPERM-like permute vector, except that -1 is used for
5716// undefined bytes. Return true if the VPERM can be implemented using P.
5717// When returning true set OpNo0 to the VPERM operand that should be
5718// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5719//
5720// For example, if swapping the VPERM operands allows P to match, OpNo0
5721// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5722// operand, but rewriting it to use two duplicated operands allows it to
5723// match P, then OpNo0 and OpNo1 will be the same.
5724static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5725 unsigned &OpNo0, unsigned &OpNo1) {
5726 int OpNos[] = { -1, -1 };
5727 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5728 int Elt = Bytes[I];
5729 if (Elt >= 0) {
5730 // Make sure that the two permute vectors use the same suboperand
5731 // byte number. Only the operand numbers (the high bits) are
5732 // allowed to differ.
5733 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5734 return false;
5735 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5736 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5737 // Make sure that the operand mappings are consistent with previous
5738 // elements.
5739 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5740 return false;
5741 OpNos[ModelOpNo] = RealOpNo;
5742 }
5743 }
5744 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5745}
5746
5747// As above, but search for a matching permute.
5748static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5749 unsigned &OpNo0, unsigned &OpNo1) {
5750 for (auto &P : PermuteForms)
5751 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5752 return &P;
5753 return nullptr;
5754}
5755
5756// Bytes is a VPERM-like permute vector, except that -1 is used for
5757// undefined bytes. This permute is an operand of an outer permute.
5758// See whether redistributing the -1 bytes gives a shuffle that can be
5759// implemented using P. If so, set Transform to a VPERM-like permute vector
5760// that, when applied to the result of P, gives the original permute in Bytes.
5762 const Permute &P,
5763 SmallVectorImpl<int> &Transform) {
5764 unsigned To = 0;
5765 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5766 int Elt = Bytes[From];
5767 if (Elt < 0)
5768 // Byte number From of the result is undefined.
5769 Transform[From] = -1;
5770 else {
5771 while (P.Bytes[To] != Elt) {
5772 To += 1;
5773 if (To == SystemZ::VectorBytes)
5774 return false;
5775 }
5776 Transform[From] = To;
5777 }
5778 }
5779 return true;
5780}
5781
5782// As above, but search for a matching permute.
5783static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5784 SmallVectorImpl<int> &Transform) {
5785 for (auto &P : PermuteForms)
5786 if (matchDoublePermute(Bytes, P, Transform))
5787 return &P;
5788 return nullptr;
5789}
5790
5791// Convert the mask of the given shuffle op into a byte-level mask,
5792// as if it had type vNi8.
5793static bool getVPermMask(SDValue ShuffleOp,
5794 SmallVectorImpl<int> &Bytes) {
5795 EVT VT = ShuffleOp.getValueType();
5796 unsigned NumElements = VT.getVectorNumElements();
5797 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5798
5799 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5800 Bytes.resize(NumElements * BytesPerElement, -1);
5801 for (unsigned I = 0; I < NumElements; ++I) {
5802 int Index = VSN->getMaskElt(I);
5803 if (Index >= 0)
5804 for (unsigned J = 0; J < BytesPerElement; ++J)
5805 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5806 }
5807 return true;
5808 }
5809 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
5810 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
5811 unsigned Index = ShuffleOp.getConstantOperandVal(1);
5812 Bytes.resize(NumElements * BytesPerElement, -1);
5813 for (unsigned I = 0; I < NumElements; ++I)
5814 for (unsigned J = 0; J < BytesPerElement; ++J)
5815 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5816 return true;
5817 }
5818 return false;
5819}
5820
5821// Bytes is a VPERM-like permute vector, except that -1 is used for
5822// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
5823// the result come from a contiguous sequence of bytes from one input.
5824// Set Base to the selector for the first byte if so.
5825static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
5826 unsigned BytesPerElement, int &Base) {
5827 Base = -1;
5828 for (unsigned I = 0; I < BytesPerElement; ++I) {
5829 if (Bytes[Start + I] >= 0) {
5830 unsigned Elem = Bytes[Start + I];
5831 if (Base < 0) {
5832 Base = Elem - I;
5833 // Make sure the bytes would come from one input operand.
5834 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
5835 return false;
5836 } else if (unsigned(Base) != Elem - I)
5837 return false;
5838 }
5839 }
5840 return true;
5841}
5842
5843// Bytes is a VPERM-like permute vector, except that -1 is used for
5844// undefined bytes. Return true if it can be performed using VSLDB.
5845// When returning true, set StartIndex to the shift amount and OpNo0
5846// and OpNo1 to the VPERM operands that should be used as the first
5847// and second shift operand respectively.
5849 unsigned &StartIndex, unsigned &OpNo0,
5850 unsigned &OpNo1) {
5851 int OpNos[] = { -1, -1 };
5852 int Shift = -1;
5853 for (unsigned I = 0; I < 16; ++I) {
5854 int Index = Bytes[I];
5855 if (Index >= 0) {
5856 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
5857 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
5858 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
5859 if (Shift < 0)
5860 Shift = ExpectedShift;
5861 else if (Shift != ExpectedShift)
5862 return false;
5863 // Make sure that the operand mappings are consistent with previous
5864 // elements.
5865 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5866 return false;
5867 OpNos[ModelOpNo] = RealOpNo;
5868 }
5869 }
5870 StartIndex = Shift;
5871 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5872}
5873
5874// Create a node that performs P on operands Op0 and Op1, casting the
5875// operands to the appropriate type. The type of the result is determined by P.
5877 const Permute &P, SDValue Op0, SDValue Op1) {
5878 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
5879 // elements of a PACK are twice as wide as the outputs.
5880 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
5881 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
5882 P.Operand);
5883 // Cast both operands to the appropriate type.
5884 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
5885 SystemZ::VectorBytes / InBytes);
5886 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
5887 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
5888 SDValue Op;
5889 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
5890 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
5891 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
5892 } else if (P.Opcode == SystemZISD::PACK) {
5893 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
5894 SystemZ::VectorBytes / P.Operand);
5895 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
5896 } else {
5897 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
5898 }
5899 return Op;
5900}
5901
5902static bool isZeroVector(SDValue N) {
5903 if (N->getOpcode() == ISD::BITCAST)
5904 N = N->getOperand(0);
5905 if (N->getOpcode() == ISD::SPLAT_VECTOR)
5906 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
5907 return Op->getZExtValue() == 0;
5908 return ISD::isBuildVectorAllZeros(N.getNode());
5909}
5910
5911// Return the index of the zero/undef vector, or UINT32_MAX if not found.
5912static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
5913 for (unsigned I = 0; I < Num ; I++)
5914 if (isZeroVector(Ops[I]))
5915 return I;
5916 return UINT32_MAX;
5917}
5918
5919// Bytes is a VPERM-like permute vector, except that -1 is used for
5920// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
5921// VSLDB or VPERM.
5923 SDValue *Ops,
5924 const SmallVectorImpl<int> &Bytes) {
5925 for (unsigned I = 0; I < 2; ++I)
5926 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
5927
5928 // First see whether VSLDB can be used.
5929 unsigned StartIndex, OpNo0, OpNo1;
5930 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
5931 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
5932 Ops[OpNo1],
5933 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
5934
5935 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
5936 // eliminate a zero vector by reusing any zero index in the permute vector.
5937 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
5938 if (ZeroVecIdx != UINT32_MAX) {
5939 bool MaskFirst = true;
5940 int ZeroIdx = -1;
5941 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5942 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
5943 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
5944 if (OpNo == ZeroVecIdx && I == 0) {
5945 // If the first byte is zero, use mask as first operand.
5946 ZeroIdx = 0;
5947 break;
5948 }
5949 if (OpNo != ZeroVecIdx && Byte == 0) {
5950 // If mask contains a zero, use it by placing that vector first.
5951 ZeroIdx = I + SystemZ::VectorBytes;
5952 MaskFirst = false;
5953 break;
5954 }
5955 }
5956 if (ZeroIdx != -1) {
5957 SDValue IndexNodes[SystemZ::VectorBytes];
5958 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5959 if (Bytes[I] >= 0) {
5960 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
5961 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
5962 if (OpNo == ZeroVecIdx)
5963 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
5964 else {
5965 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
5966 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
5967 }
5968 } else
5969 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
5970 }
5971 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
5972 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
5973 if (MaskFirst)
5974 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
5975 Mask);
5976 else
5977 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
5978 Mask);
5979 }
5980 }
5981
5982 SDValue IndexNodes[SystemZ::VectorBytes];
5983 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
5984 if (Bytes[I] >= 0)
5985 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
5986 else
5987 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
5988 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
5989 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
5990 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
5991}
5992
5993namespace {
5994// Describes a general N-operand vector shuffle.
5995struct GeneralShuffle {
5996 GeneralShuffle(EVT vt)
5997 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
5998 void addUndef();
5999 bool add(SDValue, unsigned);
6000 SDValue getNode(SelectionDAG &, const SDLoc &);
6001 void tryPrepareForUnpack();
6002 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6003 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6004
6005 // The operands of the shuffle.
6007
6008 // Index I is -1 if byte I of the result is undefined. Otherwise the
6009 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6010 // Bytes[I] / SystemZ::VectorBytes.
6012
6013 // The type of the shuffle result.
6014 EVT VT;
6015
6016 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6017 unsigned UnpackFromEltSize;
6018 // True if the final unpack uses the low half.
6019 bool UnpackLow;
6020};
6021} // namespace
6022
6023// Add an extra undefined element to the shuffle.
6024void GeneralShuffle::addUndef() {
6025 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6026 for (unsigned I = 0; I < BytesPerElement; ++I)
6027 Bytes.push_back(-1);
6028}
6029
6030// Add an extra element to the shuffle, taking it from element Elem of Op.
6031// A null Op indicates a vector input whose value will be calculated later;
6032// there is at most one such input per shuffle and it always has the same
6033// type as the result. Aborts and returns false if the source vector elements
6034// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6035// LLVM they become implicitly extended, but this is rare and not optimized.
6036bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6037 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6038
6039 // The source vector can have wider elements than the result,
6040 // either through an explicit TRUNCATE or because of type legalization.
6041 // We want the least significant part.
6042 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6043 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6044
6045 // Return false if the source elements are smaller than their destination
6046 // elements.
6047 if (FromBytesPerElement < BytesPerElement)
6048 return false;
6049
6050 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6051 (FromBytesPerElement - BytesPerElement));
6052
6053 // Look through things like shuffles and bitcasts.
6054 while (Op.getNode()) {
6055 if (Op.getOpcode() == ISD::BITCAST)
6056 Op = Op.getOperand(0);
6057 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6058 // See whether the bytes we need come from a contiguous part of one
6059 // operand.
6061 if (!getVPermMask(Op, OpBytes))
6062 break;
6063 int NewByte;
6064 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6065 break;
6066 if (NewByte < 0) {
6067 addUndef();
6068 return true;
6069 }
6070 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6071 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6072 } else if (Op.isUndef()) {
6073 addUndef();
6074 return true;
6075 } else
6076 break;
6077 }
6078
6079 // Make sure that the source of the extraction is in Ops.
6080 unsigned OpNo = 0;
6081 for (; OpNo < Ops.size(); ++OpNo)
6082 if (Ops[OpNo] == Op)
6083 break;
6084 if (OpNo == Ops.size())
6085 Ops.push_back(Op);
6086
6087 // Add the element to Bytes.
6088 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6089 for (unsigned I = 0; I < BytesPerElement; ++I)
6090 Bytes.push_back(Base + I);
6091
6092 return true;
6093}
6094
6095// Return SDNodes for the completed shuffle.
6096SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6097 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6098
6099 if (Ops.size() == 0)
6100 return DAG.getUNDEF(VT);
6101
6102 // Use a single unpack if possible as the last operation.
6103 tryPrepareForUnpack();
6104
6105 // Make sure that there are at least two shuffle operands.
6106 if (Ops.size() == 1)
6107 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6108
6109 // Create a tree of shuffles, deferring root node until after the loop.
6110 // Try to redistribute the undefined elements of non-root nodes so that
6111 // the non-root shuffles match something like a pack or merge, then adjust
6112 // the parent node's permute vector to compensate for the new order.
6113 // Among other things, this copes with vectors like <2 x i16> that were
6114 // padded with undefined elements during type legalization.
6115 //
6116 // In the best case this redistribution will lead to the whole tree
6117 // using packs and merges. It should rarely be a loss in other cases.
6118 unsigned Stride = 1;
6119 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6120 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6121 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6122
6123 // Create a mask for just these two operands.
6125 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6126 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6127 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6128 if (OpNo == I)
6129 NewBytes[J] = Byte;
6130 else if (OpNo == I + Stride)
6131 NewBytes[J] = SystemZ::VectorBytes + Byte;
6132 else
6133 NewBytes[J] = -1;
6134 }
6135 // See if it would be better to reorganize NewMask to avoid using VPERM.
6137 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6138 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6139 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6140 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6141 if (NewBytes[J] >= 0) {
6142 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6143 "Invalid double permute");
6144 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6145 } else
6146 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6147 }
6148 } else {
6149 // Just use NewBytes on the operands.
6150 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6151 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6152 if (NewBytes[J] >= 0)
6153 Bytes[J] = I * SystemZ::VectorBytes + J;
6154 }
6155 }
6156 }
6157
6158 // Now we just have 2 inputs. Put the second operand in Ops[1].
6159 if (Stride > 1) {
6160 Ops[1] = Ops[Stride];
6161 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6162 if (Bytes[I] >= int(SystemZ::VectorBytes))
6163 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6164 }
6165
6166 // Look for an instruction that can do the permute without resorting
6167 // to VPERM.
6168 unsigned OpNo0, OpNo1;
6169 SDValue Op;
6170 if (unpackWasPrepared() && Ops[1].isUndef())
6171 Op = Ops[0];
6172 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6173 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6174 else
6175 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6176
6177 Op = insertUnpackIfPrepared(DAG, DL, Op);
6178
6179 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6180}
6181
6182#ifndef NDEBUG
6183static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6184 dbgs() << Msg.c_str() << " { ";
6185 for (unsigned I = 0; I < Bytes.size(); I++)
6186 dbgs() << Bytes[I] << " ";
6187 dbgs() << "}\n";
6188}
6189#endif
6190
6191// If the Bytes vector matches an unpack operation, prepare to do the unpack
6192// after all else by removing the zero vector and the effect of the unpack on
6193// Bytes.
6194void GeneralShuffle::tryPrepareForUnpack() {
6195 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6196 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6197 return;
6198
6199 // Only do this if removing the zero vector reduces the depth, otherwise
6200 // the critical path will increase with the final unpack.
6201 if (Ops.size() > 2 &&
6202 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6203 return;
6204
6205 // Find an unpack that would allow removing the zero vector from Ops.
6206 UnpackFromEltSize = 1;
6207 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6208 bool MatchUnpack = true;
6210 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6211 unsigned ToEltSize = UnpackFromEltSize * 2;
6212 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6213 if (!IsZextByte)
6214 SrcBytes.push_back(Bytes[Elt]);
6215 if (Bytes[Elt] != -1) {
6216 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6217 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6218 MatchUnpack = false;
6219 break;
6220 }
6221 }
6222 }
6223 if (MatchUnpack) {
6224 if (Ops.size() == 2) {
6225 // Don't use unpack if a single source operand needs rearrangement.
6226 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6227 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6228 if (SrcBytes[i] == -1)
6229 continue;
6230 if (SrcBytes[i] % 16 != int(i))
6231 CanUseUnpackHigh = false;
6232 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6233 CanUseUnpackLow = false;
6234 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6235 UnpackFromEltSize = UINT_MAX;
6236 return;
6237 }
6238 }
6239 if (!CanUseUnpackHigh)
6240 UnpackLow = true;
6241 }
6242 break;
6243 }
6244 }
6245 if (UnpackFromEltSize > 4)
6246 return;
6247
6248 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6249 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6250 << ".\n";
6251 dumpBytes(Bytes, "Original Bytes vector:"););
6252
6253 // Apply the unpack in reverse to the Bytes array.
6254 unsigned B = 0;
6255 if (UnpackLow) {
6256 while (B < SystemZ::VectorBytes / 2)
6257 Bytes[B++] = -1;
6258 }
6259 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6260 Elt += UnpackFromEltSize;
6261 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6262 Bytes[B] = Bytes[Elt];
6263 }
6264 if (!UnpackLow) {
6265 while (B < SystemZ::VectorBytes)
6266 Bytes[B++] = -1;
6267 }
6268
6269 // Remove the zero vector from Ops
6270 Ops.erase(&Ops[ZeroVecOpNo]);
6271 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6272 if (Bytes[I] >= 0) {
6273 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6274 if (OpNo > ZeroVecOpNo)
6275 Bytes[I] -= SystemZ::VectorBytes;
6276 }
6277
6278 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6279 dbgs() << "\n";);
6280}
6281
6282SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6283 const SDLoc &DL,
6284 SDValue Op) {
6285 if (!unpackWasPrepared())
6286 return Op;
6287 unsigned InBits = UnpackFromEltSize * 8;
6288 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6289 SystemZ::VectorBits / InBits);
6290 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6291 unsigned OutBits = InBits * 2;
6292 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6293 SystemZ::VectorBits / OutBits);
6294 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6295 : SystemZISD::UNPACKL_HIGH,
6296 DL, OutVT, PackedOp);
6297}
6298
6299// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6301 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6302 if (!Op.getOperand(I).isUndef())
6303 return false;
6304 return true;
6305}
6306
6307// Return a vector of type VT that contains Value in the first element.
6308// The other elements don't matter.
6310 SDValue Value) {
6311 // If we have a constant, replicate it to all elements and let the
6312 // BUILD_VECTOR lowering take care of it.
6313 if (Value.getOpcode() == ISD::Constant ||
6314 Value.getOpcode() == ISD::ConstantFP) {
6316 return DAG.getBuildVector(VT, DL, Ops);
6317 }
6318 if (Value.isUndef())
6319 return DAG.getUNDEF(VT);
6320 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6321}
6322
6323// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6324// element 1. Used for cases in which replication is cheap.
6326 SDValue Op0, SDValue Op1) {
6327 if (Op0.isUndef()) {
6328 if (Op1.isUndef())
6329 return DAG.getUNDEF(VT);
6330 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6331 }
6332 if (Op1.isUndef())
6333 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6334 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6335 buildScalarToVector(DAG, DL, VT, Op0),
6336 buildScalarToVector(DAG, DL, VT, Op1));
6337}
6338
6339// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6340// vector for them.
6342 SDValue Op1) {
6343 if (Op0.isUndef() && Op1.isUndef())
6344 return DAG.getUNDEF(MVT::v2i64);
6345 // If one of the two inputs is undefined then replicate the other one,
6346 // in order to avoid using another register unnecessarily.
6347 if (Op0.isUndef())
6348 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6349 else if (Op1.isUndef())
6350 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6351 else {
6352 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6353 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6354 }
6355 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6356}
6357
6358// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6359// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6360// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6361// would benefit from this representation and return it if so.
6363 BuildVectorSDNode *BVN) {
6364 EVT VT = BVN->getValueType(0);
6365 unsigned NumElements = VT.getVectorNumElements();
6366
6367 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6368 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6369 // need a BUILD_VECTOR, add an additional placeholder operand for that
6370 // BUILD_VECTOR and store its operands in ResidueOps.
6371 GeneralShuffle GS(VT);
6373 bool FoundOne = false;
6374 for (unsigned I = 0; I < NumElements; ++I) {
6375 SDValue Op = BVN->getOperand(I);
6376 if (Op.getOpcode() == ISD::TRUNCATE)
6377 Op = Op.getOperand(0);
6378 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6379 Op.getOperand(1).getOpcode() == ISD::Constant) {
6380 unsigned Elem = Op.getConstantOperandVal(1);
6381 if (!GS.add(Op.getOperand(0), Elem))
6382 return SDValue();
6383 FoundOne = true;
6384 } else if (Op.isUndef()) {
6385 GS.addUndef();
6386 } else {
6387 if (!GS.add(SDValue(), ResidueOps.size()))
6388 return SDValue();
6389 ResidueOps.push_back(BVN->getOperand(I));
6390 }
6391 }
6392
6393 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6394 if (!FoundOne)
6395 return SDValue();
6396
6397 // Create the BUILD_VECTOR for the remaining elements, if any.
6398 if (!ResidueOps.empty()) {
6399 while (ResidueOps.size() < NumElements)
6400 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6401 for (auto &Op : GS.Ops) {
6402 if (!Op.getNode()) {
6403 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6404 break;
6405 }
6406 }
6407 }
6408 return GS.getNode(DAG, SDLoc(BVN));
6409}
6410
6411bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6412 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6413 return true;
6414 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6415 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6416 return true;
6417 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6418 return true;
6419 return false;
6420}
6421
6423 unsigned MergedBits, EVT VT, SDValue Op0,
6424 SDValue Op1) {
6425 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6426 SystemZ::VectorBits / MergedBits);
6427 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6428 "Handling full vectors only.");
6429 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6430 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6431 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6432 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6433}
6434
6436 EVT VT, SmallVectorImpl<SDValue> &Elems,
6437 unsigned Pos) {
6438 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6439 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6440 // Avoid unnecessary undefs by reusing the other operand.
6441 if (Op01.isUndef()) {
6442 if (Op23.isUndef())
6443 return Op01;
6444 Op01 = Op23;
6445 } else if (Op23.isUndef())
6446 Op23 = Op01;
6447 // Merging identical replications is a no-op.
6448 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6449 return Op01;
6450 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6451 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6452}
6453
6454// Combine GPR scalar values Elems into a vector of type VT.
6455SDValue
6456SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6457 SmallVectorImpl<SDValue> &Elems) const {
6458 // See whether there is a single replicated value.
6460 unsigned int NumElements = Elems.size();
6461 unsigned int Count = 0;
6462 for (auto Elem : Elems) {
6463 if (!Elem.isUndef()) {
6464 if (!Single.getNode())
6465 Single = Elem;
6466 else if (Elem != Single) {
6467 Single = SDValue();
6468 break;
6469 }
6470 Count += 1;
6471 }
6472 }
6473 // There are three cases here:
6474 //
6475 // - if the only defined element is a loaded one, the best sequence
6476 // is a replicating load.
6477 //
6478 // - otherwise, if the only defined element is an i64 value, we will
6479 // end up with the same VLVGP sequence regardless of whether we short-cut
6480 // for replication or fall through to the later code.
6481 //
6482 // - otherwise, if the only defined element is an i32 or smaller value,
6483 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6484 // This is only a win if the single defined element is used more than once.
6485 // In other cases we're better off using a single VLVGx.
6486 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6487 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6488
6489 // If all elements are loads, use VLREP/VLEs (below).
6490 bool AllLoads = true;
6491 for (auto Elem : Elems)
6492 if (!isVectorElementLoad(Elem)) {
6493 AllLoads = false;
6494 break;
6495 }
6496
6497 // The best way of building a v2i64 from two i64s is to use VLVGP.
6498 if (VT == MVT::v2i64 && !AllLoads)
6499 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6500
6501 // Use a 64-bit merge high to combine two doubles.
6502 if (VT == MVT::v2f64 && !AllLoads)
6503 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6504
6505 // Build v4f32 values directly from the FPRs:
6506 //
6507 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6508 // V V VMRHF
6509 // <ABxx> <CDxx>
6510 // V VMRHG
6511 // <ABCD>
6512 if (VT == MVT::v4f32 && !AllLoads)
6513 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6514
6515 // Same for v8f16.
6516 if (VT == MVT::v8f16 && !AllLoads) {
6517 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6518 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6519 // Avoid unnecessary undefs by reusing the other operand.
6520 if (Op0123.isUndef())
6521 Op0123 = Op4567;
6522 else if (Op4567.isUndef())
6523 Op4567 = Op0123;
6524 // Merging identical replications is a no-op.
6525 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6526 return Op0123;
6527 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6528 }
6529
6530 // Collect the constant terms.
6533
6534 unsigned NumConstants = 0;
6535 for (unsigned I = 0; I < NumElements; ++I) {
6536 SDValue Elem = Elems[I];
6537 if (Elem.getOpcode() == ISD::Constant ||
6538 Elem.getOpcode() == ISD::ConstantFP) {
6539 NumConstants += 1;
6540 Constants[I] = Elem;
6541 Done[I] = true;
6542 }
6543 }
6544 // If there was at least one constant, fill in the other elements of
6545 // Constants with undefs to get a full vector constant and use that
6546 // as the starting point.
6548 SDValue ReplicatedVal;
6549 if (NumConstants > 0) {
6550 for (unsigned I = 0; I < NumElements; ++I)
6551 if (!Constants[I].getNode())
6552 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6553 Result = DAG.getBuildVector(VT, DL, Constants);
6554 } else {
6555 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6556 // avoid a false dependency on any previous contents of the vector
6557 // register.
6558
6559 // Use a VLREP if at least one element is a load. Make sure to replicate
6560 // the load with the most elements having its value.
6561 std::map<const SDNode*, unsigned> UseCounts;
6562 SDNode *LoadMaxUses = nullptr;
6563 for (unsigned I = 0; I < NumElements; ++I)
6564 if (isVectorElementLoad(Elems[I])) {
6565 SDNode *Ld = Elems[I].getNode();
6566 unsigned Count = ++UseCounts[Ld];
6567 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6568 LoadMaxUses = Ld;
6569 }
6570 if (LoadMaxUses != nullptr) {
6571 ReplicatedVal = SDValue(LoadMaxUses, 0);
6572 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6573 } else {
6574 // Try to use VLVGP.
6575 unsigned I1 = NumElements / 2 - 1;
6576 unsigned I2 = NumElements - 1;
6577 bool Def1 = !Elems[I1].isUndef();
6578 bool Def2 = !Elems[I2].isUndef();
6579 if (Def1 || Def2) {
6580 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6581 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6582 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6583 joinDwords(DAG, DL, Elem1, Elem2));
6584 Done[I1] = true;
6585 Done[I2] = true;
6586 } else
6587 Result = DAG.getUNDEF(VT);
6588 }
6589 }
6590
6591 // Use VLVGx to insert the other elements.
6592 for (unsigned I = 0; I < NumElements; ++I)
6593 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6594 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6595 DAG.getConstant(I, DL, MVT::i32));
6596 return Result;
6597}
6598
6599SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6600 SelectionDAG &DAG) const {
6601 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6602 SDLoc DL(Op);
6603 EVT VT = Op.getValueType();
6604
6605 if (BVN->isConstant()) {
6606 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6607 return Op;
6608
6609 // Fall back to loading it from memory.
6610 return SDValue();
6611 }
6612
6613 // See if we should use shuffles to construct the vector from other vectors.
6614 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6615 return Res;
6616
6617 // Detect SCALAR_TO_VECTOR conversions.
6619 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6620
6621 // Otherwise use buildVector to build the vector up from GPRs.
6622 unsigned NumElements = Op.getNumOperands();
6624 for (unsigned I = 0; I < NumElements; ++I)
6625 Ops[I] = Op.getOperand(I);
6626 return buildVector(DAG, DL, VT, Ops);
6627}
6628
6629SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6630 SelectionDAG &DAG) const {
6631 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6632 SDLoc DL(Op);
6633 EVT VT = Op.getValueType();
6634 unsigned NumElements = VT.getVectorNumElements();
6635
6636 if (VSN->isSplat()) {
6637 SDValue Op0 = Op.getOperand(0);
6638 unsigned Index = VSN->getSplatIndex();
6639 assert(Index < VT.getVectorNumElements() &&
6640 "Splat index should be defined and in first operand");
6641 // See whether the value we're splatting is directly available as a scalar.
6642 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6644 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6645 // Otherwise keep it as a vector-to-vector operation.
6646 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6647 DAG.getTargetConstant(Index, DL, MVT::i32));
6648 }
6649
6650 GeneralShuffle GS(VT);
6651 for (unsigned I = 0; I < NumElements; ++I) {
6652 int Elt = VSN->getMaskElt(I);
6653 if (Elt < 0)
6654 GS.addUndef();
6655 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6656 unsigned(Elt) % NumElements))
6657 return SDValue();
6658 }
6659 return GS.getNode(DAG, SDLoc(VSN));
6660}
6661
6662SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6663 SelectionDAG &DAG) const {
6664 SDLoc DL(Op);
6665 // Just insert the scalar into element 0 of an undefined vector.
6666 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6667 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6668 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6669}
6670
6671// Shift the lower 2 bytes of Op to the left in order to insert into the
6672// upper 2 bytes of the FP register.
6674 assert(Op.getSimpleValueType() == MVT::i64 &&
6675 "Expexted to convert i64 to f16.");
6676 SDLoc DL(Op);
6677 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6678 DAG.getConstant(48, DL, MVT::i64));
6679 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6680 SDValue F16Val =
6681 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6682 return F16Val;
6683}
6684
6685// Extract Op into GPR and shift the 2 f16 bytes to the right.
6687 assert(Op.getSimpleValueType() == MVT::f16 &&
6688 "Expected to convert f16 to i64.");
6689 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6690 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6691 SDValue(U32, 0), Op);
6692 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6693 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6694 DAG.getConstant(48, DL, MVT::i32));
6695 return Shft;
6696}
6697
6698SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6699 SelectionDAG &DAG) const {
6700 // Handle insertions of floating-point values.
6701 SDLoc DL(Op);
6702 SDValue Op0 = Op.getOperand(0);
6703 SDValue Op1 = Op.getOperand(1);
6704 SDValue Op2 = Op.getOperand(2);
6705 EVT VT = Op.getValueType();
6706
6707 // Insertions into constant indices of a v2f64 can be done using VPDI.
6708 // However, if the inserted value is a bitcast or a constant then it's
6709 // better to use GPRs, as below.
6710 if (VT == MVT::v2f64 &&
6711 Op1.getOpcode() != ISD::BITCAST &&
6712 Op1.getOpcode() != ISD::ConstantFP &&
6713 Op2.getOpcode() == ISD::Constant) {
6714 uint64_t Index = Op2->getAsZExtVal();
6715 unsigned Mask = VT.getVectorNumElements() - 1;
6716 if (Index <= Mask)
6717 return Op;
6718 }
6719
6720 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6721 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6722 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6723 SDValue IntOp1 =
6724 VT == MVT::v8f16
6725 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6726 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6727 SDValue Res =
6728 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6729 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6730 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6731}
6732
6733SDValue
6734SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6735 SelectionDAG &DAG) const {
6736 // Handle extractions of floating-point values.
6737 SDLoc DL(Op);
6738 SDValue Op0 = Op.getOperand(0);
6739 SDValue Op1 = Op.getOperand(1);
6740 EVT VT = Op.getValueType();
6741 EVT VecVT = Op0.getValueType();
6742
6743 // Extractions of constant indices can be done directly.
6744 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
6745 uint64_t Index = CIndexN->getZExtValue();
6746 unsigned Mask = VecVT.getVectorNumElements() - 1;
6747 if (Index <= Mask)
6748 return Op;
6749 }
6750
6751 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6752 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6753 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6754 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6755 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6756 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6757 if (VT == MVT::f16)
6758 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6759 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6760}
6761
6762SDValue SystemZTargetLowering::
6763lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6764 SDValue PackedOp = Op.getOperand(0);
6765 EVT OutVT = Op.getValueType();
6766 EVT InVT = PackedOp.getValueType();
6767 unsigned ToBits = OutVT.getScalarSizeInBits();
6768 unsigned FromBits = InVT.getScalarSizeInBits();
6769 unsigned StartOffset = 0;
6770
6771 // If the input is a VECTOR_SHUFFLE, there are a number of important
6772 // cases where we can directly implement the sign-extension of the
6773 // original input lanes of the shuffle.
6774 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6775 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6776 ArrayRef<int> ShuffleMask = SVN->getMask();
6777 int OutNumElts = OutVT.getVectorNumElements();
6778
6779 // Recognize the special case where the sign-extension can be done
6780 // by the VSEG instruction. Handled via the default expander.
6781 if (ToBits == 64 && OutNumElts == 2) {
6782 int NumElem = ToBits / FromBits;
6783 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6784 return SDValue();
6785 }
6786
6787 // Recognize the special case where we can fold the shuffle by
6788 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6789 int StartOffsetCandidate = -1;
6790 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6791 if (ShuffleMask[Elt] == -1)
6792 continue;
6793 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6794 if (StartOffsetCandidate == -1)
6795 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6796 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6797 continue;
6798 }
6799 StartOffsetCandidate = -1;
6800 break;
6801 }
6802 if (StartOffsetCandidate != -1) {
6803 StartOffset = StartOffsetCandidate;
6804 PackedOp = PackedOp.getOperand(0);
6805 }
6806 }
6807
6808 do {
6809 FromBits *= 2;
6810 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
6811 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
6812 unsigned Opcode = SystemZISD::UNPACK_HIGH;
6813 if (StartOffset >= OutNumElts) {
6814 Opcode = SystemZISD::UNPACK_LOW;
6815 StartOffset -= OutNumElts;
6816 }
6817 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
6818 } while (FromBits != ToBits);
6819 return PackedOp;
6820}
6821
6822// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
6823SDValue SystemZTargetLowering::
6824lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6825 SDValue PackedOp = Op.getOperand(0);
6826 SDLoc DL(Op);
6827 EVT OutVT = Op.getValueType();
6828 EVT InVT = PackedOp.getValueType();
6829 unsigned InNumElts = InVT.getVectorNumElements();
6830 unsigned OutNumElts = OutVT.getVectorNumElements();
6831 unsigned NumInPerOut = InNumElts / OutNumElts;
6832
6833 SDValue ZeroVec =
6834 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
6835
6836 SmallVector<int, 16> Mask(InNumElts);
6837 unsigned ZeroVecElt = InNumElts;
6838 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
6839 unsigned MaskElt = PackedElt * NumInPerOut;
6840 unsigned End = MaskElt + NumInPerOut - 1;
6841 for (; MaskElt < End; MaskElt++)
6842 Mask[MaskElt] = ZeroVecElt++;
6843 Mask[MaskElt] = PackedElt;
6844 }
6845 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
6846 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
6847}
6848
6849SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
6850 unsigned ByScalar) const {
6851 // Look for cases where a vector shift can use the *_BY_SCALAR form.
6852 SDValue Op0 = Op.getOperand(0);
6853 SDValue Op1 = Op.getOperand(1);
6854 SDLoc DL(Op);
6855 EVT VT = Op.getValueType();
6856 unsigned ElemBitSize = VT.getScalarSizeInBits();
6857
6858 // See whether the shift vector is a splat represented as BUILD_VECTOR.
6859 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
6860 APInt SplatBits, SplatUndef;
6861 unsigned SplatBitSize;
6862 bool HasAnyUndefs;
6863 // Check for constant splats. Use ElemBitSize as the minimum element
6864 // width and reject splats that need wider elements.
6865 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6866 ElemBitSize, true) &&
6867 SplatBitSize == ElemBitSize) {
6868 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
6869 DL, MVT::i32);
6870 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6871 }
6872 // Check for variable splats.
6873 BitVector UndefElements;
6874 SDValue Splat = BVN->getSplatValue(&UndefElements);
6875 if (Splat) {
6876 // Since i32 is the smallest legal type, we either need a no-op
6877 // or a truncation.
6878 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
6879 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6880 }
6881 }
6882
6883 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
6884 // and the shift amount is directly available in a GPR.
6885 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
6886 if (VSN->isSplat()) {
6887 SDValue VSNOp0 = VSN->getOperand(0);
6888 unsigned Index = VSN->getSplatIndex();
6889 assert(Index < VT.getVectorNumElements() &&
6890 "Splat index should be defined and in first operand");
6891 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6892 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
6893 // Since i32 is the smallest legal type, we either need a no-op
6894 // or a truncation.
6895 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
6896 VSNOp0.getOperand(Index));
6897 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6898 }
6899 }
6900 }
6901
6902 // Otherwise just treat the current form as legal.
6903 return Op;
6904}
6905
6906SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
6907 SDLoc DL(Op);
6908
6909 // i128 FSHL with a constant amount that is a multiple of 8 can be
6910 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
6911 // facility, FSHL with a constant amount less than 8 can be implemented
6912 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
6913 // combination of the two.
6914 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
6915 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
6916 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
6917 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
6918 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
6919 if (ShiftAmt > 120) {
6920 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
6921 // SHR_DOUBLE_BIT emits fewer instructions.
6922 SDValue Val =
6923 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
6924 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
6925 return DAG.getBitcast(MVT::i128, Val);
6926 }
6927 SmallVector<int, 16> Mask(16);
6928 for (unsigned Elt = 0; Elt < 16; Elt++)
6929 Mask[Elt] = (ShiftAmt >> 3) + Elt;
6930 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
6931 if ((ShiftAmt & 7) == 0)
6932 return DAG.getBitcast(MVT::i128, Shuf1);
6933 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
6934 SDValue Val =
6935 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
6936 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
6937 return DAG.getBitcast(MVT::i128, Val);
6938 }
6939 }
6940
6941 return SDValue();
6942}
6943
6944SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
6945 SDLoc DL(Op);
6946
6947 // i128 FSHR with a constant amount that is a multiple of 8 can be
6948 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
6949 // facility, FSHR with a constant amount less than 8 can be implemented
6950 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
6951 // combination of the two.
6952 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
6953 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
6954 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
6955 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
6956 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
6957 if (ShiftAmt > 120) {
6958 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
6959 // SHL_DOUBLE_BIT emits fewer instructions.
6960 SDValue Val =
6961 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
6962 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
6963 return DAG.getBitcast(MVT::i128, Val);
6964 }
6965 SmallVector<int, 16> Mask(16);
6966 for (unsigned Elt = 0; Elt < 16; Elt++)
6967 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
6968 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
6969 if ((ShiftAmt & 7) == 0)
6970 return DAG.getBitcast(MVT::i128, Shuf1);
6971 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
6972 SDValue Val =
6973 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
6974 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
6975 return DAG.getBitcast(MVT::i128, Val);
6976 }
6977 }
6978
6979 return SDValue();
6980}
6981
6983 SDLoc DL(Op);
6984 SDValue Src = Op.getOperand(0);
6985 MVT DstVT = Op.getSimpleValueType();
6986
6988 unsigned SrcAS = N->getSrcAddressSpace();
6989
6990 assert(SrcAS != N->getDestAddressSpace() &&
6991 "addrspacecast must be between different address spaces");
6992
6993 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
6994 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
6995 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
6996 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
6997 DAG.getConstant(0x7fffffff, DL, MVT::i32));
6998 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
6999 } else if (DstVT == MVT::i32) {
7000 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7001 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7002 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7003 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7004 } else {
7005 report_fatal_error("Bad address space in addrspacecast");
7006 }
7007 return Op;
7008}
7009
7010SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7011 SelectionDAG &DAG) const {
7012 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7013 if (In.getSimpleValueType() != MVT::f16)
7014 return Op; // Legal
7015 return SDValue(); // Let legalizer emit the libcall.
7016}
7017
7019 MVT VT, SDValue Arg, SDLoc DL,
7020 SDValue Chain, bool IsStrict) const {
7021 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7022 MakeLibCallOptions CallOptions;
7023 SDValue Result;
7024 std::tie(Result, Chain) =
7025 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7026 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7027}
7028
7029SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7030 SelectionDAG &DAG) const {
7031 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7032 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7033 bool IsStrict = Op->isStrictFPOpcode();
7034 SDLoc DL(Op);
7035 MVT VT = Op.getSimpleValueType();
7036 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7037 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7038 EVT InVT = InOp.getValueType();
7039
7040 // FP to unsigned is not directly supported on z10. Promoting an i32
7041 // result to (signed) i64 doesn't generate an inexact condition (fp
7042 // exception) for values that are outside the i32 range but in the i64
7043 // range, so use the default expansion.
7044 if (!Subtarget.hasFPExtension() && !IsSigned)
7045 // Expand i32/i64. F16 values will be recognized to fit and extended.
7046 return SDValue();
7047
7048 // Conversion from f16 is done via f32.
7049 if (InOp.getSimpleValueType() == MVT::f16) {
7051 LowerOperationWrapper(Op.getNode(), Results, DAG);
7052 return DAG.getMergeValues(Results, DL);
7053 }
7054
7055 if (VT == MVT::i128) {
7056 RTLIB::Libcall LC =
7057 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7058 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7059 }
7060
7061 return Op; // Legal
7062}
7063
7064SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7065 SelectionDAG &DAG) const {
7066 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7067 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7068 bool IsStrict = Op->isStrictFPOpcode();
7069 SDLoc DL(Op);
7070 MVT VT = Op.getSimpleValueType();
7071 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7072 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7073 EVT InVT = InOp.getValueType();
7074
7075 // Conversion to f16 is done via f32.
7076 if (VT == MVT::f16) {
7078 LowerOperationWrapper(Op.getNode(), Results, DAG);
7079 return DAG.getMergeValues(Results, DL);
7080 }
7081
7082 // Unsigned to fp is not directly supported on z10.
7083 if (!Subtarget.hasFPExtension() && !IsSigned)
7084 return SDValue(); // Expand i64.
7085
7086 if (InVT == MVT::i128) {
7087 RTLIB::Libcall LC =
7088 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7089 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7090 }
7091
7092 return Op; // Legal
7093}
7094
7095// Lower an f16 LOAD in case of no vector support.
7096SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7097 SelectionDAG &DAG) const {
7098 EVT RegVT = Op.getValueType();
7099 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7100 (void)RegVT;
7101
7102 // Load as integer.
7103 SDLoc DL(Op);
7104 SDValue NewLd;
7105 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7106 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7107 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7108 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7109 AtomicLd->getMemOperand());
7110 } else {
7111 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7112 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7113 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7114 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7115 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7116 }
7117 SDValue F16Val = convertToF16(NewLd, DAG);
7118 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7119}
7120
7121// Lower an f16 STORE in case of no vector support.
7122SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7123 SelectionDAG &DAG) const {
7124 SDLoc DL(Op);
7125 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7126
7127 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7128 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7129 Shft, AtomicSt->getBasePtr(),
7130 AtomicSt->getMemOperand());
7131
7132 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7133 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7134 St->getMemOperand());
7135}
7136
7137SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7138 SelectionDAG &DAG) const {
7139 SDLoc DL(Op);
7140 MVT ResultVT = Op.getSimpleValueType();
7141 SDValue Arg = Op.getOperand(0);
7142 unsigned Check = Op.getConstantOperandVal(1);
7143
7144 unsigned TDCMask = 0;
7145 if (Check & fcSNan)
7147 if (Check & fcQNan)
7149 if (Check & fcPosInf)
7151 if (Check & fcNegInf)
7153 if (Check & fcPosNormal)
7155 if (Check & fcNegNormal)
7157 if (Check & fcPosSubnormal)
7159 if (Check & fcNegSubnormal)
7161 if (Check & fcPosZero)
7162 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7163 if (Check & fcNegZero)
7164 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7165 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7166
7167 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7168 return getCCResult(DAG, Intr);
7169}
7170
7171SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7172 SelectionDAG &DAG) const {
7173 SDLoc DL(Op);
7174 SDValue Chain = Op.getOperand(0);
7175
7176 // STCKF only supports a memory operand, so we have to use a temporary.
7177 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7178 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7179 MachinePointerInfo MPI =
7181
7182 // Use STCFK to store the TOD clock into the temporary.
7183 SDValue StoreOps[] = {Chain, StackPtr};
7184 Chain = DAG.getMemIntrinsicNode(
7185 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7186 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7187
7188 // And read it back from there.
7189 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7190}
7191
7193 SelectionDAG &DAG) const {
7194 switch (Op.getOpcode()) {
7195 case ISD::FRAMEADDR:
7196 return lowerFRAMEADDR(Op, DAG);
7197 case ISD::RETURNADDR:
7198 return lowerRETURNADDR(Op, DAG);
7199 case ISD::BR_CC:
7200 return lowerBR_CC(Op, DAG);
7201 case ISD::SELECT_CC:
7202 return lowerSELECT_CC(Op, DAG);
7203 case ISD::SETCC:
7204 return lowerSETCC(Op, DAG);
7205 case ISD::STRICT_FSETCC:
7206 return lowerSTRICT_FSETCC(Op, DAG, false);
7208 return lowerSTRICT_FSETCC(Op, DAG, true);
7209 case ISD::GlobalAddress:
7210 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7212 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7213 case ISD::BlockAddress:
7214 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7215 case ISD::JumpTable:
7216 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7217 case ISD::ConstantPool:
7218 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7219 case ISD::BITCAST:
7220 return lowerBITCAST(Op, DAG);
7221 case ISD::VASTART:
7222 return lowerVASTART(Op, DAG);
7223 case ISD::VACOPY:
7224 return lowerVACOPY(Op, DAG);
7226 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7228 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7229 case ISD::MULHS:
7230 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7231 case ISD::MULHU:
7232 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7233 case ISD::SMUL_LOHI:
7234 return lowerSMUL_LOHI(Op, DAG);
7235 case ISD::UMUL_LOHI:
7236 return lowerUMUL_LOHI(Op, DAG);
7237 case ISD::SDIVREM:
7238 return lowerSDIVREM(Op, DAG);
7239 case ISD::UDIVREM:
7240 return lowerUDIVREM(Op, DAG);
7241 case ISD::SADDO:
7242 case ISD::SSUBO:
7243 case ISD::UADDO:
7244 case ISD::USUBO:
7245 return lowerXALUO(Op, DAG);
7246 case ISD::UADDO_CARRY:
7247 case ISD::USUBO_CARRY:
7248 return lowerUADDSUBO_CARRY(Op, DAG);
7249 case ISD::OR:
7250 return lowerOR(Op, DAG);
7251 case ISD::CTPOP:
7252 return lowerCTPOP(Op, DAG);
7253 case ISD::VECREDUCE_ADD:
7254 return lowerVECREDUCE_ADD(Op, DAG);
7255 case ISD::ATOMIC_FENCE:
7256 return lowerATOMIC_FENCE(Op, DAG);
7257 case ISD::ATOMIC_SWAP:
7258 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
7259 case ISD::ATOMIC_STORE:
7260 return lowerATOMIC_STORE(Op, DAG);
7261 case ISD::ATOMIC_LOAD:
7262 return lowerATOMIC_LOAD(Op, DAG);
7264 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7266 return lowerATOMIC_LOAD_SUB(Op, DAG);
7268 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
7270 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
7272 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7274 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7276 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7278 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7280 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7282 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7284 return lowerATOMIC_CMP_SWAP(Op, DAG);
7285 case ISD::STACKSAVE:
7286 return lowerSTACKSAVE(Op, DAG);
7287 case ISD::STACKRESTORE:
7288 return lowerSTACKRESTORE(Op, DAG);
7289 case ISD::PREFETCH:
7290 return lowerPREFETCH(Op, DAG);
7292 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7294 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7295 case ISD::BUILD_VECTOR:
7296 return lowerBUILD_VECTOR(Op, DAG);
7298 return lowerVECTOR_SHUFFLE(Op, DAG);
7300 return lowerSCALAR_TO_VECTOR(Op, DAG);
7302 return lowerINSERT_VECTOR_ELT(Op, DAG);
7304 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7306 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7308 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7309 case ISD::SHL:
7310 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7311 case ISD::SRL:
7312 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7313 case ISD::SRA:
7314 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7315 case ISD::ADDRSPACECAST:
7316 return lowerAddrSpaceCast(Op, DAG);
7317 case ISD::ROTL:
7318 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7319 case ISD::FSHL:
7320 return lowerFSHL(Op, DAG);
7321 case ISD::FSHR:
7322 return lowerFSHR(Op, DAG);
7323 case ISD::FP_EXTEND:
7325 return lowerFP_EXTEND(Op, DAG);
7326 case ISD::FP_TO_UINT:
7327 case ISD::FP_TO_SINT:
7330 return lower_FP_TO_INT(Op, DAG);
7331 case ISD::UINT_TO_FP:
7332 case ISD::SINT_TO_FP:
7335 return lower_INT_TO_FP(Op, DAG);
7336 case ISD::LOAD:
7337 return lowerLoadF16(Op, DAG);
7338 case ISD::STORE:
7339 return lowerStoreF16(Op, DAG);
7340 case ISD::IS_FPCLASS:
7341 return lowerIS_FPCLASS(Op, DAG);
7342 case ISD::GET_ROUNDING:
7343 return lowerGET_ROUNDING(Op, DAG);
7345 return lowerREADCYCLECOUNTER(Op, DAG);
7348 // These operations are legal on our platform, but we cannot actually
7349 // set the operation action to Legal as common code would treat this
7350 // as equivalent to Expand. Instead, we keep the operation action to
7351 // Custom and just leave them unchanged here.
7352 return Op;
7353
7354 default:
7355 llvm_unreachable("Unexpected node to lower");
7356 }
7357}
7358
7360 const SDLoc &SL) {
7361 // If i128 is legal, just use a normal bitcast.
7362 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7363 return DAG.getBitcast(MVT::f128, Src);
7364
7365 // Otherwise, f128 must live in FP128, so do a partwise move.
7367 &SystemZ::FP128BitRegClass);
7368
7369 SDValue Hi, Lo;
7370 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7371
7372 Hi = DAG.getBitcast(MVT::f64, Hi);
7373 Lo = DAG.getBitcast(MVT::f64, Lo);
7374
7375 SDNode *Pair = DAG.getMachineNode(
7376 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7377 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7378 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7379 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7380 return SDValue(Pair, 0);
7381}
7382
7384 const SDLoc &SL) {
7385 // If i128 is legal, just use a normal bitcast.
7386 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7387 return DAG.getBitcast(MVT::i128, Src);
7388
7389 // Otherwise, f128 must live in FP128, so do a partwise move.
7391 &SystemZ::FP128BitRegClass);
7392
7393 SDValue LoFP =
7394 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7395 SDValue HiFP =
7396 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7397 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7398 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7399
7400 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7401}
7402
7403// Lower operations with invalid operand or result types.
7404void
7407 SelectionDAG &DAG) const {
7408 switch (N->getOpcode()) {
7409 case ISD::ATOMIC_LOAD: {
7410 SDLoc DL(N);
7411 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
7412 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7413 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7414 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7415 DL, Tys, Ops, MVT::i128, MMO);
7416
7417 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7418 if (N->getValueType(0) == MVT::f128)
7419 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7420 Results.push_back(Lowered);
7421 Results.push_back(Res.getValue(1));
7422 break;
7423 }
7424 case ISD::ATOMIC_STORE: {
7425 SDLoc DL(N);
7426 SDVTList Tys = DAG.getVTList(MVT::Other);
7427 SDValue Val = N->getOperand(1);
7428 if (Val.getValueType() == MVT::f128)
7429 Val = expandBitCastF128ToI128(DAG, Val, DL);
7430 Val = lowerI128ToGR128(DAG, Val);
7431
7432 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7433 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7434 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7435 DL, Tys, Ops, MVT::i128, MMO);
7436 // We have to enforce sequential consistency by performing a
7437 // serialization operation after the store.
7438 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7440 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7441 MVT::Other, Res), 0);
7442 Results.push_back(Res);
7443 break;
7444 }
7446 SDLoc DL(N);
7447 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
7448 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7449 lowerI128ToGR128(DAG, N->getOperand(2)),
7450 lowerI128ToGR128(DAG, N->getOperand(3)) };
7451 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7452 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7453 DL, Tys, Ops, MVT::i128, MMO);
7454 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7456 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7457 Results.push_back(lowerGR128ToI128(DAG, Res));
7458 Results.push_back(Success);
7459 Results.push_back(Res.getValue(2));
7460 break;
7461 }
7462 case ISD::BITCAST: {
7463 if (useSoftFloat())
7464 return;
7465 SDLoc DL(N);
7466 SDValue Src = N->getOperand(0);
7467 EVT SrcVT = Src.getValueType();
7468 EVT ResVT = N->getValueType(0);
7469 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7470 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7471 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7472 if (Subtarget.hasVector()) {
7473 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7474 Results.push_back(SDValue(
7475 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7476 } else {
7477 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7478 Results.push_back(convertToF16(In64, DAG));
7479 }
7480 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7481 SDValue ExtractedVal =
7482 Subtarget.hasVector()
7483 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7484 0)
7485 : convertFromF16(Src, DL, DAG);
7486 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7487 }
7488 break;
7489 }
7490 case ISD::UINT_TO_FP:
7491 case ISD::SINT_TO_FP:
7494 if (useSoftFloat())
7495 return;
7496 bool IsStrict = N->isStrictFPOpcode();
7497 SDLoc DL(N);
7498 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7499 EVT ResVT = N->getValueType(0);
7500 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7501 if (ResVT == MVT::f16) {
7502 if (!IsStrict) {
7503 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7504 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7505 } else {
7506 SDValue OpF32 =
7507 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7508 {Chain, InOp});
7509 SDValue F16Res;
7510 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7511 OpF32, OpF32.getValue(1), DL, MVT::f16);
7512 Results.push_back(F16Res);
7513 Results.push_back(Chain);
7514 }
7515 }
7516 break;
7517 }
7518 case ISD::FP_TO_UINT:
7519 case ISD::FP_TO_SINT:
7522 if (useSoftFloat())
7523 return;
7524 bool IsStrict = N->isStrictFPOpcode();
7525 SDLoc DL(N);
7526 EVT ResVT = N->getValueType(0);
7527 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7528 EVT InVT = InOp->getValueType(0);
7529 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7530 if (InVT == MVT::f16) {
7531 if (!IsStrict) {
7532 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7533 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7534 } else {
7535 SDValue InF32;
7536 std::tie(InF32, Chain) =
7537 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7538 SDValue OpF32 =
7539 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7540 {Chain, InF32});
7541 Results.push_back(OpF32);
7542 Results.push_back(OpF32.getValue(1));
7543 }
7544 }
7545 break;
7546 }
7547 default:
7548 llvm_unreachable("Unexpected node to lower");
7549 }
7550}
7551
7552void
7558
7559// Return true if VT is a vector whose elements are a whole number of bytes
7560// in width. Also check for presence of vector support.
7561bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7562 if (!Subtarget.hasVector())
7563 return false;
7564
7565 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7566}
7567
7568// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7569// producing a result of type ResVT. Op is a possibly bitcast version
7570// of the input vector and Index is the index (based on type VecVT) that
7571// should be extracted. Return the new extraction if a simplification
7572// was possible or if Force is true.
7573SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7574 EVT VecVT, SDValue Op,
7575 unsigned Index,
7576 DAGCombinerInfo &DCI,
7577 bool Force) const {
7578 SelectionDAG &DAG = DCI.DAG;
7579
7580 // The number of bytes being extracted.
7581 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7582
7583 for (;;) {
7584 unsigned Opcode = Op.getOpcode();
7585 if (Opcode == ISD::BITCAST)
7586 // Look through bitcasts.
7587 Op = Op.getOperand(0);
7588 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7589 canTreatAsByteVector(Op.getValueType())) {
7590 // Get a VPERM-like permute mask and see whether the bytes covered
7591 // by the extracted element are a contiguous sequence from one
7592 // source operand.
7594 if (!getVPermMask(Op, Bytes))
7595 break;
7596 int First;
7597 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7598 BytesPerElement, First))
7599 break;
7600 if (First < 0)
7601 return DAG.getUNDEF(ResVT);
7602 // Make sure the contiguous sequence starts at a multiple of the
7603 // original element size.
7604 unsigned Byte = unsigned(First) % Bytes.size();
7605 if (Byte % BytesPerElement != 0)
7606 break;
7607 // We can get the extracted value directly from an input.
7608 Index = Byte / BytesPerElement;
7609 Op = Op.getOperand(unsigned(First) / Bytes.size());
7610 Force = true;
7611 } else if (Opcode == ISD::BUILD_VECTOR &&
7612 canTreatAsByteVector(Op.getValueType())) {
7613 // We can only optimize this case if the BUILD_VECTOR elements are
7614 // at least as wide as the extracted value.
7615 EVT OpVT = Op.getValueType();
7616 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7617 if (OpBytesPerElement < BytesPerElement)
7618 break;
7619 // Make sure that the least-significant bit of the extracted value
7620 // is the least significant bit of an input.
7621 unsigned End = (Index + 1) * BytesPerElement;
7622 if (End % OpBytesPerElement != 0)
7623 break;
7624 // We're extracting the low part of one operand of the BUILD_VECTOR.
7625 Op = Op.getOperand(End / OpBytesPerElement - 1);
7626 if (!Op.getValueType().isInteger()) {
7627 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
7628 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
7629 DCI.AddToWorklist(Op.getNode());
7630 }
7631 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
7632 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7633 if (VT != ResVT) {
7634 DCI.AddToWorklist(Op.getNode());
7635 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7636 }
7637 return Op;
7638 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7640 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7641 canTreatAsByteVector(Op.getValueType()) &&
7642 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7643 // Make sure that only the unextended bits are significant.
7644 EVT ExtVT = Op.getValueType();
7645 EVT OpVT = Op.getOperand(0).getValueType();
7646 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7647 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7648 unsigned Byte = Index * BytesPerElement;
7649 unsigned SubByte = Byte % ExtBytesPerElement;
7650 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7651 if (SubByte < MinSubByte ||
7652 SubByte + BytesPerElement > ExtBytesPerElement)
7653 break;
7654 // Get the byte offset of the unextended element
7655 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7656 // ...then add the byte offset relative to that element.
7657 Byte += SubByte - MinSubByte;
7658 if (Byte % BytesPerElement != 0)
7659 break;
7660 Op = Op.getOperand(0);
7661 Index = Byte / BytesPerElement;
7662 Force = true;
7663 } else
7664 break;
7665 }
7666 if (Force) {
7667 if (Op.getValueType() != VecVT) {
7668 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7669 DCI.AddToWorklist(Op.getNode());
7670 }
7671 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7672 DAG.getConstant(Index, DL, MVT::i32));
7673 }
7674 return SDValue();
7675}
7676
7677// Optimize vector operations in scalar value Op on the basis that Op
7678// is truncated to TruncVT.
7679SDValue SystemZTargetLowering::combineTruncateExtract(
7680 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7681 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7682 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7683 // of type TruncVT.
7684 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7685 TruncVT.getSizeInBits() % 8 == 0) {
7686 SDValue Vec = Op.getOperand(0);
7687 EVT VecVT = Vec.getValueType();
7688 if (canTreatAsByteVector(VecVT)) {
7689 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7690 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7691 unsigned TruncBytes = TruncVT.getStoreSize();
7692 if (BytesPerElement % TruncBytes == 0) {
7693 // Calculate the value of Y' in the above description. We are
7694 // splitting the original elements into Scale equal-sized pieces
7695 // and for truncation purposes want the last (least-significant)
7696 // of these pieces for IndexN. This is easiest to do by calculating
7697 // the start index of the following element and then subtracting 1.
7698 unsigned Scale = BytesPerElement / TruncBytes;
7699 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7700
7701 // Defer the creation of the bitcast from X to combineExtract,
7702 // which might be able to optimize the extraction.
7703 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7704 MVT::getIntegerVT(TruncBytes * 8),
7705 VecVT.getStoreSize() / TruncBytes);
7706 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7707 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7708 }
7709 }
7710 }
7711 }
7712 return SDValue();
7713}
7714
7715SDValue SystemZTargetLowering::combineZERO_EXTEND(
7716 SDNode *N, DAGCombinerInfo &DCI) const {
7717 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7718 SelectionDAG &DAG = DCI.DAG;
7719 SDValue N0 = N->getOperand(0);
7720 EVT VT = N->getValueType(0);
7721 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7722 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7723 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7724 if (TrueOp && FalseOp) {
7725 SDLoc DL(N0);
7726 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7727 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7728 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7729 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7730 // If N0 has multiple uses, change other uses as well.
7731 if (!N0.hasOneUse()) {
7732 SDValue TruncSelect =
7733 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7734 DCI.CombineTo(N0.getNode(), TruncSelect);
7735 }
7736 return NewSelect;
7737 }
7738 }
7739 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7740 // of the result is smaller than the size of X and all the truncated bits
7741 // of X are already zero.
7742 if (N0.getOpcode() == ISD::XOR &&
7743 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7744 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7745 N0.getOperand(1).getOpcode() == ISD::Constant) {
7746 SDValue X = N0.getOperand(0).getOperand(0);
7747 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7748 KnownBits Known = DAG.computeKnownBits(X);
7749 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7750 N0.getValueSizeInBits(),
7751 VT.getSizeInBits());
7752 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7753 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7754 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7755 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7756 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7757 }
7758 }
7759 }
7760 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7761 // and VECTOR ADD COMPUTE CARRY for i128:
7762 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7763 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7764 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7765 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7766 // For vector types, these patterns are recognized in the .td file.
7767 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7768 N0.getOperand(0).getValueType() == VT) {
7769 SDValue Op0 = N0.getOperand(0);
7770 SDValue Op1 = N0.getOperand(1);
7771 const ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7772 switch (CC) {
7773 case ISD::SETULE:
7774 std::swap(Op0, Op1);
7775 [[fallthrough]];
7776 case ISD::SETUGE:
7777 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7778 case ISD::SETUGT:
7779 std::swap(Op0, Op1);
7780 [[fallthrough]];
7781 case ISD::SETULT:
7782 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
7783 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
7784 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
7785 Op0->getOperand(1));
7786 break;
7787 default:
7788 break;
7789 }
7790 }
7791
7792 return SDValue();
7793}
7794
7795SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
7796 SDNode *N, DAGCombinerInfo &DCI) const {
7797 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
7798 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
7799 // into (select_cc LHS, RHS, -1, 0, COND)
7800 SelectionDAG &DAG = DCI.DAG;
7801 SDValue N0 = N->getOperand(0);
7802 EVT VT = N->getValueType(0);
7803 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7804 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
7805 N0 = N0.getOperand(0);
7806 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
7807 SDLoc DL(N0);
7808 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
7809 DAG.getAllOnesConstant(DL, VT),
7810 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
7811 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
7812 }
7813 return SDValue();
7814}
7815
7816SDValue SystemZTargetLowering::combineSIGN_EXTEND(
7817 SDNode *N, DAGCombinerInfo &DCI) const {
7818 // Convert (sext (ashr (shl X, C1), C2)) to
7819 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
7820 // cheap as narrower ones.
7821 SelectionDAG &DAG = DCI.DAG;
7822 SDValue N0 = N->getOperand(0);
7823 EVT VT = N->getValueType(0);
7824 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
7825 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7826 SDValue Inner = N0.getOperand(0);
7827 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
7828 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
7829 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
7830 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
7831 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
7832 EVT ShiftVT = N0.getOperand(1).getValueType();
7833 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
7834 Inner.getOperand(0));
7835 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
7836 DAG.getConstant(NewShlAmt, SDLoc(Inner),
7837 ShiftVT));
7838 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
7839 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
7840 }
7841 }
7842 }
7843
7844 return SDValue();
7845}
7846
7847SDValue SystemZTargetLowering::combineMERGE(
7848 SDNode *N, DAGCombinerInfo &DCI) const {
7849 SelectionDAG &DAG = DCI.DAG;
7850 unsigned Opcode = N->getOpcode();
7851 SDValue Op0 = N->getOperand(0);
7852 SDValue Op1 = N->getOperand(1);
7853 if (Op0.getOpcode() == ISD::BITCAST)
7854 Op0 = Op0.getOperand(0);
7856 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
7857 // for v4f32.
7858 if (Op1 == N->getOperand(0))
7859 return Op1;
7860 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
7861 EVT VT = Op1.getValueType();
7862 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
7863 if (ElemBytes <= 4) {
7864 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
7865 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
7866 EVT InVT = VT.changeVectorElementTypeToInteger();
7867 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
7868 SystemZ::VectorBytes / ElemBytes / 2);
7869 if (VT != InVT) {
7870 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
7871 DCI.AddToWorklist(Op1.getNode());
7872 }
7873 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
7874 DCI.AddToWorklist(Op.getNode());
7875 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7876 }
7877 }
7878 return SDValue();
7879}
7880
7881static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7882 SDNode *&HiPart) {
7883 LoPart = HiPart = nullptr;
7884
7885 // Scan through all users.
7886 for (SDUse &Use : LD->uses()) {
7887 // Skip the uses of the chain.
7888 if (Use.getResNo() != 0)
7889 continue;
7890
7891 // Verify every user is a TRUNCATE to i64 of the low or high half.
7892 SDNode *User = Use.getUser();
7893 bool IsLoPart = true;
7894 if (User->getOpcode() == ISD::SRL &&
7895 User->getOperand(1).getOpcode() == ISD::Constant &&
7896 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
7897 User = *User->user_begin();
7898 IsLoPart = false;
7899 }
7900 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
7901 return false;
7902
7903 if (IsLoPart) {
7904 if (LoPart)
7905 return false;
7906 LoPart = User;
7907 } else {
7908 if (HiPart)
7909 return false;
7910 HiPart = User;
7911 }
7912 }
7913 return true;
7914}
7915
7916static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7917 SDNode *&HiPart) {
7918 LoPart = HiPart = nullptr;
7919
7920 // Scan through all users.
7921 for (SDUse &Use : LD->uses()) {
7922 // Skip the uses of the chain.
7923 if (Use.getResNo() != 0)
7924 continue;
7925
7926 // Verify every user is an EXTRACT_SUBREG of the low or high half.
7927 SDNode *User = Use.getUser();
7928 if (!User->hasOneUse() || !User->isMachineOpcode() ||
7929 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7930 return false;
7931
7932 switch (User->getConstantOperandVal(1)) {
7933 case SystemZ::subreg_l64:
7934 if (LoPart)
7935 return false;
7936 LoPart = User;
7937 break;
7938 case SystemZ::subreg_h64:
7939 if (HiPart)
7940 return false;
7941 HiPart = User;
7942 break;
7943 default:
7944 return false;
7945 }
7946 }
7947 return true;
7948}
7949
7950SDValue SystemZTargetLowering::combineLOAD(
7951 SDNode *N, DAGCombinerInfo &DCI) const {
7952 SelectionDAG &DAG = DCI.DAG;
7953 EVT LdVT = N->getValueType(0);
7954 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
7955 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
7956 MVT PtrVT = getPointerTy(DAG.getDataLayout());
7957 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
7958 if (PtrVT != LoadNodeVT) {
7959 SDLoc DL(LN);
7960 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
7961 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
7962 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
7963 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
7964 LN->getMemOperand());
7965 }
7966 }
7967 }
7968 SDLoc DL(N);
7969
7970 // Replace a 128-bit load that is used solely to move its value into GPRs
7971 // by separate loads of both halves.
7972 LoadSDNode *LD = cast<LoadSDNode>(N);
7973 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
7974 SDNode *LoPart, *HiPart;
7975 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
7976 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
7977 // Rewrite each extraction as an independent load.
7978 SmallVector<SDValue, 2> ArgChains;
7979 if (HiPart) {
7980 SDValue EltLoad = DAG.getLoad(
7981 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
7982 LD->getPointerInfo(), LD->getBaseAlign(),
7983 LD->getMemOperand()->getFlags(), LD->getAAInfo());
7984
7985 DCI.CombineTo(HiPart, EltLoad, true);
7986 ArgChains.push_back(EltLoad.getValue(1));
7987 }
7988 if (LoPart) {
7989 SDValue EltLoad = DAG.getLoad(
7990 LoPart->getValueType(0), DL, LD->getChain(),
7991 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
7992 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
7993 LD->getMemOperand()->getFlags(), LD->getAAInfo());
7994
7995 DCI.CombineTo(LoPart, EltLoad, true);
7996 ArgChains.push_back(EltLoad.getValue(1));
7997 }
7998
7999 // Collect all chains via TokenFactor.
8000 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8001 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8002 DCI.AddToWorklist(Chain.getNode());
8003 return SDValue(N, 0);
8004 }
8005 }
8006
8007 if (LdVT.isVector() || LdVT.isInteger())
8008 return SDValue();
8009 // Transform a scalar load that is REPLICATEd as well as having other
8010 // use(s) to the form where the other use(s) use the first element of the
8011 // REPLICATE instead of the load. Otherwise instruction selection will not
8012 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8013 // point loads.
8014
8015 SDValue Replicate;
8016 SmallVector<SDNode*, 8> OtherUses;
8017 for (SDUse &Use : N->uses()) {
8018 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8019 if (Replicate)
8020 return SDValue(); // Should never happen
8021 Replicate = SDValue(Use.getUser(), 0);
8022 } else if (Use.getResNo() == 0)
8023 OtherUses.push_back(Use.getUser());
8024 }
8025 if (!Replicate || OtherUses.empty())
8026 return SDValue();
8027
8028 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8029 Replicate, DAG.getConstant(0, DL, MVT::i32));
8030 // Update uses of the loaded Value while preserving old chains.
8031 for (SDNode *U : OtherUses) {
8033 for (SDValue Op : U->ops())
8034 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8035 DAG.UpdateNodeOperands(U, Ops);
8036 }
8037 return SDValue(N, 0);
8038}
8039
8040bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8041 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8042 return true;
8043 if (Subtarget.hasVectorEnhancements2())
8044 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8045 return true;
8046 return false;
8047}
8048
8050 if (!VT.isVector() || !VT.isSimple() ||
8051 VT.getSizeInBits() != 128 ||
8052 VT.getScalarSizeInBits() % 8 != 0)
8053 return false;
8054
8055 unsigned NumElts = VT.getVectorNumElements();
8056 for (unsigned i = 0; i < NumElts; ++i) {
8057 if (M[i] < 0) continue; // ignore UNDEF indices
8058 if ((unsigned) M[i] != NumElts - 1 - i)
8059 return false;
8060 }
8061
8062 return true;
8063}
8064
8065static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8066 for (auto *U : StoredVal->users()) {
8067 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8068 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8069 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8070 continue;
8071 } else if (isa<BuildVectorSDNode>(U)) {
8072 SDValue BuildVector = SDValue(U, 0);
8073 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8074 isOnlyUsedByStores(BuildVector, DAG))
8075 continue;
8076 }
8077 return false;
8078 }
8079 return true;
8080}
8081
8082static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8083 SDValue &HiPart) {
8084 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8085 return false;
8086
8087 SDValue Op0 = Val.getOperand(0);
8088 SDValue Op1 = Val.getOperand(1);
8089
8090 if (Op0.getOpcode() == ISD::SHL)
8091 std::swap(Op0, Op1);
8092 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8093 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8094 Op1.getConstantOperandVal(1) != 64)
8095 return false;
8096 Op1 = Op1.getOperand(0);
8097
8098 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8099 Op0.getOperand(0).getValueType() != MVT::i64)
8100 return false;
8101 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8102 Op1.getOperand(0).getValueType() != MVT::i64)
8103 return false;
8104
8105 LoPart = Op0.getOperand(0);
8106 HiPart = Op1.getOperand(0);
8107 return true;
8108}
8109
8110static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8111 SDValue &HiPart) {
8112 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8113 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8114 return false;
8115
8116 if (Val->getNumOperands() != 5 ||
8117 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8118 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8119 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8120 return false;
8121
8122 LoPart = Val->getOperand(1);
8123 HiPart = Val->getOperand(3);
8124 return true;
8125}
8126
8127SDValue SystemZTargetLowering::combineSTORE(
8128 SDNode *N, DAGCombinerInfo &DCI) const {
8129 SelectionDAG &DAG = DCI.DAG;
8130 auto *SN = cast<StoreSDNode>(N);
8131 auto &Op1 = N->getOperand(1);
8132 EVT MemVT = SN->getMemoryVT();
8133
8134 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8135 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8136 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8137 if (PtrVT != StoreNodeVT) {
8138 SDLoc DL(SN);
8139 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8140 SYSTEMZAS::PTR32, 0);
8141 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8142 SN->getPointerInfo(), SN->getBaseAlign(),
8143 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8144 }
8145 }
8146
8147 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8148 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8149 // If X has wider elements then convert it to:
8150 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8151 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8152 if (SDValue Value =
8153 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8154 DCI.AddToWorklist(Value.getNode());
8155
8156 // Rewrite the store with the new form of stored value.
8157 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8158 SN->getBasePtr(), SN->getMemoryVT(),
8159 SN->getMemOperand());
8160 }
8161 }
8162
8163 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8164 if (Op1->isMachineOpcode() &&
8165 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8166 // Obtain the frame index the store was targeting.
8167 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8168 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8169 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8170 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8171 }
8172
8173 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8174 if (!SN->isTruncatingStore() &&
8175 Op1.getOpcode() == ISD::BSWAP &&
8176 Op1.getNode()->hasOneUse() &&
8177 canLoadStoreByteSwapped(Op1.getValueType())) {
8178
8179 SDValue BSwapOp = Op1.getOperand(0);
8180
8181 if (BSwapOp.getValueType() == MVT::i16)
8182 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8183
8184 SDValue Ops[] = {
8185 N->getOperand(0), BSwapOp, N->getOperand(2)
8186 };
8187
8188 return
8189 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8190 Ops, MemVT, SN->getMemOperand());
8191 }
8192 // Combine STORE (element-swap) into VSTER
8193 if (!SN->isTruncatingStore() &&
8194 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8195 Op1.getNode()->hasOneUse() &&
8196 Subtarget.hasVectorEnhancements2()) {
8197 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8198 ArrayRef<int> ShuffleMask = SVN->getMask();
8199 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8200 SDValue Ops[] = {
8201 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8202 };
8203
8204 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8205 DAG.getVTList(MVT::Other),
8206 Ops, MemVT, SN->getMemOperand());
8207 }
8208 }
8209
8210 // Combine STORE (READCYCLECOUNTER) into STCKF.
8211 if (!SN->isTruncatingStore() &&
8213 Op1.hasOneUse() &&
8214 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8215 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8216 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8217 DAG.getVTList(MVT::Other),
8218 Ops, MemVT, SN->getMemOperand());
8219 }
8220
8221 // Transform a store of a 128-bit value moved from parts into two stores.
8222 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8223 SDValue LoPart, HiPart;
8224 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8225 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8226 SDLoc DL(SN);
8227 SDValue Chain0 = DAG.getStore(
8228 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8229 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8230 SDValue Chain1 = DAG.getStore(
8231 SN->getChain(), DL, LoPart,
8232 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8233 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8234 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8235
8236 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8237 }
8238 }
8239
8240 // Replicate a reg or immediate with VREP instead of scalar multiply or
8241 // immediate load. It seems best to do this during the first DAGCombine as
8242 // it is straight-forward to handle the zero-extend node in the initial
8243 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8244 // extracting an i16 element from a v16i8 vector).
8245 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8246 isOnlyUsedByStores(Op1, DAG)) {
8247 SDValue Word = SDValue();
8248 EVT WordVT;
8249
8250 // Find a replicated immediate and return it if found in Word and its
8251 // type in WordVT.
8252 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8253 // Some constants are better handled with a scalar store.
8254 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8255 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8256 return;
8257
8258 APInt Val = C->getAPIntValue();
8259 // Truncate Val in case of a truncating store.
8260 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8261 assert(SN->isTruncatingStore() &&
8262 "Non-truncating store and immediate value does not fit?");
8263 Val = Val.trunc(TotBytes * 8);
8264 }
8265
8266 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8267 if (VCI.isVectorConstantLegal(Subtarget) &&
8268 VCI.Opcode == SystemZISD::REPLICATE) {
8269 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8270 WordVT = VCI.VecVT.getScalarType();
8271 }
8272 };
8273
8274 // Find a replicated register and return it if found in Word and its type
8275 // in WordVT.
8276 auto FindReplicatedReg = [&](SDValue MulOp) {
8277 EVT MulVT = MulOp.getValueType();
8278 if (MulOp->getOpcode() == ISD::MUL &&
8279 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8280 // Find a zero extended value and its type.
8281 SDValue LHS = MulOp->getOperand(0);
8282 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8283 WordVT = LHS->getOperand(0).getValueType();
8284 else if (LHS->getOpcode() == ISD::AssertZext)
8285 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8286 else
8287 return;
8288 // Find a replicating constant, e.g. 0x00010001.
8289 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8290 SystemZVectorConstantInfo VCI(
8291 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8292 if (VCI.isVectorConstantLegal(Subtarget) &&
8293 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8294 WordVT == VCI.VecVT.getScalarType())
8295 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8296 }
8297 }
8298 };
8299
8300 if (isa<BuildVectorSDNode>(Op1) &&
8301 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8302 SDValue SplatVal = Op1->getOperand(0);
8303 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8304 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8305 else
8306 FindReplicatedReg(SplatVal);
8307 } else {
8308 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8309 FindReplicatedImm(C, MemVT.getStoreSize());
8310 else
8311 FindReplicatedReg(Op1);
8312 }
8313
8314 if (Word != SDValue()) {
8315 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8316 "Bad type handling");
8317 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8318 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8319 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8320 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8321 SN->getBasePtr(), SN->getMemOperand());
8322 }
8323 }
8324
8325 return SDValue();
8326}
8327
8328SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8329 SDNode *N, DAGCombinerInfo &DCI) const {
8330 SelectionDAG &DAG = DCI.DAG;
8331 // Combine element-swap (LOAD) into VLER
8332 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8333 N->getOperand(0).hasOneUse() &&
8334 Subtarget.hasVectorEnhancements2()) {
8335 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8336 ArrayRef<int> ShuffleMask = SVN->getMask();
8337 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8338 SDValue Load = N->getOperand(0);
8339 LoadSDNode *LD = cast<LoadSDNode>(Load);
8340
8341 // Create the element-swapping load.
8342 SDValue Ops[] = {
8343 LD->getChain(), // Chain
8344 LD->getBasePtr() // Ptr
8345 };
8346 SDValue ESLoad =
8347 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8348 DAG.getVTList(LD->getValueType(0), MVT::Other),
8349 Ops, LD->getMemoryVT(), LD->getMemOperand());
8350
8351 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8352 // by the load dead.
8353 DCI.CombineTo(N, ESLoad);
8354
8355 // Next, combine the load away, we give it a bogus result value but a real
8356 // chain result. The result value is dead because the shuffle is dead.
8357 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8358
8359 // Return N so it doesn't get rechecked!
8360 return SDValue(N, 0);
8361 }
8362 }
8363
8364 return SDValue();
8365}
8366
8367SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8368 SDNode *N, DAGCombinerInfo &DCI) const {
8369 SelectionDAG &DAG = DCI.DAG;
8370
8371 if (!Subtarget.hasVector())
8372 return SDValue();
8373
8374 // Look through bitcasts that retain the number of vector elements.
8375 SDValue Op = N->getOperand(0);
8376 if (Op.getOpcode() == ISD::BITCAST &&
8377 Op.getValueType().isVector() &&
8378 Op.getOperand(0).getValueType().isVector() &&
8379 Op.getValueType().getVectorNumElements() ==
8380 Op.getOperand(0).getValueType().getVectorNumElements())
8381 Op = Op.getOperand(0);
8382
8383 // Pull BSWAP out of a vector extraction.
8384 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8385 EVT VecVT = Op.getValueType();
8386 EVT EltVT = VecVT.getVectorElementType();
8387 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8388 Op.getOperand(0), N->getOperand(1));
8389 DCI.AddToWorklist(Op.getNode());
8390 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8391 if (EltVT != N->getValueType(0)) {
8392 DCI.AddToWorklist(Op.getNode());
8393 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8394 }
8395 return Op;
8396 }
8397
8398 // Try to simplify a vector extraction.
8399 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8400 SDValue Op0 = N->getOperand(0);
8401 EVT VecVT = Op0.getValueType();
8402 if (canTreatAsByteVector(VecVT))
8403 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8404 IndexN->getZExtValue(), DCI, false);
8405 }
8406 return SDValue();
8407}
8408
8409SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8410 SDNode *N, DAGCombinerInfo &DCI) const {
8411 SelectionDAG &DAG = DCI.DAG;
8412 // (join_dwords X, X) == (replicate X)
8413 if (N->getOperand(0) == N->getOperand(1))
8414 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8415 N->getOperand(0));
8416 return SDValue();
8417}
8418
8420 SDValue Chain1 = N1->getOperand(0);
8421 SDValue Chain2 = N2->getOperand(0);
8422
8423 // Trivial case: both nodes take the same chain.
8424 if (Chain1 == Chain2)
8425 return Chain1;
8426
8427 // FIXME - we could handle more complex cases via TokenFactor,
8428 // assuming we can verify that this would not create a cycle.
8429 return SDValue();
8430}
8431
8432SDValue SystemZTargetLowering::combineFP_ROUND(
8433 SDNode *N, DAGCombinerInfo &DCI) const {
8434
8435 if (!Subtarget.hasVector())
8436 return SDValue();
8437
8438 // (fpround (extract_vector_elt X 0))
8439 // (fpround (extract_vector_elt X 1)) ->
8440 // (extract_vector_elt (VROUND X) 0)
8441 // (extract_vector_elt (VROUND X) 2)
8442 //
8443 // This is a special case since the target doesn't really support v2f32s.
8444 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8445 SelectionDAG &DAG = DCI.DAG;
8446 SDValue Op0 = N->getOperand(OpNo);
8447 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8449 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8450 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8451 Op0.getConstantOperandVal(1) == 0) {
8452 SDValue Vec = Op0.getOperand(0);
8453 for (auto *U : Vec->users()) {
8454 if (U != Op0.getNode() && U->hasOneUse() &&
8455 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8456 U->getOperand(0) == Vec &&
8457 U->getOperand(1).getOpcode() == ISD::Constant &&
8458 U->getConstantOperandVal(1) == 1) {
8459 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8460 if (OtherRound.getOpcode() == N->getOpcode() &&
8461 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8462 OtherRound.getValueType() == MVT::f32) {
8463 SDValue VRound, Chain;
8464 if (N->isStrictFPOpcode()) {
8465 Chain = MergeInputChains(N, OtherRound.getNode());
8466 if (!Chain)
8467 continue;
8468 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8469 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8470 Chain = VRound.getValue(1);
8471 } else
8472 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8473 MVT::v4f32, Vec);
8474 DCI.AddToWorklist(VRound.getNode());
8475 SDValue Extract1 =
8476 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8477 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8478 DCI.AddToWorklist(Extract1.getNode());
8479 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8480 if (Chain)
8481 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8482 SDValue Extract0 =
8483 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8484 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8485 if (Chain)
8486 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8487 N->getVTList(), Extract0, Chain);
8488 return Extract0;
8489 }
8490 }
8491 }
8492 }
8493 return SDValue();
8494}
8495
8496SDValue SystemZTargetLowering::combineFP_EXTEND(
8497 SDNode *N, DAGCombinerInfo &DCI) const {
8498
8499 if (!Subtarget.hasVector())
8500 return SDValue();
8501
8502 // (fpextend (extract_vector_elt X 0))
8503 // (fpextend (extract_vector_elt X 2)) ->
8504 // (extract_vector_elt (VEXTEND X) 0)
8505 // (extract_vector_elt (VEXTEND X) 1)
8506 //
8507 // This is a special case since the target doesn't really support v2f32s.
8508 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8509 SelectionDAG &DAG = DCI.DAG;
8510 SDValue Op0 = N->getOperand(OpNo);
8511 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8513 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8514 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8515 Op0.getConstantOperandVal(1) == 0) {
8516 SDValue Vec = Op0.getOperand(0);
8517 for (auto *U : Vec->users()) {
8518 if (U != Op0.getNode() && U->hasOneUse() &&
8519 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8520 U->getOperand(0) == Vec &&
8521 U->getOperand(1).getOpcode() == ISD::Constant &&
8522 U->getConstantOperandVal(1) == 2) {
8523 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8524 if (OtherExtend.getOpcode() == N->getOpcode() &&
8525 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8526 OtherExtend.getValueType() == MVT::f64) {
8527 SDValue VExtend, Chain;
8528 if (N->isStrictFPOpcode()) {
8529 Chain = MergeInputChains(N, OtherExtend.getNode());
8530 if (!Chain)
8531 continue;
8532 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8533 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8534 Chain = VExtend.getValue(1);
8535 } else
8536 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8537 MVT::v2f64, Vec);
8538 DCI.AddToWorklist(VExtend.getNode());
8539 SDValue Extract1 =
8540 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8541 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8542 DCI.AddToWorklist(Extract1.getNode());
8543 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8544 if (Chain)
8545 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8546 SDValue Extract0 =
8547 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8548 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8549 if (Chain)
8550 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8551 N->getVTList(), Extract0, Chain);
8552 return Extract0;
8553 }
8554 }
8555 }
8556 }
8557 return SDValue();
8558}
8559
8560SDValue SystemZTargetLowering::combineINT_TO_FP(
8561 SDNode *N, DAGCombinerInfo &DCI) const {
8562 if (DCI.Level != BeforeLegalizeTypes)
8563 return SDValue();
8564 SelectionDAG &DAG = DCI.DAG;
8565 LLVMContext &Ctx = *DAG.getContext();
8566 unsigned Opcode = N->getOpcode();
8567 EVT OutVT = N->getValueType(0);
8568 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8569 SDValue Op = N->getOperand(0);
8570 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8571 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8572
8573 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8574 // v2f64 = uint_to_fp v2i16
8575 // =>
8576 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8577 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8578 OutScalarBits <= 64) {
8579 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8580 EVT ExtVT = EVT::getVectorVT(
8581 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8582 unsigned ExtOpcode =
8584 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8585 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8586 }
8587 return SDValue();
8588}
8589
8590SDValue SystemZTargetLowering::combineFCOPYSIGN(
8591 SDNode *N, DAGCombinerInfo &DCI) const {
8592 SelectionDAG &DAG = DCI.DAG;
8593 EVT VT = N->getValueType(0);
8594 SDValue ValOp = N->getOperand(0);
8595 SDValue SignOp = N->getOperand(1);
8596
8597 // Remove the rounding which is not needed.
8598 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8599 SDValue WideOp = SignOp.getOperand(0);
8600 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8601 }
8602
8603 return SDValue();
8604}
8605
8606SDValue SystemZTargetLowering::combineBSWAP(
8607 SDNode *N, DAGCombinerInfo &DCI) const {
8608 SelectionDAG &DAG = DCI.DAG;
8609 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8610 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8611 N->getOperand(0).hasOneUse() &&
8612 canLoadStoreByteSwapped(N->getValueType(0))) {
8613 SDValue Load = N->getOperand(0);
8614 LoadSDNode *LD = cast<LoadSDNode>(Load);
8615
8616 // Create the byte-swapping load.
8617 SDValue Ops[] = {
8618 LD->getChain(), // Chain
8619 LD->getBasePtr() // Ptr
8620 };
8621 EVT LoadVT = N->getValueType(0);
8622 if (LoadVT == MVT::i16)
8623 LoadVT = MVT::i32;
8624 SDValue BSLoad =
8625 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8626 DAG.getVTList(LoadVT, MVT::Other),
8627 Ops, LD->getMemoryVT(), LD->getMemOperand());
8628
8629 // If this is an i16 load, insert the truncate.
8630 SDValue ResVal = BSLoad;
8631 if (N->getValueType(0) == MVT::i16)
8632 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8633
8634 // First, combine the bswap away. This makes the value produced by the
8635 // load dead.
8636 DCI.CombineTo(N, ResVal);
8637
8638 // Next, combine the load away, we give it a bogus result value but a real
8639 // chain result. The result value is dead because the bswap is dead.
8640 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8641
8642 // Return N so it doesn't get rechecked!
8643 return SDValue(N, 0);
8644 }
8645
8646 // Look through bitcasts that retain the number of vector elements.
8647 SDValue Op = N->getOperand(0);
8648 if (Op.getOpcode() == ISD::BITCAST &&
8649 Op.getValueType().isVector() &&
8650 Op.getOperand(0).getValueType().isVector() &&
8651 Op.getValueType().getVectorNumElements() ==
8652 Op.getOperand(0).getValueType().getVectorNumElements())
8653 Op = Op.getOperand(0);
8654
8655 // Push BSWAP into a vector insertion if at least one side then simplifies.
8656 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8657 SDValue Vec = Op.getOperand(0);
8658 SDValue Elt = Op.getOperand(1);
8659 SDValue Idx = Op.getOperand(2);
8660
8662 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8664 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8665 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8666 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8667 EVT VecVT = N->getValueType(0);
8668 EVT EltVT = N->getValueType(0).getVectorElementType();
8669 if (VecVT != Vec.getValueType()) {
8670 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8671 DCI.AddToWorklist(Vec.getNode());
8672 }
8673 if (EltVT != Elt.getValueType()) {
8674 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8675 DCI.AddToWorklist(Elt.getNode());
8676 }
8677 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8678 DCI.AddToWorklist(Vec.getNode());
8679 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8680 DCI.AddToWorklist(Elt.getNode());
8681 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8682 Vec, Elt, Idx);
8683 }
8684 }
8685
8686 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8687 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8688 if (SV && Op.hasOneUse()) {
8689 SDValue Op0 = Op.getOperand(0);
8690 SDValue Op1 = Op.getOperand(1);
8691
8693 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8695 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8696 EVT VecVT = N->getValueType(0);
8697 if (VecVT != Op0.getValueType()) {
8698 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8699 DCI.AddToWorklist(Op0.getNode());
8700 }
8701 if (VecVT != Op1.getValueType()) {
8702 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8703 DCI.AddToWorklist(Op1.getNode());
8704 }
8705 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8706 DCI.AddToWorklist(Op0.getNode());
8707 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8708 DCI.AddToWorklist(Op1.getNode());
8709 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8710 }
8711 }
8712
8713 return SDValue();
8714}
8715
8716SDValue SystemZTargetLowering::combineSETCC(
8717 SDNode *N, DAGCombinerInfo &DCI) const {
8718 SelectionDAG &DAG = DCI.DAG;
8719 const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
8720 const SDValue LHS = N->getOperand(0);
8721 const SDValue RHS = N->getOperand(1);
8722 bool CmpNull = isNullConstant(RHS);
8723 bool CmpAllOnes = isAllOnesConstant(RHS);
8724 EVT VT = N->getValueType(0);
8725 SDLoc DL(N);
8726
8727 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8728 // change the outer compare to a i128 compare. This will normally
8729 // allow the reduction to be recognized in adjustICmp128, and even if
8730 // not, the i128 compare will still generate better code.
8731 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8733 if (Src.getOpcode() == ISD::SETCC &&
8734 Src.getValueType().isFixedLengthVector() &&
8735 Src.getValueType().getScalarType() == MVT::i1) {
8736 EVT CmpVT = Src.getOperand(0).getValueType();
8737 if (CmpVT.getSizeInBits() == 128) {
8738 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8739 SDValue LHS =
8740 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8741 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8742 : DAG.getAllOnesConstant(DL, MVT::i128);
8743 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8744 N->getFlags());
8745 }
8746 }
8747 }
8748
8749 return SDValue();
8750}
8751
8752static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8753 unsigned Depth = 0) {
8754 // Limit depth of potentially exponential walk.
8755 if (Depth > 5)
8756 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8757
8758 switch (Val.getOpcode()) {
8759 default:
8760 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8761 case SystemZISD::IPM:
8762 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8763 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8764 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8765 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8766 case SystemZISD::SELECT_CCMASK: {
8767 SDValue Op4CCReg = Val.getOperand(4);
8768 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8769 Op4CCReg.getOpcode() == SystemZISD::TM) {
8770 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8771 if (OpCC != SDValue())
8772 return std::make_pair(OpCC, OpCCValid);
8773 }
8774 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8775 if (!CCValid)
8776 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8777 int CCValidVal = CCValid->getZExtValue();
8778 return std::make_pair(Op4CCReg, CCValidVal);
8779 }
8780 case ISD::ADD:
8781 case ISD::AND:
8782 case ISD::OR:
8783 case ISD::XOR:
8784 case ISD::SHL:
8785 case ISD::SRA:
8786 case ISD::SRL:
8787 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
8788 if (Op0CC != SDValue())
8789 return std::make_pair(Op0CC, Op0CCValid);
8790 return findCCUse(Val.getOperand(1), Depth + 1);
8791 }
8792}
8793
8794static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8795 SelectionDAG &DAG);
8796
8798 SelectionDAG &DAG) {
8799 SDLoc DL(Val);
8800 auto Opcode = Val.getOpcode();
8801 switch (Opcode) {
8802 default:
8803 return {};
8804 case ISD::Constant:
8805 return {Val, Val, Val, Val};
8806 case SystemZISD::IPM: {
8807 SDValue IPMOp0 = Val.getOperand(0);
8808 if (IPMOp0 != CC)
8809 return {};
8810 SmallVector<SDValue, 4> ShiftedCCVals;
8811 for (auto CC : {0, 1, 2, 3})
8812 ShiftedCCVals.emplace_back(
8813 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
8814 return ShiftedCCVals;
8815 }
8816 case SystemZISD::SELECT_CCMASK: {
8817 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
8818 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8819 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
8820 if (!CCValid || !CCMask)
8821 return {};
8822
8823 int CCValidVal = CCValid->getZExtValue();
8824 int CCMaskVal = CCMask->getZExtValue();
8825 // Pruning search tree early - Moving CC test and combineCCMask ahead of
8826 // recursive call to simplifyAssumingCCVal.
8827 SDValue Op4CCReg = Val.getOperand(4);
8828 if (Op4CCReg != CC)
8829 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
8830 if (Op4CCReg != CC)
8831 return {};
8832 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
8833 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
8834 if (TrueSDVals.empty() || FalseSDVals.empty())
8835 return {};
8836 SmallVector<SDValue, 4> MergedSDVals;
8837 for (auto &CCVal : {0, 1, 2, 3})
8838 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
8839 ? TrueSDVals[CCVal]
8840 : FalseSDVals[CCVal]);
8841 return MergedSDVals;
8842 }
8843 case ISD::ADD:
8844 case ISD::AND:
8845 case ISD::OR:
8846 case ISD::XOR:
8847 case ISD::SRA:
8848 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
8849 // would clobber CC).
8850 if (!Val.hasOneUse())
8851 return {};
8852 [[fallthrough]];
8853 case ISD::SHL:
8854 case ISD::SRL:
8855 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
8856 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
8857 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
8858 if (Op0SDVals.empty() || Op1SDVals.empty())
8859 return {};
8860 SmallVector<SDValue, 4> BinaryOpSDVals;
8861 for (auto CCVal : {0, 1, 2, 3})
8862 BinaryOpSDVals.emplace_back(DAG.getNode(
8863 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
8864 return BinaryOpSDVals;
8865 }
8866}
8867
8868static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8869 SelectionDAG &DAG) {
8870 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
8871 // set by the CCReg instruction using the CCValid / CCMask masks,
8872 // If the CCReg instruction is itself a ICMP / TM testing the condition
8873 // code set by some other instruction, see whether we can directly
8874 // use that condition code.
8875 auto *CCNode = CCReg.getNode();
8876 if (!CCNode)
8877 return false;
8878
8879 if (CCNode->getOpcode() == SystemZISD::TM) {
8880 if (CCValid != SystemZ::CCMASK_TM)
8881 return false;
8882 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
8883 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8884 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8885 if (!Op0Node || !Op1Node)
8886 return -1;
8887 auto Op0APVal = Op0Node->getAPIntValue();
8888 auto Op1APVal = Op1Node->getAPIntValue();
8889 auto Result = Op0APVal & Op1APVal;
8890 bool AllOnes = Result == Op1APVal;
8891 bool AllZeros = Result == 0;
8892 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
8893 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
8894 };
8895 SDValue Op0 = CCNode->getOperand(0);
8896 SDValue Op1 = CCNode->getOperand(1);
8897 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
8898 if (Op0CC == SDValue())
8899 return false;
8900 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
8901 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
8902 if (Op0SDVals.empty() || Op1SDVals.empty())
8903 return false;
8904 int NewCCMask = 0;
8905 for (auto CC : {0, 1, 2, 3}) {
8906 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
8907 if (CCVal < 0)
8908 return false;
8909 NewCCMask <<= 1;
8910 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
8911 }
8912 NewCCMask &= Op0CCValid;
8913 CCReg = Op0CC;
8914 CCMask = NewCCMask;
8915 CCValid = Op0CCValid;
8916 return true;
8917 }
8918 if (CCNode->getOpcode() != SystemZISD::ICMP ||
8919 CCValid != SystemZ::CCMASK_ICMP)
8920 return false;
8921
8922 SDValue CmpOp0 = CCNode->getOperand(0);
8923 SDValue CmpOp1 = CCNode->getOperand(1);
8924 SDValue CmpOp2 = CCNode->getOperand(2);
8925 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
8926 if (Op0CC != SDValue()) {
8927 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
8928 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
8929 if (Op0SDVals.empty() || Op1SDVals.empty())
8930 return false;
8931
8932 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
8933 auto CmpTypeVal = CmpType->getZExtValue();
8934 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
8935 const SDValue &Op1Val) {
8936 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8937 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8938 if (!Op0Node || !Op1Node)
8939 return -1;
8940 auto Op0APVal = Op0Node->getAPIntValue();
8941 auto Op1APVal = Op1Node->getAPIntValue();
8942 if (CmpTypeVal == SystemZICMP::SignedOnly)
8943 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
8944 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
8945 };
8946 int NewCCMask = 0;
8947 for (auto CC : {0, 1, 2, 3}) {
8948 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
8949 if (CCVal < 0)
8950 return false;
8951 NewCCMask <<= 1;
8952 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
8953 }
8954 NewCCMask &= Op0CCValid;
8955 CCMask = NewCCMask;
8956 CCReg = Op0CC;
8957 CCValid = Op0CCValid;
8958 return true;
8959 }
8960
8961 return false;
8962}
8963
8964// Merging versus split in multiple branches cost.
8967 const Value *Lhs,
8968 const Value *Rhs,
8969 const Function *) const {
8970 const auto isFlagOutOpCC = [](const Value *V) {
8971 using namespace llvm::PatternMatch;
8972 const Value *RHSVal;
8973 const APInt *RHSC;
8974 if (const auto *I = dyn_cast<Instruction>(V)) {
8975 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
8976 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
8977 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
8978 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
8979 if (CB->isInlineAsm()) {
8980 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
8981 return IA && IA->getConstraintString().contains("{@cc}");
8982 }
8983 }
8984 }
8985 }
8986 return false;
8987 };
8988 // Pattern (ICmp %asm) or (ICmp (And %asm)).
8989 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
8990 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
8991 // conditionals will be merged or else conditionals will be split.
8992 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
8993 return {3, 0, -1};
8994 // Default.
8995 return {-1, -1, -1};
8996}
8997
8998SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
8999 DAGCombinerInfo &DCI) const {
9000 SelectionDAG &DAG = DCI.DAG;
9001
9002 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9003 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9004 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9005 if (!CCValid || !CCMask)
9006 return SDValue();
9007
9008 int CCValidVal = CCValid->getZExtValue();
9009 int CCMaskVal = CCMask->getZExtValue();
9010 SDValue Chain = N->getOperand(0);
9011 SDValue CCReg = N->getOperand(4);
9012 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9013 // the modified BR_CCMASK with the new values.
9014 // In order to avoid conditional branches with full or empty cc masks, do not
9015 // do this if ccmask is 0 or equal to ccvalid.
9016 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9017 CCMaskVal != CCValidVal)
9018 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9019 Chain,
9020 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9021 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9022 N->getOperand(3), CCReg);
9023 return SDValue();
9024}
9025
9026SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9027 SDNode *N, DAGCombinerInfo &DCI) const {
9028 SelectionDAG &DAG = DCI.DAG;
9029
9030 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9031 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9032 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9033 if (!CCValid || !CCMask)
9034 return SDValue();
9035
9036 int CCValidVal = CCValid->getZExtValue();
9037 int CCMaskVal = CCMask->getZExtValue();
9038 SDValue CCReg = N->getOperand(4);
9039
9040 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9041
9042 // Populate SDVals vector for each condition code ccval for given Val, which
9043 // can again be another nested select_ccmask with the same CC.
9044 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9045 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9047 if (Val.getOperand(4) != CCReg)
9048 return SmallVector<SDValue, 4>{};
9049 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9050 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9051 if (!CCMask)
9052 return SmallVector<SDValue, 4>{};
9053
9054 int CCMaskVal = CCMask->getZExtValue();
9055 for (auto &CC : {0, 1, 2, 3})
9056 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9057 : FalseVal);
9058 return Res;
9059 }
9060 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9061 };
9062 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9063 // with CCReg found by combineCCMask or original CCReg.
9064 SDValue TrueVal = N->getOperand(0);
9065 SDValue FalseVal = N->getOperand(1);
9066 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9067 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9068 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9069 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9070 if (TrueSDVals.empty())
9071 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9072 if (FalseSDVals.empty())
9073 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9074 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9075 SmallSet<SDValue, 4> MergedSDValsSet;
9076 // Ignoring CC values outside CCValiid.
9077 for (auto CC : {0, 1, 2, 3}) {
9078 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9079 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9080 ? TrueSDVals[CC]
9081 : FalseSDVals[CC]);
9082 }
9083 if (MergedSDValsSet.size() == 1)
9084 return *MergedSDValsSet.begin();
9085 if (MergedSDValsSet.size() == 2) {
9086 auto BeginIt = MergedSDValsSet.begin();
9087 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9088 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9089 std::swap(NewTrueVal, NewFalseVal);
9090 int NewCCMask = 0;
9091 for (auto CC : {0, 1, 2, 3}) {
9092 NewCCMask <<= 1;
9093 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9094 ? (TrueSDVals[CC] == NewTrueVal)
9095 : (FalseSDVals[CC] == NewTrueVal);
9096 }
9097 CCMaskVal = NewCCMask;
9098 CCMaskVal &= CCValidVal;
9099 TrueVal = NewTrueVal;
9100 FalseVal = NewFalseVal;
9101 IsCombinedCCReg = true;
9102 }
9103 }
9104 // If the condition is trivially false or trivially true after
9105 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9106 // (possibly modified by constructCCSDValsFromSELECT).
9107 if (CCMaskVal == 0)
9108 return FalseVal;
9109 if (CCMaskVal == CCValidVal)
9110 return TrueVal;
9111
9112 if (IsCombinedCCReg)
9113 return DAG.getNode(
9114 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9115 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9116 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9117
9118 return SDValue();
9119}
9120
9121SDValue SystemZTargetLowering::combineGET_CCMASK(
9122 SDNode *N, DAGCombinerInfo &DCI) const {
9123
9124 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9125 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9126 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9127 if (!CCValid || !CCMask)
9128 return SDValue();
9129 int CCValidVal = CCValid->getZExtValue();
9130 int CCMaskVal = CCMask->getZExtValue();
9131
9132 SDValue Select = N->getOperand(0);
9133 if (Select->getOpcode() == ISD::TRUNCATE)
9134 Select = Select->getOperand(0);
9135 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9136 return SDValue();
9137
9138 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9139 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9140 if (!SelectCCValid || !SelectCCMask)
9141 return SDValue();
9142 int SelectCCValidVal = SelectCCValid->getZExtValue();
9143 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9144
9145 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9146 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9147 if (!TrueVal || !FalseVal)
9148 return SDValue();
9149 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9150 ;
9151 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9152 SelectCCMaskVal ^= SelectCCValidVal;
9153 else
9154 return SDValue();
9155
9156 if (SelectCCValidVal & ~CCValidVal)
9157 return SDValue();
9158 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9159 return SDValue();
9160
9161 return Select->getOperand(4);
9162}
9163
9164SDValue SystemZTargetLowering::combineIntDIVREM(
9165 SDNode *N, DAGCombinerInfo &DCI) const {
9166 SelectionDAG &DAG = DCI.DAG;
9167 EVT VT = N->getValueType(0);
9168 // In the case where the divisor is a vector of constants a cheaper
9169 // sequence of instructions can replace the divide. BuildSDIV is called to
9170 // do this during DAG combining, but it only succeeds when it can build a
9171 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9172 // since it is not Legal but Custom it can only happen before
9173 // legalization. Therefore we must scalarize this early before Combine
9174 // 1. For widened vectors, this is already the result of type legalization.
9175 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9176 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9177 return DAG.UnrollVectorOp(N);
9178 return SDValue();
9179}
9180
9181
9182// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9183// This is closely modeled after the common-code combineShiftToMULH.
9184SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9185 SDNode *N, DAGCombinerInfo &DCI) const {
9186 SelectionDAG &DAG = DCI.DAG;
9187 SDLoc DL(N);
9188
9189 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9190 "SRL or SRA node is required here!");
9191
9192 if (!Subtarget.hasVector())
9193 return SDValue();
9194
9195 // Check the shift amount. Proceed with the transformation if the shift
9196 // amount is constant.
9197 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9198 if (!ShiftAmtSrc)
9199 return SDValue();
9200
9201 // The operation feeding into the shift must be an add.
9202 SDValue ShiftOperand = N->getOperand(0);
9203 if (ShiftOperand.getOpcode() != ISD::ADD)
9204 return SDValue();
9205
9206 // One operand of the add must be a multiply.
9207 SDValue MulOp = ShiftOperand.getOperand(0);
9208 SDValue AddOp = ShiftOperand.getOperand(1);
9209 if (MulOp.getOpcode() != ISD::MUL) {
9210 if (AddOp.getOpcode() != ISD::MUL)
9211 return SDValue();
9212 std::swap(MulOp, AddOp);
9213 }
9214
9215 // All operands must be equivalent extend nodes.
9216 SDValue LeftOp = MulOp.getOperand(0);
9217 SDValue RightOp = MulOp.getOperand(1);
9218
9219 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9220 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9221
9222 if (!IsSignExt && !IsZeroExt)
9223 return SDValue();
9224
9225 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9226 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9227
9228 SDValue MulhRightOp;
9229 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9230 unsigned ActiveBits = IsSignExt
9231 ? Constant->getAPIntValue().getSignificantBits()
9232 : Constant->getAPIntValue().getActiveBits();
9233 if (ActiveBits > NarrowVTSize)
9234 return SDValue();
9235 MulhRightOp = DAG.getConstant(
9236 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9237 NarrowVT);
9238 } else {
9239 if (LeftOp.getOpcode() != RightOp.getOpcode())
9240 return SDValue();
9241 // Check that the two extend nodes are the same type.
9242 if (NarrowVT != RightOp.getOperand(0).getValueType())
9243 return SDValue();
9244 MulhRightOp = RightOp.getOperand(0);
9245 }
9246
9247 SDValue MulhAddOp;
9248 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9249 unsigned ActiveBits = IsSignExt
9250 ? Constant->getAPIntValue().getSignificantBits()
9251 : Constant->getAPIntValue().getActiveBits();
9252 if (ActiveBits > NarrowVTSize)
9253 return SDValue();
9254 MulhAddOp = DAG.getConstant(
9255 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9256 NarrowVT);
9257 } else {
9258 if (LeftOp.getOpcode() != AddOp.getOpcode())
9259 return SDValue();
9260 // Check that the two extend nodes are the same type.
9261 if (NarrowVT != AddOp.getOperand(0).getValueType())
9262 return SDValue();
9263 MulhAddOp = AddOp.getOperand(0);
9264 }
9265
9266 EVT WideVT = LeftOp.getValueType();
9267 // Proceed with the transformation if the wide types match.
9268 assert((WideVT == RightOp.getValueType()) &&
9269 "Cannot have a multiply node with two different operand types.");
9270 assert((WideVT == AddOp.getValueType()) &&
9271 "Cannot have an add node with two different operand types.");
9272
9273 // Proceed with the transformation if the wide type is twice as large
9274 // as the narrow type.
9275 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9276 return SDValue();
9277
9278 // Check the shift amount with the narrow type size.
9279 // Proceed with the transformation if the shift amount is the width
9280 // of the narrow type.
9281 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9282 if (ShiftAmt != NarrowVTSize)
9283 return SDValue();
9284
9285 // Proceed if we support the multiply-and-add-high operation.
9286 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9287 NarrowVT == MVT::v4i32 ||
9288 (Subtarget.hasVectorEnhancements3() &&
9289 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9290 return SDValue();
9291
9292 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9293 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9294 DL, NarrowVT, LeftOp.getOperand(0),
9295 MulhRightOp, MulhAddOp);
9296 bool IsSigned = N->getOpcode() == ISD::SRA;
9297 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9298}
9299
9300// Op is an operand of a multiplication. Check whether this can be folded
9301// into an even/odd widening operation; if so, return the opcode to be used
9302// and update Op to the appropriate sub-operand. Note that the caller must
9303// verify that *both* operands of the multiplication support the operation.
9305 const SystemZSubtarget &Subtarget,
9306 SDValue &Op) {
9307 EVT VT = Op.getValueType();
9308
9309 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9310 // to selecting the even or odd vector elements.
9311 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9312 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9313 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9314 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9315 unsigned NumElts = VT.getVectorNumElements();
9316 Op = Op.getOperand(0);
9317 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9318 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9320 ArrayRef<int> ShuffleMask = SVN->getMask();
9321 bool CanUseEven = true, CanUseOdd = true;
9322 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9323 if (ShuffleMask[Elt] == -1)
9324 continue;
9325 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9326 CanUseEven = false;
9327 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9328 CanUseOdd = false;
9329 }
9330 Op = Op.getOperand(0);
9331 if (CanUseEven)
9332 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9333 if (CanUseOdd)
9334 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9335 }
9336 }
9337
9338 // For z17, we can also support the v2i64->i128 case, which looks like
9339 // (sign/zero_extend (extract_vector_elt X 0/1))
9340 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9341 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9342 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9343 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9344 Op = Op.getOperand(0);
9345 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9346 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9347 Op.getOperand(1).getOpcode() == ISD::Constant) {
9348 unsigned Elem = Op.getConstantOperandVal(1);
9349 Op = Op.getOperand(0);
9350 if (Elem == 0)
9351 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9352 if (Elem == 1)
9353 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9354 }
9355 }
9356
9357 return 0;
9358}
9359
9360SDValue SystemZTargetLowering::combineMUL(
9361 SDNode *N, DAGCombinerInfo &DCI) const {
9362 SelectionDAG &DAG = DCI.DAG;
9363
9364 // Detect even/odd widening multiplication.
9365 SDValue Op0 = N->getOperand(0);
9366 SDValue Op1 = N->getOperand(1);
9367 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9368 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9369 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9370 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9371
9372 return SDValue();
9373}
9374
9375SDValue SystemZTargetLowering::combineINTRINSIC(
9376 SDNode *N, DAGCombinerInfo &DCI) const {
9377 SelectionDAG &DAG = DCI.DAG;
9378
9379 unsigned Id = N->getConstantOperandVal(1);
9380 switch (Id) {
9381 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9382 // or larger is simply a vector load.
9383 case Intrinsic::s390_vll:
9384 case Intrinsic::s390_vlrl:
9385 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9386 if (C->getZExtValue() >= 15)
9387 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9388 N->getOperand(3), MachinePointerInfo());
9389 break;
9390 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9391 case Intrinsic::s390_vstl:
9392 case Intrinsic::s390_vstrl:
9393 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9394 if (C->getZExtValue() >= 15)
9395 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9396 N->getOperand(4), MachinePointerInfo());
9397 break;
9398 }
9399
9400 return SDValue();
9401}
9402
9403SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9404 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9405 return N->getOperand(0);
9406 return N;
9407}
9408
9410 DAGCombinerInfo &DCI) const {
9411 switch(N->getOpcode()) {
9412 default: break;
9413 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9414 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9415 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9416 case SystemZISD::MERGE_HIGH:
9417 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9418 case ISD::LOAD: return combineLOAD(N, DCI);
9419 case ISD::STORE: return combineSTORE(N, DCI);
9420 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9421 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9422 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9424 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9426 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9427 case ISD::SINT_TO_FP:
9428 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9429 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9430 case ISD::BSWAP: return combineBSWAP(N, DCI);
9431 case ISD::SETCC: return combineSETCC(N, DCI);
9432 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9433 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9434 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9435 case ISD::SRL:
9436 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9437 case ISD::MUL: return combineMUL(N, DCI);
9438 case ISD::SDIV:
9439 case ISD::UDIV:
9440 case ISD::SREM:
9441 case ISD::UREM: return combineIntDIVREM(N, DCI);
9443 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9444 }
9445
9446 return SDValue();
9447}
9448
9449// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9450// are for Op.
9451static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9452 unsigned OpNo) {
9453 EVT VT = Op.getValueType();
9454 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9455 APInt SrcDemE;
9456 unsigned Opcode = Op.getOpcode();
9457 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9458 unsigned Id = Op.getConstantOperandVal(0);
9459 switch (Id) {
9460 case Intrinsic::s390_vpksh: // PACKS
9461 case Intrinsic::s390_vpksf:
9462 case Intrinsic::s390_vpksg:
9463 case Intrinsic::s390_vpkshs: // PACKS_CC
9464 case Intrinsic::s390_vpksfs:
9465 case Intrinsic::s390_vpksgs:
9466 case Intrinsic::s390_vpklsh: // PACKLS
9467 case Intrinsic::s390_vpklsf:
9468 case Intrinsic::s390_vpklsg:
9469 case Intrinsic::s390_vpklshs: // PACKLS_CC
9470 case Intrinsic::s390_vpklsfs:
9471 case Intrinsic::s390_vpklsgs:
9472 // VECTOR PACK truncates the elements of two source vectors into one.
9473 SrcDemE = DemandedElts;
9474 if (OpNo == 2)
9475 SrcDemE.lshrInPlace(NumElts / 2);
9476 SrcDemE = SrcDemE.trunc(NumElts / 2);
9477 break;
9478 // VECTOR UNPACK extends half the elements of the source vector.
9479 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9480 case Intrinsic::s390_vuphh:
9481 case Intrinsic::s390_vuphf:
9482 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9483 case Intrinsic::s390_vuplhh:
9484 case Intrinsic::s390_vuplhf:
9485 SrcDemE = APInt(NumElts * 2, 0);
9486 SrcDemE.insertBits(DemandedElts, 0);
9487 break;
9488 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9489 case Intrinsic::s390_vuplhw:
9490 case Intrinsic::s390_vuplf:
9491 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9492 case Intrinsic::s390_vupllh:
9493 case Intrinsic::s390_vupllf:
9494 SrcDemE = APInt(NumElts * 2, 0);
9495 SrcDemE.insertBits(DemandedElts, NumElts);
9496 break;
9497 case Intrinsic::s390_vpdi: {
9498 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9499 SrcDemE = APInt(NumElts, 0);
9500 if (!DemandedElts[OpNo - 1])
9501 break;
9502 unsigned Mask = Op.getConstantOperandVal(3);
9503 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9504 // Demand input element 0 or 1, given by the mask bit value.
9505 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9506 break;
9507 }
9508 case Intrinsic::s390_vsldb: {
9509 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9510 assert(VT == MVT::v16i8 && "Unexpected type.");
9511 unsigned FirstIdx = Op.getConstantOperandVal(3);
9512 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9513 unsigned NumSrc0Els = 16 - FirstIdx;
9514 SrcDemE = APInt(NumElts, 0);
9515 if (OpNo == 1) {
9516 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9517 SrcDemE.insertBits(DemEls, FirstIdx);
9518 } else {
9519 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9520 SrcDemE.insertBits(DemEls, 0);
9521 }
9522 break;
9523 }
9524 case Intrinsic::s390_vperm:
9525 SrcDemE = APInt::getAllOnes(NumElts);
9526 break;
9527 default:
9528 llvm_unreachable("Unhandled intrinsic.");
9529 break;
9530 }
9531 } else {
9532 switch (Opcode) {
9533 case SystemZISD::JOIN_DWORDS:
9534 // Scalar operand.
9535 SrcDemE = APInt(1, 1);
9536 break;
9537 case SystemZISD::SELECT_CCMASK:
9538 SrcDemE = DemandedElts;
9539 break;
9540 default:
9541 llvm_unreachable("Unhandled opcode.");
9542 break;
9543 }
9544 }
9545 return SrcDemE;
9546}
9547
9549 const APInt &DemandedElts,
9550 const SelectionDAG &DAG, unsigned Depth,
9551 unsigned OpNo) {
9552 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9553 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9554 KnownBits LHSKnown =
9555 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9556 KnownBits RHSKnown =
9557 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9558 Known = LHSKnown.intersectWith(RHSKnown);
9559}
9560
9561void
9564 const APInt &DemandedElts,
9565 const SelectionDAG &DAG,
9566 unsigned Depth) const {
9567 Known.resetAll();
9568
9569 // Intrinsic CC result is returned in the two low bits.
9570 unsigned Tmp0, Tmp1; // not used
9571 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9572 Known.Zero.setBitsFrom(2);
9573 return;
9574 }
9575 EVT VT = Op.getValueType();
9576 if (Op.getResNo() != 0 || VT == MVT::Untyped)
9577 return;
9578 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9579 "KnownBits does not match VT in bitwidth");
9580 assert ((!VT.isVector() ||
9581 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9582 "DemandedElts does not match VT number of elements");
9583 unsigned BitWidth = Known.getBitWidth();
9584 unsigned Opcode = Op.getOpcode();
9585 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9586 bool IsLogical = false;
9587 unsigned Id = Op.getConstantOperandVal(0);
9588 switch (Id) {
9589 case Intrinsic::s390_vpksh: // PACKS
9590 case Intrinsic::s390_vpksf:
9591 case Intrinsic::s390_vpksg:
9592 case Intrinsic::s390_vpkshs: // PACKS_CC
9593 case Intrinsic::s390_vpksfs:
9594 case Intrinsic::s390_vpksgs:
9595 case Intrinsic::s390_vpklsh: // PACKLS
9596 case Intrinsic::s390_vpklsf:
9597 case Intrinsic::s390_vpklsg:
9598 case Intrinsic::s390_vpklshs: // PACKLS_CC
9599 case Intrinsic::s390_vpklsfs:
9600 case Intrinsic::s390_vpklsgs:
9601 case Intrinsic::s390_vpdi:
9602 case Intrinsic::s390_vsldb:
9603 case Intrinsic::s390_vperm:
9604 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9605 break;
9606 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9607 case Intrinsic::s390_vuplhh:
9608 case Intrinsic::s390_vuplhf:
9609 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9610 case Intrinsic::s390_vupllh:
9611 case Intrinsic::s390_vupllf:
9612 IsLogical = true;
9613 [[fallthrough]];
9614 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9615 case Intrinsic::s390_vuphh:
9616 case Intrinsic::s390_vuphf:
9617 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9618 case Intrinsic::s390_vuplhw:
9619 case Intrinsic::s390_vuplf: {
9620 SDValue SrcOp = Op.getOperand(1);
9621 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9622 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9623 if (IsLogical) {
9624 Known = Known.zext(BitWidth);
9625 } else
9626 Known = Known.sext(BitWidth);
9627 break;
9628 }
9629 default:
9630 break;
9631 }
9632 } else {
9633 switch (Opcode) {
9634 case SystemZISD::JOIN_DWORDS:
9635 case SystemZISD::SELECT_CCMASK:
9636 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9637 break;
9638 case SystemZISD::REPLICATE: {
9639 SDValue SrcOp = Op.getOperand(0);
9640 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9641 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9642 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9643 break;
9644 }
9645 default:
9646 break;
9647 }
9648 }
9649
9650 // Known has the width of the source operand(s). Adjust if needed to match
9651 // the passed bitwidth.
9652 if (Known.getBitWidth() != BitWidth)
9653 Known = Known.anyextOrTrunc(BitWidth);
9654}
9655
9656static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9657 const SelectionDAG &DAG, unsigned Depth,
9658 unsigned OpNo) {
9659 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9660 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9661 if (LHS == 1) return 1; // Early out.
9662 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9663 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9664 if (RHS == 1) return 1; // Early out.
9665 unsigned Common = std::min(LHS, RHS);
9666 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9667 EVT VT = Op.getValueType();
9668 unsigned VTBits = VT.getScalarSizeInBits();
9669 if (SrcBitWidth > VTBits) { // PACK
9670 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9671 if (Common > SrcExtraBits)
9672 return (Common - SrcExtraBits);
9673 return 1;
9674 }
9675 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9676 return Common;
9677}
9678
9679unsigned
9681 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9682 unsigned Depth) const {
9683 if (Op.getResNo() != 0)
9684 return 1;
9685 unsigned Opcode = Op.getOpcode();
9686 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9687 unsigned Id = Op.getConstantOperandVal(0);
9688 switch (Id) {
9689 case Intrinsic::s390_vpksh: // PACKS
9690 case Intrinsic::s390_vpksf:
9691 case Intrinsic::s390_vpksg:
9692 case Intrinsic::s390_vpkshs: // PACKS_CC
9693 case Intrinsic::s390_vpksfs:
9694 case Intrinsic::s390_vpksgs:
9695 case Intrinsic::s390_vpklsh: // PACKLS
9696 case Intrinsic::s390_vpklsf:
9697 case Intrinsic::s390_vpklsg:
9698 case Intrinsic::s390_vpklshs: // PACKLS_CC
9699 case Intrinsic::s390_vpklsfs:
9700 case Intrinsic::s390_vpklsgs:
9701 case Intrinsic::s390_vpdi:
9702 case Intrinsic::s390_vsldb:
9703 case Intrinsic::s390_vperm:
9704 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9705 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9706 case Intrinsic::s390_vuphh:
9707 case Intrinsic::s390_vuphf:
9708 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9709 case Intrinsic::s390_vuplhw:
9710 case Intrinsic::s390_vuplf: {
9711 SDValue PackedOp = Op.getOperand(1);
9712 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9713 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9714 EVT VT = Op.getValueType();
9715 unsigned VTBits = VT.getScalarSizeInBits();
9716 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9717 return Tmp;
9718 }
9719 default:
9720 break;
9721 }
9722 } else {
9723 switch (Opcode) {
9724 case SystemZISD::SELECT_CCMASK:
9725 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9726 default:
9727 break;
9728 }
9729 }
9730
9731 return 1;
9732}
9733
9735 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9736 UndefPoisonKind Kind, unsigned Depth) const {
9737 switch (Op->getOpcode()) {
9738 case SystemZISD::PCREL_WRAPPER:
9739 case SystemZISD::PCREL_OFFSET:
9740 return true;
9741 }
9742 return false;
9743}
9744
9745unsigned
9747 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9748 unsigned StackAlign = TFI->getStackAlignment();
9749 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9750 "Unexpected stack alignment");
9751 // The default stack probe size is 4096 if the function has no
9752 // stack-probe-size attribute.
9753 unsigned StackProbeSize =
9754 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9755 // Round down to the stack alignment.
9756 StackProbeSize &= ~(StackAlign - 1);
9757 return StackProbeSize ? StackProbeSize : StackAlign;
9758}
9759
9760//===----------------------------------------------------------------------===//
9761// Custom insertion
9762//===----------------------------------------------------------------------===//
9763
9764// Force base value Base into a register before MI. Return the register.
9766 const SystemZInstrInfo *TII) {
9767 MachineBasicBlock *MBB = MI.getParent();
9768 MachineFunction &MF = *MBB->getParent();
9769 MachineRegisterInfo &MRI = MF.getRegInfo();
9770
9771 if (Base.isReg()) {
9772 // Copy Base into a new virtual register to help register coalescing in
9773 // cases with multiple uses.
9774 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9775 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9776 .add(Base);
9777 return Reg;
9778 }
9779
9780 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9781 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
9782 .add(Base)
9783 .addImm(0)
9784 .addReg(0);
9785 return Reg;
9786}
9787
9788// The CC operand of MI might be missing a kill marker because there
9789// were multiple uses of CC, and ISel didn't know which to mark.
9790// Figure out whether MI should have had a kill marker.
9792 // Scan forward through BB for a use/def of CC.
9794 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
9795 const MachineInstr &MI = *miI;
9796 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
9797 return false;
9798 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
9799 break; // Should have kill-flag - update below.
9800 }
9801
9802 // If we hit the end of the block, check whether CC is live into a
9803 // successor.
9804 if (miI == MBB->end()) {
9805 for (const MachineBasicBlock *Succ : MBB->successors())
9806 if (Succ->isLiveIn(SystemZ::CC))
9807 return false;
9808 }
9809
9810 return true;
9811}
9812
9813// Return true if it is OK for this Select pseudo-opcode to be cascaded
9814// together with other Select pseudo-opcodes into a single basic-block with
9815// a conditional jump around it.
9817 switch (MI.getOpcode()) {
9818 case SystemZ::Select32:
9819 case SystemZ::Select64:
9820 case SystemZ::Select128:
9821 case SystemZ::SelectF32:
9822 case SystemZ::SelectF64:
9823 case SystemZ::SelectF128:
9824 case SystemZ::SelectVR32:
9825 case SystemZ::SelectVR64:
9826 case SystemZ::SelectVR128:
9827 return true;
9828
9829 default:
9830 return false;
9831 }
9832}
9833
9834// Helper function, which inserts PHI functions into SinkMBB:
9835// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
9836// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
9838 MachineBasicBlock *TrueMBB,
9839 MachineBasicBlock *FalseMBB,
9840 MachineBasicBlock *SinkMBB) {
9841 MachineFunction *MF = TrueMBB->getParent();
9843
9844 MachineInstr *FirstMI = Selects.front();
9845 unsigned CCValid = FirstMI->getOperand(3).getImm();
9846 unsigned CCMask = FirstMI->getOperand(4).getImm();
9847
9848 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
9849
9850 // As we are creating the PHIs, we have to be careful if there is more than
9851 // one. Later Selects may reference the results of earlier Selects, but later
9852 // PHIs have to reference the individual true/false inputs from earlier PHIs.
9853 // That also means that PHI construction must work forward from earlier to
9854 // later, and that the code must maintain a mapping from earlier PHI's
9855 // destination registers, and the registers that went into the PHI.
9857
9858 for (auto *MI : Selects) {
9859 Register DestReg = MI->getOperand(0).getReg();
9860 Register TrueReg = MI->getOperand(1).getReg();
9861 Register FalseReg = MI->getOperand(2).getReg();
9862
9863 // If this Select we are generating is the opposite condition from
9864 // the jump we generated, then we have to swap the operands for the
9865 // PHI that is going to be generated.
9866 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
9867 std::swap(TrueReg, FalseReg);
9868
9869 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
9870 TrueReg = It->second.first;
9871
9872 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
9873 FalseReg = It->second.second;
9874
9875 DebugLoc DL = MI->getDebugLoc();
9876 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
9877 .addReg(TrueReg).addMBB(TrueMBB)
9878 .addReg(FalseReg).addMBB(FalseMBB);
9879
9880 // Add this PHI to the rewrite table.
9881 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
9882 }
9883
9884 MF->getProperties().resetNoPHIs();
9885}
9886
9888SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
9889 MachineBasicBlock *BB) const {
9890 MachineFunction &MF = *BB->getParent();
9891 MachineFrameInfo &MFI = MF.getFrameInfo();
9892 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
9893 assert(TFL->hasReservedCallFrame(MF) &&
9894 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
9895 (void)TFL;
9896 // Get the MaxCallFrameSize value and erase MI since it serves no further
9897 // purpose as the call frame is statically reserved in the prolog. Set
9898 // AdjustsStack as MI is *not* mapped as a frame instruction.
9899 uint32_t NumBytes = MI.getOperand(0).getImm();
9900 if (NumBytes > MFI.getMaxCallFrameSize())
9901 MFI.setMaxCallFrameSize(NumBytes);
9902 MFI.setAdjustsStack(true);
9903
9904 MI.eraseFromParent();
9905 return BB;
9906}
9907
9908// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
9910SystemZTargetLowering::emitSelect(MachineInstr &MI,
9911 MachineBasicBlock *MBB) const {
9912 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
9913 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
9914
9915 unsigned CCValid = MI.getOperand(3).getImm();
9916 unsigned CCMask = MI.getOperand(4).getImm();
9917
9918 // If we have a sequence of Select* pseudo instructions using the
9919 // same condition code value, we want to expand all of them into
9920 // a single pair of basic blocks using the same condition.
9921 SmallVector<MachineInstr*, 8> Selects;
9922 SmallVector<MachineInstr*, 8> DbgValues;
9923 Selects.push_back(&MI);
9924 unsigned Count = 0;
9925 for (MachineInstr &NextMI : llvm::make_range(
9926 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
9927 if (isSelectPseudo(NextMI)) {
9928 assert(NextMI.getOperand(3).getImm() == CCValid &&
9929 "Bad CCValid operands since CC was not redefined.");
9930 if (NextMI.getOperand(4).getImm() == CCMask ||
9931 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
9932 Selects.push_back(&NextMI);
9933 continue;
9934 }
9935 break;
9936 }
9937 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
9938 NextMI.usesCustomInsertionHook())
9939 break;
9940 bool User = false;
9941 for (auto *SelMI : Selects)
9942 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
9943 User = true;
9944 break;
9945 }
9946 if (NextMI.isDebugInstr()) {
9947 if (User) {
9948 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
9949 DbgValues.push_back(&NextMI);
9950 }
9951 } else if (User || ++Count > 20)
9952 break;
9953 }
9954
9955 MachineInstr *LastMI = Selects.back();
9956 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
9957 checkCCKill(*LastMI, MBB));
9958 MachineBasicBlock *StartMBB = MBB;
9959 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
9960 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
9961
9962 // Unless CC was killed in the last Select instruction, mark it as
9963 // live-in to both FalseMBB and JoinMBB.
9964 if (!CCKilled) {
9965 FalseMBB->addLiveIn(SystemZ::CC);
9966 JoinMBB->addLiveIn(SystemZ::CC);
9967 }
9968
9969 // StartMBB:
9970 // BRC CCMask, JoinMBB
9971 // # fallthrough to FalseMBB
9972 MBB = StartMBB;
9973 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
9974 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
9975 MBB->addSuccessor(JoinMBB);
9976 MBB->addSuccessor(FalseMBB);
9977
9978 // FalseMBB:
9979 // # fallthrough to JoinMBB
9980 MBB = FalseMBB;
9981 MBB->addSuccessor(JoinMBB);
9982
9983 // JoinMBB:
9984 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
9985 // ...
9986 MBB = JoinMBB;
9987 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
9988 for (auto *SelMI : Selects)
9989 SelMI->eraseFromParent();
9990
9992 for (auto *DbgMI : DbgValues)
9993 MBB->splice(InsertPos, StartMBB, DbgMI);
9994
9995 return JoinMBB;
9996}
9997
9998// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
9999// StoreOpcode is the store to use and Invert says whether the store should
10000// happen when the condition is false rather than true. If a STORE ON
10001// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10002MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10004 unsigned StoreOpcode,
10005 unsigned STOCOpcode,
10006 bool Invert) const {
10007 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10008
10009 Register SrcReg = MI.getOperand(0).getReg();
10010 MachineOperand Base = MI.getOperand(1);
10011 int64_t Disp = MI.getOperand(2).getImm();
10012 Register IndexReg = MI.getOperand(3).getReg();
10013 unsigned CCValid = MI.getOperand(4).getImm();
10014 unsigned CCMask = MI.getOperand(5).getImm();
10015 DebugLoc DL = MI.getDebugLoc();
10016
10017 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10018
10019 // ISel pattern matching also adds a load memory operand of the same
10020 // address, so take special care to find the storing memory operand.
10021 MachineMemOperand *MMO = nullptr;
10022 for (auto *I : MI.memoperands())
10023 if (I->isStore()) {
10024 MMO = I;
10025 break;
10026 }
10027
10028 // Use STOCOpcode if possible. We could use different store patterns in
10029 // order to avoid matching the index register, but the performance trade-offs
10030 // might be more complicated in that case.
10031 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10032 if (Invert)
10033 CCMask ^= CCValid;
10034
10035 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10036 .addReg(SrcReg)
10037 .add(Base)
10038 .addImm(Disp)
10039 .addImm(CCValid)
10040 .addImm(CCMask)
10041 .addMemOperand(MMO);
10042
10043 MI.eraseFromParent();
10044 return MBB;
10045 }
10046
10047 // Get the condition needed to branch around the store.
10048 if (!Invert)
10049 CCMask ^= CCValid;
10050
10051 MachineBasicBlock *StartMBB = MBB;
10052 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10053 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10054
10055 // Unless CC was killed in the CondStore instruction, mark it as
10056 // live-in to both FalseMBB and JoinMBB.
10057 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10058 !checkCCKill(MI, JoinMBB)) {
10059 FalseMBB->addLiveIn(SystemZ::CC);
10060 JoinMBB->addLiveIn(SystemZ::CC);
10061 }
10062
10063 // StartMBB:
10064 // BRC CCMask, JoinMBB
10065 // # fallthrough to FalseMBB
10066 MBB = StartMBB;
10067 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10068 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10069 MBB->addSuccessor(JoinMBB);
10070 MBB->addSuccessor(FalseMBB);
10071
10072 // FalseMBB:
10073 // store %SrcReg, %Disp(%Index,%Base)
10074 // # fallthrough to JoinMBB
10075 MBB = FalseMBB;
10076 BuildMI(MBB, DL, TII->get(StoreOpcode))
10077 .addReg(SrcReg)
10078 .add(Base)
10079 .addImm(Disp)
10080 .addReg(IndexReg)
10081 .addMemOperand(MMO);
10082 MBB->addSuccessor(JoinMBB);
10083
10084 MI.eraseFromParent();
10085 return JoinMBB;
10086}
10087
10088// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10090SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10092 bool Unsigned) const {
10093 MachineFunction &MF = *MBB->getParent();
10094 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10095 MachineRegisterInfo &MRI = MF.getRegInfo();
10096
10097 // Synthetic instruction to compare 128-bit values.
10098 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10099 Register Op0 = MI.getOperand(0).getReg();
10100 Register Op1 = MI.getOperand(1).getReg();
10101
10102 MachineBasicBlock *StartMBB = MBB;
10103 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10104 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10105
10106 // StartMBB:
10107 //
10108 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10109 // Swap the inputs to get:
10110 // CC 1 if high(Op0) > high(Op1)
10111 // CC 2 if high(Op0) < high(Op1)
10112 // CC 0 if high(Op0) == high(Op1)
10113 //
10114 // If CC != 0, we'd done, so jump over the next instruction.
10115 //
10116 // VEC[L]G Op1, Op0
10117 // JNE JoinMBB
10118 // # fallthrough to HiEqMBB
10119 MBB = StartMBB;
10120 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10121 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10122 .addReg(Op1).addReg(Op0);
10123 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10125 MBB->addSuccessor(JoinMBB);
10126 MBB->addSuccessor(HiEqMBB);
10127
10128 // HiEqMBB:
10129 //
10130 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10131 // Since we already know the high parts are equal, the CC
10132 // result will only depend on the low parts:
10133 // CC 1 if low(Op0) > low(Op1)
10134 // CC 3 if low(Op0) <= low(Op1)
10135 //
10136 // VCHLGS Tmp, Op0, Op1
10137 // # fallthrough to JoinMBB
10138 MBB = HiEqMBB;
10139 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10140 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10141 .addReg(Op0).addReg(Op1);
10142 MBB->addSuccessor(JoinMBB);
10143
10144 // Mark CC as live-in to JoinMBB.
10145 JoinMBB->addLiveIn(SystemZ::CC);
10146
10147 MI.eraseFromParent();
10148 return JoinMBB;
10149}
10150
10151// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10152// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10153// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10154// whether the field should be inverted after performing BinOpcode (e.g. for
10155// NAND).
10156MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10157 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10158 bool Invert) const {
10159 MachineFunction &MF = *MBB->getParent();
10160 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10161 MachineRegisterInfo &MRI = MF.getRegInfo();
10162
10163 // Extract the operands. Base can be a register or a frame index.
10164 // Src2 can be a register or immediate.
10165 Register Dest = MI.getOperand(0).getReg();
10166 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10167 int64_t Disp = MI.getOperand(2).getImm();
10168 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10169 Register BitShift = MI.getOperand(4).getReg();
10170 Register NegBitShift = MI.getOperand(5).getReg();
10171 unsigned BitSize = MI.getOperand(6).getImm();
10172 DebugLoc DL = MI.getDebugLoc();
10173
10174 // Get the right opcodes for the displacement.
10175 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10176 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10177 assert(LOpcode && CSOpcode && "Displacement out of range");
10178
10179 // Create virtual registers for temporary results.
10180 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10181 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10182 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10183 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10184 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10185
10186 // Insert a basic block for the main loop.
10187 MachineBasicBlock *StartMBB = MBB;
10188 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10189 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10190
10191 // StartMBB:
10192 // ...
10193 // %OrigVal = L Disp(%Base)
10194 // # fall through to LoopMBB
10195 MBB = StartMBB;
10196 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10197 MBB->addSuccessor(LoopMBB);
10198
10199 // LoopMBB:
10200 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10201 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10202 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10203 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10204 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10205 // JNE LoopMBB
10206 // # fall through to DoneMBB
10207 MBB = LoopMBB;
10208 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10209 .addReg(OrigVal).addMBB(StartMBB)
10210 .addReg(Dest).addMBB(LoopMBB);
10211 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10212 .addReg(OldVal).addReg(BitShift).addImm(0);
10213 if (Invert) {
10214 // Perform the operation normally and then invert every bit of the field.
10215 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10216 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
10217 // XILF with the upper BitSize bits set.
10218 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10219 .addReg(Tmp).addImm(-1U << (32 - BitSize));
10220 } else if (BinOpcode)
10221 // A simply binary operation.
10222 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10223 .addReg(RotatedOldVal)
10224 .add(Src2);
10225 else
10226 // Use RISBG to rotate Src2 into position and use it to replace the
10227 // field in RotatedOldVal.
10228 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10229 .addReg(RotatedOldVal).addReg(Src2.getReg())
10230 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
10231 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10232 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10233 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10234 .addReg(OldVal)
10235 .addReg(NewVal)
10236 .add(Base)
10237 .addImm(Disp);
10238 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10240 MBB->addSuccessor(LoopMBB);
10241 MBB->addSuccessor(DoneMBB);
10242
10243 MI.eraseFromParent();
10244 return DoneMBB;
10245}
10246
10247// Implement EmitInstrWithCustomInserter for subword pseudo
10248// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10249// instruction that should be used to compare the current field with the
10250// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10251// for when the current field should be kept.
10252MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10253 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10254 unsigned KeepOldMask) const {
10255 MachineFunction &MF = *MBB->getParent();
10256 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10257 MachineRegisterInfo &MRI = MF.getRegInfo();
10258
10259 // Extract the operands. Base can be a register or a frame index.
10260 Register Dest = MI.getOperand(0).getReg();
10261 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10262 int64_t Disp = MI.getOperand(2).getImm();
10263 Register Src2 = MI.getOperand(3).getReg();
10264 Register BitShift = MI.getOperand(4).getReg();
10265 Register NegBitShift = MI.getOperand(5).getReg();
10266 unsigned BitSize = MI.getOperand(6).getImm();
10267 DebugLoc DL = MI.getDebugLoc();
10268
10269 // Get the right opcodes for the displacement.
10270 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10271 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10272 assert(LOpcode && CSOpcode && "Displacement out of range");
10273
10274 // Create virtual registers for temporary results.
10275 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10276 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10277 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10278 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10279 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10280 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10281
10282 // Insert 3 basic blocks for the loop.
10283 MachineBasicBlock *StartMBB = MBB;
10284 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10285 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10286 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10287 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10288
10289 // StartMBB:
10290 // ...
10291 // %OrigVal = L Disp(%Base)
10292 // # fall through to LoopMBB
10293 MBB = StartMBB;
10294 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10295 MBB->addSuccessor(LoopMBB);
10296
10297 // LoopMBB:
10298 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10299 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10300 // CompareOpcode %RotatedOldVal, %Src2
10301 // BRC KeepOldMask, UpdateMBB
10302 MBB = LoopMBB;
10303 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10304 .addReg(OrigVal).addMBB(StartMBB)
10305 .addReg(Dest).addMBB(UpdateMBB);
10306 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10307 .addReg(OldVal).addReg(BitShift).addImm(0);
10308 BuildMI(MBB, DL, TII->get(CompareOpcode))
10309 .addReg(RotatedOldVal).addReg(Src2);
10310 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10311 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10312 MBB->addSuccessor(UpdateMBB);
10313 MBB->addSuccessor(UseAltMBB);
10314
10315 // UseAltMBB:
10316 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10317 // # fall through to UpdateMBB
10318 MBB = UseAltMBB;
10319 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10320 .addReg(RotatedOldVal).addReg(Src2)
10321 .addImm(32).addImm(31 + BitSize).addImm(0);
10322 MBB->addSuccessor(UpdateMBB);
10323
10324 // UpdateMBB:
10325 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10326 // [ %RotatedAltVal, UseAltMBB ]
10327 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10328 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10329 // JNE LoopMBB
10330 // # fall through to DoneMBB
10331 MBB = UpdateMBB;
10332 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10333 .addReg(RotatedOldVal).addMBB(LoopMBB)
10334 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10335 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10336 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10337 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10338 .addReg(OldVal)
10339 .addReg(NewVal)
10340 .add(Base)
10341 .addImm(Disp);
10342 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10344 MBB->addSuccessor(LoopMBB);
10345 MBB->addSuccessor(DoneMBB);
10346
10347 MI.eraseFromParent();
10348 return DoneMBB;
10349}
10350
10351// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10352// instruction MI.
10354SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10355 MachineBasicBlock *MBB) const {
10356 MachineFunction &MF = *MBB->getParent();
10357 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10358 MachineRegisterInfo &MRI = MF.getRegInfo();
10359
10360 // Extract the operands. Base can be a register or a frame index.
10361 Register Dest = MI.getOperand(0).getReg();
10362 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10363 int64_t Disp = MI.getOperand(2).getImm();
10364 Register CmpVal = MI.getOperand(3).getReg();
10365 Register OrigSwapVal = MI.getOperand(4).getReg();
10366 Register BitShift = MI.getOperand(5).getReg();
10367 Register NegBitShift = MI.getOperand(6).getReg();
10368 int64_t BitSize = MI.getOperand(7).getImm();
10369 DebugLoc DL = MI.getDebugLoc();
10370
10371 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10372
10373 // Get the right opcodes for the displacement and zero-extension.
10374 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10375 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10376 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10377 assert(LOpcode && CSOpcode && "Displacement out of range");
10378
10379 // Create virtual registers for temporary results.
10380 Register OrigOldVal = MRI.createVirtualRegister(RC);
10381 Register OldVal = MRI.createVirtualRegister(RC);
10382 Register SwapVal = MRI.createVirtualRegister(RC);
10383 Register StoreVal = MRI.createVirtualRegister(RC);
10384 Register OldValRot = MRI.createVirtualRegister(RC);
10385 Register RetryOldVal = MRI.createVirtualRegister(RC);
10386 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10387
10388 // Insert 2 basic blocks for the loop.
10389 MachineBasicBlock *StartMBB = MBB;
10390 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10391 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10392 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10393
10394 // StartMBB:
10395 // ...
10396 // %OrigOldVal = L Disp(%Base)
10397 // # fall through to LoopMBB
10398 MBB = StartMBB;
10399 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10400 .add(Base)
10401 .addImm(Disp)
10402 .addReg(0);
10403 MBB->addSuccessor(LoopMBB);
10404
10405 // LoopMBB:
10406 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10407 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10408 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10409 // ^^ The low BitSize bits contain the field
10410 // of interest.
10411 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10412 // ^^ Replace the upper 32-BitSize bits of the
10413 // swap value with those that we loaded and rotated.
10414 // %Dest = LL[CH] %OldValRot
10415 // CR %Dest, %CmpVal
10416 // JNE DoneMBB
10417 // # Fall through to SetMBB
10418 MBB = LoopMBB;
10419 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10420 .addReg(OrigOldVal).addMBB(StartMBB)
10421 .addReg(RetryOldVal).addMBB(SetMBB);
10422 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10423 .addReg(OrigSwapVal).addMBB(StartMBB)
10424 .addReg(RetrySwapVal).addMBB(SetMBB);
10425 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10426 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10427 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10428 .addReg(SwapVal).addReg(OldValRot).addImm(32).addImm(63 - BitSize).addImm(0);
10429 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10430 .addReg(OldValRot);
10431 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10432 .addReg(Dest).addReg(CmpVal);
10433 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10436 MBB->addSuccessor(DoneMBB);
10437 MBB->addSuccessor(SetMBB);
10438
10439 // SetMBB:
10440 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10441 // ^^ Rotate the new field to its proper position.
10442 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10443 // JNE LoopMBB
10444 // # fall through to ExitMBB
10445 MBB = SetMBB;
10446 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10447 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10448 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10449 .addReg(OldVal)
10450 .addReg(StoreVal)
10451 .add(Base)
10452 .addImm(Disp);
10453 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10455 MBB->addSuccessor(LoopMBB);
10456 MBB->addSuccessor(DoneMBB);
10457
10458 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10459 // to the block after the loop. At this point, CC may have been defined
10460 // either by the CR in LoopMBB or by the CS in SetMBB.
10461 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10462 DoneMBB->addLiveIn(SystemZ::CC);
10463
10464 MI.eraseFromParent();
10465 return DoneMBB;
10466}
10467
10468// Emit a move from two GR64s to a GR128.
10470SystemZTargetLowering::emitPair128(MachineInstr &MI,
10471 MachineBasicBlock *MBB) const {
10472 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10473 const DebugLoc &DL = MI.getDebugLoc();
10474
10475 Register Dest = MI.getOperand(0).getReg();
10476 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest)
10477 .add(MI.getOperand(1))
10478 .addImm(SystemZ::subreg_h64)
10479 .add(MI.getOperand(2))
10480 .addImm(SystemZ::subreg_l64);
10481 MI.eraseFromParent();
10482 return MBB;
10483}
10484
10485// Emit an extension from a GR64 to a GR128. ClearEven is true
10486// if the high register of the GR128 value must be cleared or false if
10487// it's "don't care".
10488MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
10490 bool ClearEven) const {
10491 MachineFunction &MF = *MBB->getParent();
10492 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10493 MachineRegisterInfo &MRI = MF.getRegInfo();
10494 DebugLoc DL = MI.getDebugLoc();
10495
10496 Register Dest = MI.getOperand(0).getReg();
10497 Register Src = MI.getOperand(1).getReg();
10498 Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
10499
10500 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
10501 if (ClearEven) {
10502 Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
10503 Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10504
10505 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
10506 .addImm(0);
10507 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
10508 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
10509 In128 = NewIn128;
10510 }
10511 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
10512 .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64);
10513
10514 MI.eraseFromParent();
10515 return MBB;
10516}
10517
10519SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10521 unsigned Opcode, bool IsMemset) const {
10522 MachineFunction &MF = *MBB->getParent();
10523 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10524 MachineRegisterInfo &MRI = MF.getRegInfo();
10525 DebugLoc DL = MI.getDebugLoc();
10526
10527 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10528 uint64_t DestDisp = MI.getOperand(1).getImm();
10529 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10530 uint64_t SrcDisp;
10531
10532 // Fold the displacement Disp if it is out of range.
10533 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10534 if (!isUInt<12>(Disp)) {
10535 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10536 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10537 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10538 .add(Base).addImm(Disp).addReg(0);
10540 Disp = 0;
10541 }
10542 };
10543
10544 if (!IsMemset) {
10545 SrcBase = earlyUseOperand(MI.getOperand(2));
10546 SrcDisp = MI.getOperand(3).getImm();
10547 } else {
10548 SrcBase = DestBase;
10549 SrcDisp = DestDisp++;
10550 foldDisplIfNeeded(DestBase, DestDisp);
10551 }
10552
10553 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10554 bool IsImmForm = LengthMO.isImm();
10555 bool IsRegForm = !IsImmForm;
10556
10557 // Build and insert one Opcode of Length, with special treatment for memset.
10558 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10560 MachineOperand DBase, uint64_t DDisp,
10561 MachineOperand SBase, uint64_t SDisp,
10562 unsigned Length) -> void {
10563 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10564 if (IsMemset) {
10565 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10566 if (ByteMO.isImm())
10567 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10568 .add(SBase).addImm(SDisp).add(ByteMO);
10569 else
10570 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10571 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10572 if (--Length == 0)
10573 return;
10574 }
10575 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10576 .add(DBase).addImm(DDisp).addImm(Length)
10577 .add(SBase).addImm(SDisp)
10578 .setMemRefs(MI.memoperands());
10579 };
10580
10581 bool NeedsLoop = false;
10582 uint64_t ImmLength = 0;
10583 Register LenAdjReg = SystemZ::NoRegister;
10584 if (IsImmForm) {
10585 ImmLength = LengthMO.getImm();
10586 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10587 if (ImmLength == 0) {
10588 MI.eraseFromParent();
10589 return MBB;
10590 }
10591 if (Opcode == SystemZ::CLC) {
10592 if (ImmLength > 3 * 256)
10593 // A two-CLC sequence is a clear win over a loop, not least because
10594 // it needs only one branch. A three-CLC sequence needs the same
10595 // number of branches as a loop (i.e. 2), but is shorter. That
10596 // brings us to lengths greater than 768 bytes. It seems relatively
10597 // likely that a difference will be found within the first 768 bytes,
10598 // so we just optimize for the smallest number of branch
10599 // instructions, in order to avoid polluting the prediction buffer
10600 // too much.
10601 NeedsLoop = true;
10602 } else if (ImmLength > 6 * 256)
10603 // The heuristic we use is to prefer loops for anything that would
10604 // require 7 or more MVCs. With these kinds of sizes there isn't much
10605 // to choose between straight-line code and looping code, since the
10606 // time will be dominated by the MVCs themselves.
10607 NeedsLoop = true;
10608 } else {
10609 NeedsLoop = true;
10610 LenAdjReg = LengthMO.getReg();
10611 }
10612
10613 // When generating more than one CLC, all but the last will need to
10614 // branch to the end when a difference is found.
10615 MachineBasicBlock *EndMBB =
10616 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10618 : nullptr);
10619
10620 if (NeedsLoop) {
10621 Register StartCountReg =
10622 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10623 if (IsImmForm) {
10624 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10625 ImmLength &= 255;
10626 } else {
10627 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10628 .addReg(LenAdjReg)
10629 .addReg(0)
10630 .addImm(8);
10631 }
10632
10633 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10634 auto loadZeroAddress = [&]() -> MachineOperand {
10635 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10636 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10637 return MachineOperand::CreateReg(Reg, false);
10638 };
10639 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10640 DestBase = loadZeroAddress();
10641 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10642 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10643
10644 MachineBasicBlock *StartMBB = nullptr;
10645 MachineBasicBlock *LoopMBB = nullptr;
10646 MachineBasicBlock *NextMBB = nullptr;
10647 MachineBasicBlock *DoneMBB = nullptr;
10648 MachineBasicBlock *AllDoneMBB = nullptr;
10649
10650 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10651 Register StartDestReg =
10652 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10653
10654 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10655 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10656 Register ThisDestReg =
10657 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10658 Register NextSrcReg = MRI.createVirtualRegister(RC);
10659 Register NextDestReg =
10660 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10661 RC = &SystemZ::GR64BitRegClass;
10662 Register ThisCountReg = MRI.createVirtualRegister(RC);
10663 Register NextCountReg = MRI.createVirtualRegister(RC);
10664
10665 if (IsRegForm) {
10666 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10667 StartMBB = SystemZ::emitBlockAfter(MBB);
10668 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10669 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10670 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10671
10672 // MBB:
10673 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10674 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10675 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10676 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10678 .addMBB(AllDoneMBB);
10679 MBB->addSuccessor(AllDoneMBB);
10680 if (!IsMemset)
10681 MBB->addSuccessor(StartMBB);
10682 else {
10683 // MemsetOneCheckMBB:
10684 // # Jump to MemsetOneMBB for a memset of length 1, or
10685 // # fall thru to StartMBB.
10686 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10687 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10688 MBB->addSuccessor(MemsetOneCheckMBB);
10689 MBB = MemsetOneCheckMBB;
10690 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10691 .addReg(LenAdjReg).addImm(-1);
10692 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10694 .addMBB(MemsetOneMBB);
10695 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10696 MBB->addSuccessor(StartMBB, {90, 100});
10697
10698 // MemsetOneMBB:
10699 // # Jump back to AllDoneMBB after a single MVI or STC.
10700 MBB = MemsetOneMBB;
10701 insertMemMemOp(MBB, MBB->end(),
10702 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10703 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10704 1);
10705 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10706 MBB->addSuccessor(AllDoneMBB);
10707 }
10708
10709 // StartMBB:
10710 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10711 MBB = StartMBB;
10712 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10713 .addReg(StartCountReg).addImm(0);
10714 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10716 .addMBB(DoneMBB);
10717 MBB->addSuccessor(DoneMBB);
10718 MBB->addSuccessor(LoopMBB);
10719 }
10720 else {
10721 StartMBB = MBB;
10722 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10723 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10724 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10725
10726 // StartMBB:
10727 // # fall through to LoopMBB
10728 MBB->addSuccessor(LoopMBB);
10729
10730 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10731 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10732 if (EndMBB && !ImmLength)
10733 // If the loop handled the whole CLC range, DoneMBB will be empty with
10734 // CC live-through into EndMBB, so add it as live-in.
10735 DoneMBB->addLiveIn(SystemZ::CC);
10736 }
10737
10738 // LoopMBB:
10739 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10740 // [ %NextDestReg, NextMBB ]
10741 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10742 // [ %NextSrcReg, NextMBB ]
10743 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10744 // [ %NextCountReg, NextMBB ]
10745 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10746 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10747 // ( JLH EndMBB )
10748 //
10749 // The prefetch is used only for MVC. The JLH is used only for CLC.
10750 MBB = LoopMBB;
10751 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10752 .addReg(StartDestReg).addMBB(StartMBB)
10753 .addReg(NextDestReg).addMBB(NextMBB);
10754 if (!HaveSingleBase)
10755 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10756 .addReg(StartSrcReg).addMBB(StartMBB)
10757 .addReg(NextSrcReg).addMBB(NextMBB);
10758 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10759 .addReg(StartCountReg).addMBB(StartMBB)
10760 .addReg(NextCountReg).addMBB(NextMBB);
10761 if (Opcode == SystemZ::MVC)
10762 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10764 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10765 insertMemMemOp(MBB, MBB->end(),
10766 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10767 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10768 if (EndMBB) {
10769 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10771 .addMBB(EndMBB);
10772 MBB->addSuccessor(EndMBB);
10773 MBB->addSuccessor(NextMBB);
10774 }
10775
10776 // NextMBB:
10777 // %NextDestReg = LA 256(%ThisDestReg)
10778 // %NextSrcReg = LA 256(%ThisSrcReg)
10779 // %NextCountReg = AGHI %ThisCountReg, -1
10780 // CGHI %NextCountReg, 0
10781 // JLH LoopMBB
10782 // # fall through to DoneMBB
10783 //
10784 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10785 MBB = NextMBB;
10786 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10787 .addReg(ThisDestReg).addImm(256).addReg(0);
10788 if (!HaveSingleBase)
10789 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10790 .addReg(ThisSrcReg).addImm(256).addReg(0);
10791 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10792 .addReg(ThisCountReg).addImm(-1);
10793 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10794 .addReg(NextCountReg).addImm(0);
10795 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10797 .addMBB(LoopMBB);
10798 MBB->addSuccessor(LoopMBB);
10799 MBB->addSuccessor(DoneMBB);
10800
10801 MBB = DoneMBB;
10802 if (IsRegForm) {
10803 // DoneMBB:
10804 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10805 // # Use EXecute Relative Long for the remainder of the bytes. The target
10806 // instruction of the EXRL will have a length field of 1 since 0 is an
10807 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10808 // 0xff) + 1.
10809 // # Fall through to AllDoneMBB.
10810 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10811 Register RemDestReg = HaveSingleBase ? RemSrcReg
10812 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10813 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
10814 .addReg(StartDestReg).addMBB(StartMBB)
10815 .addReg(NextDestReg).addMBB(NextMBB);
10816 if (!HaveSingleBase)
10817 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
10818 .addReg(StartSrcReg).addMBB(StartMBB)
10819 .addReg(NextSrcReg).addMBB(NextMBB);
10820 if (IsMemset)
10821 insertMemMemOp(MBB, MBB->end(),
10822 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
10823 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
10824 MachineInstrBuilder EXRL_MIB =
10825 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
10826 .addImm(Opcode)
10827 .addReg(LenAdjReg)
10828 .addReg(RemDestReg).addImm(DestDisp)
10829 .addReg(RemSrcReg).addImm(SrcDisp);
10830 MBB->addSuccessor(AllDoneMBB);
10831 MBB = AllDoneMBB;
10832 if (Opcode != SystemZ::MVC) {
10833 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
10834 if (EndMBB)
10835 MBB->addLiveIn(SystemZ::CC);
10836 }
10837 }
10838 MF.getProperties().resetNoPHIs();
10839 }
10840
10841 // Handle any remaining bytes with straight-line code.
10842 while (ImmLength > 0) {
10843 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
10844 // The previous iteration might have created out-of-range displacements.
10845 // Apply them using LA/LAY if so.
10846 foldDisplIfNeeded(DestBase, DestDisp);
10847 foldDisplIfNeeded(SrcBase, SrcDisp);
10848 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
10849 DestDisp += ThisLength;
10850 SrcDisp += ThisLength;
10851 ImmLength -= ThisLength;
10852 // If there's another CLC to go, branch to the end if a difference
10853 // was found.
10854 if (EndMBB && ImmLength > 0) {
10855 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
10856 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10858 .addMBB(EndMBB);
10859 MBB->addSuccessor(EndMBB);
10860 MBB->addSuccessor(NextMBB);
10861 MBB = NextMBB;
10862 }
10863 }
10864 if (EndMBB) {
10865 MBB->addSuccessor(EndMBB);
10866 MBB = EndMBB;
10867 MBB->addLiveIn(SystemZ::CC);
10868 }
10869
10870 MI.eraseFromParent();
10871 return MBB;
10872}
10873
10874// Decompose string pseudo-instruction MI into a loop that continually performs
10875// Opcode until CC != 3.
10876MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
10877 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
10878 MachineFunction &MF = *MBB->getParent();
10879 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10880 MachineRegisterInfo &MRI = MF.getRegInfo();
10881 DebugLoc DL = MI.getDebugLoc();
10882
10883 uint64_t End1Reg = MI.getOperand(0).getReg();
10884 uint64_t Start1Reg = MI.getOperand(1).getReg();
10885 uint64_t Start2Reg = MI.getOperand(2).getReg();
10886 uint64_t CharReg = MI.getOperand(3).getReg();
10887
10888 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
10889 uint64_t This1Reg = MRI.createVirtualRegister(RC);
10890 uint64_t This2Reg = MRI.createVirtualRegister(RC);
10891 uint64_t End2Reg = MRI.createVirtualRegister(RC);
10892
10893 MachineBasicBlock *StartMBB = MBB;
10894 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10895 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10896
10897 // StartMBB:
10898 // # fall through to LoopMBB
10899 MBB->addSuccessor(LoopMBB);
10900
10901 // LoopMBB:
10902 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
10903 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
10904 // R0L = %CharReg
10905 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
10906 // JO LoopMBB
10907 // # fall through to DoneMBB
10908 //
10909 // The load of R0L can be hoisted by post-RA LICM.
10910 MBB = LoopMBB;
10911
10912 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
10913 .addReg(Start1Reg).addMBB(StartMBB)
10914 .addReg(End1Reg).addMBB(LoopMBB);
10915 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
10916 .addReg(Start2Reg).addMBB(StartMBB)
10917 .addReg(End2Reg).addMBB(LoopMBB);
10918 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
10919 BuildMI(MBB, DL, TII->get(Opcode))
10920 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
10921 .addReg(This1Reg).addReg(This2Reg);
10922 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10924 MBB->addSuccessor(LoopMBB);
10925 MBB->addSuccessor(DoneMBB);
10926
10927 DoneMBB->addLiveIn(SystemZ::CC);
10928
10929 MI.eraseFromParent();
10930 return DoneMBB;
10931}
10932
10933// Update TBEGIN instruction with final opcode and register clobbers.
10934MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
10935 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
10936 bool NoFloat) const {
10937 MachineFunction &MF = *MBB->getParent();
10938 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
10939 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10940
10941 // Update opcode.
10942 MI.setDesc(TII->get(Opcode));
10943
10944 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
10945 // Make sure to add the corresponding GRSM bits if they are missing.
10946 uint64_t Control = MI.getOperand(2).getImm();
10947 static const unsigned GPRControlBit[16] = {
10948 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
10949 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
10950 };
10951 Control |= GPRControlBit[15];
10952 if (TFI->hasFP(MF))
10953 Control |= GPRControlBit[11];
10954 MI.getOperand(2).setImm(Control);
10955
10956 // Add GPR clobbers.
10957 for (int I = 0; I < 16; I++) {
10958 if ((Control & GPRControlBit[I]) == 0) {
10959 unsigned Reg = SystemZMC::GR64Regs[I];
10960 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
10961 }
10962 }
10963
10964 // Add FPR/VR clobbers.
10965 if (!NoFloat && (Control & 4) != 0) {
10966 if (Subtarget.hasVector()) {
10967 for (unsigned Reg : SystemZMC::VR128Regs) {
10968 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
10969 }
10970 } else {
10971 for (unsigned Reg : SystemZMC::FP64Regs) {
10972 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
10973 }
10974 }
10975 }
10976
10977 return MBB;
10978}
10979
10980MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
10981 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
10982 MachineFunction &MF = *MBB->getParent();
10983 MachineRegisterInfo *MRI = &MF.getRegInfo();
10984 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10985 DebugLoc DL = MI.getDebugLoc();
10986
10987 Register SrcReg = MI.getOperand(0).getReg();
10988
10989 // Create new virtual register of the same class as source.
10990 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
10991 Register DstReg = MRI->createVirtualRegister(RC);
10992
10993 // Replace pseudo with a normal load-and-test that models the def as
10994 // well.
10995 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
10996 .addReg(SrcReg)
10997 .setMIFlags(MI.getFlags());
10998 MI.eraseFromParent();
10999
11000 return MBB;
11001}
11002
11003MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11005 MachineFunction &MF = *MBB->getParent();
11006 MachineRegisterInfo *MRI = &MF.getRegInfo();
11007 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11008 DebugLoc DL = MI.getDebugLoc();
11009 const unsigned ProbeSize = getStackProbeSize(MF);
11010 Register DstReg = MI.getOperand(0).getReg();
11011 Register SizeReg = MI.getOperand(2).getReg();
11012
11013 MachineBasicBlock *StartMBB = MBB;
11014 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11015 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11016 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11017 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11018 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11019
11020 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11022
11023 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11024 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11025
11026 // LoopTestMBB
11027 // BRC TailTestMBB
11028 // # fallthrough to LoopBodyMBB
11029 StartMBB->addSuccessor(LoopTestMBB);
11030 MBB = LoopTestMBB;
11031 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11032 .addReg(SizeReg)
11033 .addMBB(StartMBB)
11034 .addReg(IncReg)
11035 .addMBB(LoopBodyMBB);
11036 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11037 .addReg(PHIReg)
11038 .addImm(ProbeSize);
11039 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11041 .addMBB(TailTestMBB);
11042 MBB->addSuccessor(LoopBodyMBB);
11043 MBB->addSuccessor(TailTestMBB);
11044
11045 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11046 // J LoopTestMBB
11047 MBB = LoopBodyMBB;
11048 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11049 .addReg(PHIReg)
11050 .addImm(ProbeSize);
11051 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11052 .addReg(SystemZ::R15D)
11053 .addImm(ProbeSize);
11054 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
11055 .addReg(SystemZ::R15D).addImm(ProbeSize - 8).addReg(0)
11056 .setMemRefs(VolLdMMO);
11057 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11058 MBB->addSuccessor(LoopTestMBB);
11059
11060 // TailTestMBB
11061 // BRC DoneMBB
11062 // # fallthrough to TailMBB
11063 MBB = TailTestMBB;
11064 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11065 .addReg(PHIReg)
11066 .addImm(0);
11067 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11069 .addMBB(DoneMBB);
11070 MBB->addSuccessor(TailMBB);
11071 MBB->addSuccessor(DoneMBB);
11072
11073 // TailMBB
11074 // # fallthrough to DoneMBB
11075 MBB = TailMBB;
11076 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11077 .addReg(SystemZ::R15D)
11078 .addReg(PHIReg);
11079 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
11080 .addReg(SystemZ::R15D).addImm(-8).addReg(PHIReg)
11081 .setMemRefs(VolLdMMO);
11082 MBB->addSuccessor(DoneMBB);
11083
11084 // DoneMBB
11085 MBB = DoneMBB;
11086 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11087 .addReg(SystemZ::R15D);
11088
11089 MI.eraseFromParent();
11090 return DoneMBB;
11091}
11092
11093SDValue SystemZTargetLowering::
11094getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11095 MachineFunction &MF = DAG.getMachineFunction();
11096 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11097 SDLoc DL(SP);
11098 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11099 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11100}
11101
11102// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11103// a dead early-clobber def reg that will be used as a scratch register
11104// when the pseudo is expanded.
11105MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11106 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11107 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11108 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11109 DebugLoc DL = MI.getDebugLoc();
11110 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11111 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11112 .addFrameIndex(MI.getOperand(0).getIndex())
11113 .addImm(MI.getOperand(1).getImm());
11114 MI.eraseFromParent();
11115 return MBB;
11116}
11117
11120 switch (MI.getOpcode()) {
11121 case SystemZ::ADJCALLSTACKDOWN:
11122 case SystemZ::ADJCALLSTACKUP:
11123 return emitAdjCallStack(MI, MBB);
11124
11125 case SystemZ::Select32:
11126 case SystemZ::Select64:
11127 case SystemZ::Select128:
11128 case SystemZ::SelectF32:
11129 case SystemZ::SelectF64:
11130 case SystemZ::SelectF128:
11131 case SystemZ::SelectVR32:
11132 case SystemZ::SelectVR64:
11133 case SystemZ::SelectVR128:
11134 return emitSelect(MI, MBB);
11135
11136 case SystemZ::CondStore8Mux:
11137 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11138 case SystemZ::CondStore8MuxInv:
11139 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11140 case SystemZ::CondStore16Mux:
11141 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11142 case SystemZ::CondStore16MuxInv:
11143 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11144 case SystemZ::CondStore32Mux:
11145 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11146 case SystemZ::CondStore32MuxInv:
11147 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11148 case SystemZ::CondStore8:
11149 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11150 case SystemZ::CondStore8Inv:
11151 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11152 case SystemZ::CondStore16:
11153 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11154 case SystemZ::CondStore16Inv:
11155 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11156 case SystemZ::CondStore32:
11157 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11158 case SystemZ::CondStore32Inv:
11159 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11160 case SystemZ::CondStore64:
11161 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11162 case SystemZ::CondStore64Inv:
11163 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11164 case SystemZ::CondStoreF32:
11165 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11166 case SystemZ::CondStoreF32Inv:
11167 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11168 case SystemZ::CondStoreF64:
11169 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11170 case SystemZ::CondStoreF64Inv:
11171 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11172
11173 case SystemZ::SCmp128Hi:
11174 return emitICmp128Hi(MI, MBB, false);
11175 case SystemZ::UCmp128Hi:
11176 return emitICmp128Hi(MI, MBB, true);
11177
11178 case SystemZ::PAIR128:
11179 return emitPair128(MI, MBB);
11180 case SystemZ::AEXT128:
11181 return emitExt128(MI, MBB, false);
11182 case SystemZ::ZEXT128:
11183 return emitExt128(MI, MBB, true);
11184
11185 case SystemZ::ATOMIC_SWAPW:
11186 return emitAtomicLoadBinary(MI, MBB, 0);
11187
11188 case SystemZ::ATOMIC_LOADW_AR:
11189 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11190 case SystemZ::ATOMIC_LOADW_AFI:
11191 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11192
11193 case SystemZ::ATOMIC_LOADW_SR:
11194 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11195
11196 case SystemZ::ATOMIC_LOADW_NR:
11197 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11198 case SystemZ::ATOMIC_LOADW_NILH:
11199 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11200
11201 case SystemZ::ATOMIC_LOADW_OR:
11202 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11203 case SystemZ::ATOMIC_LOADW_OILH:
11204 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11205
11206 case SystemZ::ATOMIC_LOADW_XR:
11207 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11208 case SystemZ::ATOMIC_LOADW_XILF:
11209 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11210
11211 case SystemZ::ATOMIC_LOADW_NRi:
11212 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11213 case SystemZ::ATOMIC_LOADW_NILHi:
11214 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11215
11216 case SystemZ::ATOMIC_LOADW_MIN:
11217 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11218 case SystemZ::ATOMIC_LOADW_MAX:
11219 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11220 case SystemZ::ATOMIC_LOADW_UMIN:
11221 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11222 case SystemZ::ATOMIC_LOADW_UMAX:
11223 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11224
11225 case SystemZ::ATOMIC_CMP_SWAPW:
11226 return emitAtomicCmpSwapW(MI, MBB);
11227 case SystemZ::MVCImm:
11228 case SystemZ::MVCReg:
11229 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11230 case SystemZ::NCImm:
11231 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11232 case SystemZ::OCImm:
11233 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11234 case SystemZ::XCImm:
11235 case SystemZ::XCReg:
11236 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11237 case SystemZ::CLCImm:
11238 case SystemZ::CLCReg:
11239 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11240 case SystemZ::MemsetImmImm:
11241 case SystemZ::MemsetImmReg:
11242 case SystemZ::MemsetRegImm:
11243 case SystemZ::MemsetRegReg:
11244 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11245 case SystemZ::CLSTLoop:
11246 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11247 case SystemZ::MVSTLoop:
11248 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11249 case SystemZ::SRSTLoop:
11250 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11251 case SystemZ::TBEGIN:
11252 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11253 case SystemZ::TBEGIN_nofloat:
11254 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11255 case SystemZ::TBEGINC:
11256 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11257 case SystemZ::LTEBRCompare_Pseudo:
11258 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11259 case SystemZ::LTDBRCompare_Pseudo:
11260 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11261 case SystemZ::LTXBRCompare_Pseudo:
11262 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11263
11264 case SystemZ::PROBED_ALLOCA:
11265 return emitProbedAlloca(MI, MBB);
11266 case SystemZ::EH_SjLj_SetJmp:
11267 return emitEHSjLjSetJmp(MI, MBB);
11268 case SystemZ::EH_SjLj_LongJmp:
11269 return emitEHSjLjLongJmp(MI, MBB);
11270
11271 case TargetOpcode::STACKMAP:
11272 case TargetOpcode::PATCHPOINT:
11273 return emitPatchPoint(MI, MBB);
11274
11275 case SystemZ::MOV_STACKGUARD_DAG:
11276 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11277
11278 case SystemZ::CMP_STACKGUARD_DAG:
11279 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11280
11281 default:
11282 llvm_unreachable("Unexpected instr type to insert");
11283 }
11284}
11285
11286// This is only used by the isel schedulers, and is needed only to prevent
11287// compiler from crashing when list-ilp is used.
11288const TargetRegisterClass *
11289SystemZTargetLowering::getRepRegClassFor(MVT VT) const {
11290 if (VT == MVT::Untyped)
11291 return &SystemZ::ADDR128BitRegClass;
11293}
11294
11295SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11296 SelectionDAG &DAG) const {
11297 SDLoc dl(Op);
11298 /*
11299 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11300 settings:
11301 00 Round to nearest
11302 01 Round to 0
11303 10 Round to +inf
11304 11 Round to -inf
11305
11306 FLT_ROUNDS, on the other hand, expects the following:
11307 -1 Undefined
11308 0 Round to 0
11309 1 Round to nearest
11310 2 Round to +inf
11311 3 Round to -inf
11312 */
11313
11314 // Save FPC to register.
11315 SDValue Chain = Op.getOperand(0);
11316 SDValue EFPC(
11317 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11318 Chain = EFPC.getValue(1);
11319
11320 // Transform as necessary
11321 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11322 DAG.getConstant(3, dl, MVT::i32));
11323 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11324 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11325 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11326 DAG.getConstant(1, dl, MVT::i32)));
11327
11328 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11329 DAG.getConstant(1, dl, MVT::i32));
11330 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11331
11332 return DAG.getMergeValues({RetVal, Chain}, dl);
11333}
11334
11335SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11336 SelectionDAG &DAG) const {
11337 EVT VT = Op.getValueType();
11338 Op = Op.getOperand(0);
11339 EVT OpVT = Op.getValueType();
11340
11341 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11342
11343 SDLoc DL(Op);
11344
11345 // load a 0 vector for the third operand of VSUM.
11346 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11347
11348 // execute VSUM.
11349 switch (OpVT.getScalarSizeInBits()) {
11350 case 8:
11351 case 16:
11352 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11353 [[fallthrough]];
11354 case 32:
11355 case 64:
11356 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11357 DAG.getBitcast(Op.getValueType(), Zero));
11358 break;
11359 case 128:
11360 break; // VSUM over v1i128 should not happen and would be a noop
11361 default:
11362 llvm_unreachable("Unexpected scalar size.");
11363 }
11364 // Cast to original vector type, retrieve last element.
11365 return DAG.getNode(
11366 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11367 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11368}
11369
11371 FunctionType *FT = F->getFunctionType();
11372 const AttributeList &Attrs = F->getAttributes();
11373 if (Attrs.hasRetAttrs())
11374 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11375 OS << *F->getReturnType() << " @" << F->getName() << "(";
11376 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11377 if (I)
11378 OS << ", ";
11379 OS << *FT->getParamType(I);
11380 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11381 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11382 if (ArgAttrs.hasAttribute(A))
11383 OS << " " << Attribute::getNameFromAttrKind(A);
11384 }
11385 OS << ")\n";
11386}
11387
11388bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11389 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11390 if (Itr == IsInternalCache.end())
11391 Itr = IsInternalCache
11392 .insert(std::pair<const Function *, bool>(
11393 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11394 .first;
11395 return Itr->second;
11396}
11397
11398void SystemZTargetLowering::
11399verifyNarrowIntegerArgs_Call(const SmallVectorImpl<ISD::OutputArg> &Outs,
11400 const Function *F, SDValue Callee) const {
11401 // Temporarily only do the check when explicitly requested, until it can be
11402 // enabled by default.
11404 return;
11405
11406 bool IsInternal = false;
11407 const Function *CalleeFn = nullptr;
11408 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11409 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11410 IsInternal = isInternal(CalleeFn);
11411 if (!IsInternal && !verifyNarrowIntegerArgs(Outs)) {
11412 errs() << "ERROR: Missing extension attribute of passed "
11413 << "value in call to function:\n" << "Callee: ";
11414 if (CalleeFn != nullptr)
11415 printFunctionArgExts(CalleeFn, errs());
11416 else
11417 errs() << "-\n";
11418 errs() << "Caller: ";
11420 llvm_unreachable("");
11421 }
11422}
11423
11424void SystemZTargetLowering::
11425verifyNarrowIntegerArgs_Ret(const SmallVectorImpl<ISD::OutputArg> &Outs,
11426 const Function *F) const {
11427 // Temporarily only do the check when explicitly requested, until it can be
11428 // enabled by default.
11430 return;
11431
11432 if (!isInternal(F) && !verifyNarrowIntegerArgs(Outs)) {
11433 errs() << "ERROR: Missing extension attribute of returned "
11434 << "value from function:\n";
11436 llvm_unreachable("");
11437 }
11438}
11439
11440// Verify that narrow integer arguments are extended as required by the ABI.
11441// Return false if an error is found.
11442bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11443 const SmallVectorImpl<ISD::OutputArg> &Outs) const {
11444 if (!Subtarget.isTargetELF())
11445 return true;
11446
11449 return true;
11450 } else if (!getTargetMachine().Options.VerifyArgABICompliance)
11451 return true;
11452
11453 for (unsigned i = 0; i < Outs.size(); ++i) {
11454 MVT VT = Outs[i].VT;
11455 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11456 if (VT.isInteger()) {
11457 assert((VT == MVT::i32 || VT.getSizeInBits() >= 64) &&
11458 "Unexpected integer argument VT.");
11459 if (VT == MVT::i32 &&
11460 !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt())
11461 return false;
11462 }
11463 }
11464
11465 return true;
11466}
11467
11469 Module &M, const LibcallLoweringInfo &Libcalls) const {
11470 StringRef GuardMode = M.getStackProtectorGuard();
11471
11472 // In the TLS case, no symbol needs to be inserted.
11473 if (GuardMode == "tls" || GuardMode.empty())
11474 return;
11475
11476 // Otherwise (in the global case), insert the appropriate global variable.
11478}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
AMDGPU Register Bank Select
static bool isZeroVector(SDValue N)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
#define Check(C,...)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
static bool isSelectPseudo(MachineInstr &MI)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SDValue getI128Select(SelectionDAG &DAG, const SDLoc &DL, Comparison C, SDValue TrueOp, SDValue FalseOp)
static SmallVector< SDValue, 4 > simplifyAssumingCCVal(SDValue &Val, SDValue &CC, SelectionDAG &DAG)
static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void printFunctionArgExts(const Function *F, raw_fd_ostream &OS)
static void adjustForLTGFR(Comparison &C)
static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, SDValue Op1)
#define CONV(X)
static cl::opt< bool > EnableIntArgExtCheck("argext-abi-check", cl::init(false), cl::desc("Verify that narrow int args are properly extended per the " "SystemZ ABI."))
static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG)
static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, unsigned Opcode, SDValue Op0, SDValue Op1, SDValue &Even, SDValue &Odd)
static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue lowerAddrSpaceCast(SDValue Op, SelectionDAG &DAG)
static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Value)
static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In)
static bool isSimpleShift(SDValue N, unsigned &ShiftVal)
static SDValue mergeHighParts(SelectionDAG &DAG, const SDLoc &DL, unsigned MergedBits, EVT VT, SDValue Op0, SDValue Op1)
static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1)
static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num)
static bool isVectorElementSwap(ArrayRef< int > M, EVT VT)
static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, SDValue &AlignedAddr, SDValue &BitShift, SDValue &NegBitShift)
static bool isShlDoublePermute(const SmallVectorImpl< int > &Bytes, unsigned &StartIndex, unsigned &OpNo0, unsigned &OpNo1)
static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, const Permute &P, SDValue Op0, SDValue Op1)
static SDNode * emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg)
static void adjustForStackGuardCompare(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, SDValue Op0, SDValue Op1, SDValue &Hi, SDValue &Lo)
static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static void createPHIsForSelects(SmallVector< MachineInstr *, 8 > &Selects, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *SinkMBB)
static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, SDValue *Ops, const SmallVectorImpl< int > &Bytes)
static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, bool &Invert)
static unsigned CCMaskForCondCode(ISD::CondCode CC)
static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForFNeg(Comparison &C)
static bool isScalarToVector(SDValue Op)
static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, unsigned CCValid, unsigned CCMask)
static bool matchPermute(const SmallVectorImpl< int > &Bytes, const Permute &P, unsigned &OpNo0, unsigned &OpNo1)
static bool isAddCarryChain(SDValue Carry)
static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static MachineOperand earlyUseOperand(MachineOperand Op)
static bool canUseSiblingCall(const CCState &ArgCCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, SmallVectorImpl< ISD::OutputArg > &Outs)
static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, SDLoc &DL, SDValue &Chain)
static SDValue convertToF16(SDValue Op, SelectionDAG &DAG)
static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask, SelectionDAG &DAG)
static bool shouldSwapCmpOperands(const Comparison &C)
static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType)
static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, unsigned Offset, bool LoadAdr=false)
static SDNode * emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool getVPermMask(SDValue ShuffleOp, SmallVectorImpl< int > &Bytes)
static const Permute PermuteForms[]
static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static std::pair< SDValue, int > findCCUse(const SDValue &Val, unsigned Depth=0)
static bool isSubBorrowChain(SDValue Carry)
static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool analyzeArgSplit(const SmallVectorImpl< ArgTy > &Args, SmallVector< CCValAssign, 16 > &ArgLocs, unsigned I, MVT &PartVT, unsigned &NumParts)
static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, unsigned OpNo)
static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, bool IsNegative)
static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static SDValue expandBitCastI128ToF128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, BuildVectorSDNode *BVN)
static SDValue convertFromF16(SDValue Op, SDLoc DL, SelectionDAG &DAG)
static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode)
static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In)
static SDValue MergeInputChains(SDNode *N1, SDNode *N2)
static SDValue expandBitCastF128ToI128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, uint64_t Mask, uint64_t CmpVal, unsigned ICmpType)
static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, SDValue Op, SDValue Chain)
static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, ISD::CondCode Cond, const SDLoc &DL, SDValue Chain=SDValue(), bool IsSignaling=false)
static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB)
static Register forceReg(MachineInstr &MI, MachineOperand &Base, const SystemZInstrInfo *TII)
static bool is32Bit(EVT VT)
static std::pair< unsigned, const TargetRegisterClass * > parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, const unsigned *Map, unsigned Size)
static unsigned detectEvenOddMultiplyOperand(const SelectionDAG &DAG, const SystemZSubtarget &Subtarget, SDValue &Op)
static bool matchDoublePermute(const SmallVectorImpl< int > &Bytes, const Permute &P, SmallVectorImpl< int > &Transform)
static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, SDValue Call, unsigned CCValid, uint64_t CC, ISD::CondCode Cond)
static SDValue buildFPVecFromScalars4(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SmallVectorImpl< SDValue > &Elems, unsigned Pos)
static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg)
static AddressingMode getLoadStoreAddrMode(bool HasVector, Type *Ty)
static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op0, SDValue Op1)
static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static bool getShuffleInput(const SmallVectorImpl< int > &Bytes, unsigned Start, unsigned BytesPerElement, int &Base)
static AddressingMode supportedAddressingMode(Instruction *I, bool HasVector)
static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:259
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition APInt.h:323
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:398
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:407
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI bool isConstant() const
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
uint64_t getZExtValue() const
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:933
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:758
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:770
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasInternalLinkage() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Tracks which library functions to use for a particular subtarget.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
Machine Value Type.
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
reverse_iterator rbegin()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineFunctionProperties & getProperties() const
Get the function properties.
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
Align getBaseAlign() const
Returns alignment and volatility of the memory access.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS)
Return an AddrSpaceCastSDNode.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands,...
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
ArrayRef< int > getMask() const
const_iterator begin() const
Definition SmallSet.h:216
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
A SystemZ-specific class detailing special use registers particular for calling conventions.
static SystemZConstantPoolValue * Create(const GlobalValue *GV, SystemZCP::SystemZCPModifier Modifier)
const SystemZInstrInfo * getInstrInfo() const override
SystemZCallingConventionRegisters * getSpecialRegisters() const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
Register getExceptionSelectorRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
bool hasInlineStackProbe(const MachineFunction &MF) const override
Returns true if stack probing through inline assembly is requested.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT) const override
Return the ValueType of the result of SETCC operations.
bool allowTruncateForTailCall(Type *, Type *) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag, const SDLoc &DL, const AsmOperandInfo &Constraint, SelectionDAG &DAG) const override
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
std::pair< SDValue, SDValue > makeExternalCall(SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT, ArrayRef< SDValue > Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL, bool DoesNotReturn, bool IsReturnValueUsed) const
void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const override
Insert SSP declaration if global stack protector is used.
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const override
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SystemZTargetLowering(const TargetMachine &TM, const SystemZSubtarget &STI)
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
TargetLowering::ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AS, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Determine if the target supports unaligned memory accesses.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
TargetLowering::ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns true if the target can instruction select the specified FP immediate natively.
Register getExceptionPointerRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const override
Target-specific combining of register parts into its original value.
bool isTruncateFree(Type *, Type *) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
SDValue useLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, MVT VT, SDValue Arg, SDLoc DL, SDValue Chain, bool IsStrict) const
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine the number of bits in the operation that are sign bits.
void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, const Function *F) const override
bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const override
Determines the optimal series of memory ops to replace the memset / memcpy.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
unsigned getStackProbeSize(const MachineFunction &MF) const
XPLINK64 calling convention specific use registers Particular to z/OS when in 64 bit mode.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
unsigned getPointerSize(unsigned AS) const
Get the pointer size for this target.
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
int getNumOccurrences() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
A raw_ostream that writes to a file descriptor.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:513
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:168
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ GlobalAddress
Definition ISDOpcodes.h:88
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:473
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:920
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:438
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:798
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:487
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BR_JT
BR_JT - Jumptable branch.
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:980
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:472
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:486
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:466
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:480
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:427
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:797
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:458
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:162
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
const unsigned GR64Regs[16]
const unsigned VR128Regs[32]
const unsigned VR16Regs[32]
const unsigned GR128Regs[16]
const unsigned FP32Regs[16]
const unsigned FP16Regs[16]
const unsigned GR32Regs[16]
const unsigned FP64Regs[16]
const int64_t ELFCallFrameSize
const unsigned VR64Regs[32]
const unsigned FP128Regs[16]
const unsigned VR32Regs[32]
unsigned odd128(bool Is32bit)
const unsigned CCMASK_CMP_GE
Definition SystemZ.h:41
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:177
const unsigned CCMASK_TEND
Definition SystemZ.h:98
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:68
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:93
const unsigned CCMASK_0
Definition SystemZ.h:28
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:83
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:61
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:123
const unsigned CCMASK_TDC
Definition SystemZ.h:110
const unsigned CCMASK_FCMP
Definition SystemZ.h:49
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:82
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:172
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:125
const unsigned PFD_READ
Definition SystemZ.h:116
const unsigned CCMASK_1
Definition SystemZ.h:29
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:122
const unsigned PFD_WRITE
Definition SystemZ.h:117
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:38
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:129
const unsigned CCMASK_CS
Definition SystemZ.h:70
const unsigned CCMASK_ANY
Definition SystemZ.h:32
const unsigned CCMASK_ARITH
Definition SystemZ.h:56
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:79
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:124
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:162
const unsigned VectorBits
Definition SystemZ.h:155
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:167
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:126
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:78
const unsigned IPM_CC
Definition SystemZ.h:113
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:40
const unsigned CCMASK_CMP_O
Definition SystemZ.h:45
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:36
const unsigned VectorBytes
Definition SystemZ.h:159
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:127
const unsigned CCMASK_ICMP
Definition SystemZ.h:48
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:102
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:104
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:105
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:80
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:84
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:55
const unsigned CCMASK_CS_NE
Definition SystemZ.h:69
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:130
const unsigned CCMASK_TM
Definition SystemZ.h:86
const unsigned CCMASK_3
Definition SystemZ.h:31
const unsigned CCMASK_NONE
Definition SystemZ.h:27
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:37
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:39
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:120
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:128
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:121
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:81
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:63
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:44
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:65
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:85
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:131
initializer< Ty > init(const Ty &Val)
support::ulittle32_t Word
Definition IRSymtab.h:53
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:387
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:383
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:344
@ Offset
Definition DWP.cpp:573
@ Length
Definition DWP.cpp:573
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:88
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:77
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N
#define EQ(a, b)
Definition regexec.c:65
AddressingMode(bool LongDispl, bool IdxReg)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:181
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
SmallVector< unsigned, 2 > OpVals
bool isVectorConstantLegal(const SystemZSubtarget &Subtarget)
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.