LLVM 17.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"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsS390.h"
27#include <cctype>
28#include <optional>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "systemz-lower"
33
34namespace {
35// Represents information about a comparison.
36struct Comparison {
37 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
38 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
39 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
40
41 // The operands to the comparison.
42 SDValue Op0, Op1;
43
44 // Chain if this is a strict floating-point comparison.
45 SDValue Chain;
46
47 // The opcode that should be used to compare Op0 and Op1.
48 unsigned Opcode;
49
50 // A SystemZICMP value. Only used for integer comparisons.
51 unsigned ICmpType;
52
53 // The mask of CC values that Opcode can produce.
54 unsigned CCValid;
55
56 // The mask of CC values for which the original condition is true.
57 unsigned CCMask;
58};
59} // end anonymous namespace
60
61// Classify VT as either 32 or 64 bit.
62static bool is32Bit(EVT VT) {
63 switch (VT.getSimpleVT().SimpleTy) {
64 case MVT::i32:
65 return true;
66 case MVT::i64:
67 return false;
68 default:
69 llvm_unreachable("Unsupported type");
70 }
71}
72
73// Return a version of MachineOperand that can be safely used before the
74// final use.
76 if (Op.isReg())
77 Op.setIsKill(false);
78 return Op;
79}
80
82 const SystemZSubtarget &STI)
83 : TargetLowering(TM), Subtarget(STI) {
84 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
85
86 auto *Regs = STI.getSpecialRegisters();
87
88 // Set up the register classes.
89 if (Subtarget.hasHighWord())
90 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
91 else
92 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
93 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
94 if (!useSoftFloat()) {
95 if (Subtarget.hasVector()) {
96 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
97 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
98 } else {
99 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
101 }
102 if (Subtarget.hasVectorEnhancements1())
103 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
104 else
105 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
106
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
111 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
112 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
113 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
114 }
115 }
116
117 // Compute derived properties from the register classes
119
120 // Set up special registers.
121 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
122
123 // TODO: It may be better to default to latency-oriented scheduling, however
124 // LLVM's current latency-oriented scheduler can't handle physreg definitions
125 // such as SystemZ has with CC, so set this to the register-pressure
126 // scheduler, because it can.
128
131
132 // Instructions are strings of 2-byte aligned 2-byte values.
134 // For performance reasons we prefer 16-byte alignment.
136
137 // Handle operations that are handled in a similar way for all types.
138 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
140 ++I) {
142 if (isTypeLegal(VT)) {
143 // Lower SET_CC into an IPM-based sequence.
147
148 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
150
151 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
154 }
155 }
156
157 // Expand jump table branches as address arithmetic followed by an
158 // indirect jump.
160
161 // Expand BRCOND into a BR_CC (see above).
163
164 // Handle integer types.
165 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
167 ++I) {
169 if (isTypeLegal(VT)) {
171
172 // Expand individual DIV and REMs into DIVREMs.
179
180 // Support addition/subtraction with overflow.
183
184 // Support addition/subtraction with carry.
187
188 // Support carry in as value rather than glue.
191
192 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
193 // stores, putting a serialization instruction after the stores.
196
197 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
198 // available, or if the operand is constant.
200
201 // Use POPCNT on z196 and above.
202 if (Subtarget.hasPopulationCount())
204 else
206
207 // No special instructions for these.
210
211 // Use *MUL_LOHI where possible instead of MULH*.
216
217 // Only z196 and above have native support for conversions to unsigned.
218 // On z10, promoting to i64 doesn't generate an inexact condition for
219 // values that are outside the i32 range but in the i64 range, so use
220 // the default expansion.
221 if (!Subtarget.hasFPExtension())
223
224 // Mirror those settings for STRICT_FP_TO_[SU]INT. Note that these all
225 // default to Expand, so need to be modified to Legal where appropriate.
227 if (Subtarget.hasFPExtension())
229
230 // And similarly for STRICT_[SU]INT_TO_FP.
232 if (Subtarget.hasFPExtension())
234 }
235 }
236
237 // Type legalization will convert 8- and 16-bit atomic operations into
238 // forms that operate on i32s (but still keeping the original memory VT).
239 // Lower them into full i32 operations.
251
252 // Even though i128 is not a legal type, we still need to custom lower
253 // the atomic operations in order to exploit SystemZ instructions.
256
257 // We can use the CC result of compare-and-swap to implement
258 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
262
264
265 // Traps are legal, as we will convert them to "j .+2".
267
268 // z10 has instructions for signed but not unsigned FP conversion.
269 // Handle unsigned 32-bit types as signed 64-bit types.
270 if (!Subtarget.hasFPExtension()) {
275 }
276
277 // We have native support for a 64-bit CTLZ, via FLOGR.
281
282 // On z15 we have native support for a 64-bit CTPOP.
283 if (Subtarget.hasMiscellaneousExtensions3()) {
286 }
287
288 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
290
291 // Expand 128 bit shifts without using a libcall.
295 setLibcallName(RTLIB::SRL_I128, nullptr);
296 setLibcallName(RTLIB::SHL_I128, nullptr);
297 setLibcallName(RTLIB::SRA_I128, nullptr);
298
299 // Handle bitcast from fp128 to i128.
301
302 // We have native instructions for i8, i16 and i32 extensions, but not i1.
304 for (MVT VT : MVT::integer_valuetypes()) {
308 }
309
310 // Handle the various types of symbolic address.
316
317 // We need to handle dynamic allocations specially because of the
318 // 160-byte area at the bottom of the stack.
321
324
325 // Handle prefetches with PFD or PFDRL.
327
329 // Assume by default that all vector operations need to be expanded.
330 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
331 if (getOperationAction(Opcode, VT) == Legal)
332 setOperationAction(Opcode, VT, Expand);
333
334 // Likewise all truncating stores and extending loads.
335 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
336 setTruncStoreAction(VT, InnerVT, Expand);
339 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
340 }
341
342 if (isTypeLegal(VT)) {
343 // These operations are legal for anything that can be stored in a
344 // vector register, even if there is no native support for the format
345 // as such. In particular, we can do these for v4f32 even though there
346 // are no specific instructions for that format.
352
353 // Likewise, except that we need to replace the nodes with something
354 // more specific.
357 }
358 }
359
360 // Handle integer vector types.
362 if (isTypeLegal(VT)) {
363 // These operations have direct equivalents.
368 if (VT != MVT::v2i64)
374 if (Subtarget.hasVectorEnhancements1())
376 else
380
381 // Convert a GPR scalar to a vector by inserting it into element 0.
383
384 // Use a series of unpacks for extensions.
387
388 // Detect shifts by a scalar amount and convert them into
389 // V*_BY_SCALAR.
393
394 // At present ROTL isn't matched by DAGCombiner. ROTR should be
395 // converted into ROTL.
398
399 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
400 // and inverting the result as necessary.
403 if (Subtarget.hasVectorEnhancements1())
405 }
406 }
407
408 if (Subtarget.hasVector()) {
409 // There should be no need to check for float types other than v2f64
410 // since <2 x f32> isn't a legal type.
419
428 }
429
430 if (Subtarget.hasVectorEnhancements2()) {
439
448 }
449
450 // Handle floating-point types.
451 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
453 ++I) {
455 if (isTypeLegal(VT)) {
456 // We can use FI for FRINT.
458
459 // We can use the extended form of FI for other rounding operations.
460 if (Subtarget.hasFPExtension()) {
466 }
467
468 // No special instructions for these.
474
475 // Special treatment.
477
478 // Handle constrained floating-point operations.
488 if (Subtarget.hasFPExtension()) {
494 }
495 }
496 }
497
498 // Handle floating-point vector types.
499 if (Subtarget.hasVector()) {
500 // Scalar-to-vector conversion is just a subreg.
503
504 // Some insertions and extractions can be done directly but others
505 // need to go via integers.
510
511 // These operations have direct equivalents.
526
527 // Handle constrained floating-point operations.
540 }
541
542 // The vector enhancements facility 1 has instructions for these.
543 if (Subtarget.hasVectorEnhancements1()) {
558
563
568
573
578
583
584 // Handle constrained floating-point operations.
597 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
603 }
604 }
605
606 // We only have fused f128 multiply-addition on vector registers.
607 if (!Subtarget.hasVectorEnhancements1()) {
610 }
611
612 // We don't have a copysign instruction on vector registers.
613 if (Subtarget.hasVectorEnhancements1())
615
616 // Needed so that we don't try to implement f128 constant loads using
617 // a load-and-extend of a f80 constant (in cases where the constant
618 // would fit in an f80).
619 for (MVT VT : MVT::fp_valuetypes())
621
622 // We don't have extending load instruction on vector registers.
623 if (Subtarget.hasVectorEnhancements1()) {
626 }
627
628 // Floating-point truncation and stores need to be done separately.
632
633 // We have 64-bit FPR<->GPR moves, but need special handling for
634 // 32-bit forms.
635 if (!Subtarget.hasVector()) {
638 }
639
640 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
641 // structure, but VAEND is a no-op.
645
647
648 // Codes for which we want to perform some z-specific combinations.
652 ISD::LOAD,
663 ISD::SDIV,
664 ISD::UDIV,
665 ISD::SREM,
666 ISD::UREM,
669
670 // Handle intrinsics.
673
674 // We want to use MVC in preference to even a single load/store pair.
675 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
677
678 // The main memset sequence is a byte store followed by an MVC.
679 // Two STC or MV..I stores win over that, but the kind of fused stores
680 // generated by target-independent code don't when the byte value is
681 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
682 // than "STC;MVC". Handle the choice in target-specific code instead.
683 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
685
686 // Default to having -disable-strictnode-mutation on
687 IsStrictFPEnabled = true;
688}
689
691 return Subtarget.hasSoftFloat();
692}
693
695 LLVMContext &, EVT VT) const {
696 if (!VT.isVector())
697 return MVT::i32;
699}
700
702 const MachineFunction &MF, EVT VT) const {
703 VT = VT.getScalarType();
704
705 if (!VT.isSimple())
706 return false;
707
708 switch (VT.getSimpleVT().SimpleTy) {
709 case MVT::f32:
710 case MVT::f64:
711 return true;
712 case MVT::f128:
713 return Subtarget.hasVectorEnhancements1();
714 default:
715 break;
716 }
717
718 return false;
719}
720
721// Return true if the constant can be generated with a vector instruction,
722// such as VGM, VGMB or VREPI.
724 const SystemZSubtarget &Subtarget) {
725 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
726 if (!Subtarget.hasVector() ||
727 (isFP128 && !Subtarget.hasVectorEnhancements1()))
728 return false;
729
730 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
731 // preferred way of creating all-zero and all-one vectors so give it
732 // priority over other methods below.
733 unsigned Mask = 0;
734 unsigned I = 0;
735 for (; I < SystemZ::VectorBytes; ++I) {
736 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
737 if (Byte == 0xff)
738 Mask |= 1ULL << I;
739 else if (Byte != 0)
740 break;
741 }
742 if (I == SystemZ::VectorBytes) {
744 OpVals.push_back(Mask);
746 return true;
747 }
748
749 if (SplatBitSize > 64)
750 return false;
751
752 auto tryValue = [&](uint64_t Value) -> bool {
753 // Try VECTOR REPLICATE IMMEDIATE
754 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
755 if (isInt<16>(SignedValue)) {
756 OpVals.push_back(((unsigned) SignedValue));
759 SystemZ::VectorBits / SplatBitSize);
760 return true;
761 }
762 // Try VECTOR GENERATE MASK
763 unsigned Start, End;
764 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
765 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
766 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
767 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
768 OpVals.push_back(Start - (64 - SplatBitSize));
769 OpVals.push_back(End - (64 - SplatBitSize));
772 SystemZ::VectorBits / SplatBitSize);
773 return true;
774 }
775 return false;
776 };
777
778 // First try assuming that any undefined bits above the highest set bit
779 // and below the lowest set bit are 1s. This increases the likelihood of
780 // being able to use a sign-extended element value in VECTOR REPLICATE
781 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
782 uint64_t SplatBitsZ = SplatBits.getZExtValue();
783 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
784 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
785 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
786 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
787 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
788 if (tryValue(SplatBitsZ | Upper | Lower))
789 return true;
790
791 // Now try assuming that any undefined bits between the first and
792 // last defined set bits are set. This increases the chances of
793 // using a non-wraparound mask.
794 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
795 return tryValue(SplatBitsZ | Middle);
796}
797
799 if (IntImm.isSingleWord()) {
800 IntBits = APInt(128, IntImm.getZExtValue());
801 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
802 } else
803 IntBits = IntImm;
804 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
805
806 // Find the smallest splat.
807 SplatBits = IntImm;
808 unsigned Width = SplatBits.getBitWidth();
809 while (Width > 8) {
810 unsigned HalfSize = Width / 2;
811 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
812 APInt LowValue = SplatBits.trunc(HalfSize);
813
814 // If the two halves do not match, stop here.
815 if (HighValue != LowValue || 8 > HalfSize)
816 break;
817
818 SplatBits = HighValue;
819 Width = HalfSize;
820 }
821 SplatUndef = 0;
822 SplatBitSize = Width;
823}
824
826 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
827 bool HasAnyUndefs;
828
829 // Get IntBits by finding the 128 bit splat.
830 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
831 true);
832
833 // Get SplatBits by finding the 8 bit or greater splat.
834 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
835 true);
836}
837
839 bool ForCodeSize) const {
840 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
841 if (Imm.isZero() || Imm.isNegZero())
842 return true;
843
845}
846
847/// Returns true if stack probing through inline assembly is requested.
849 // If the function specifically requests inline stack probes, emit them.
850 if (MF.getFunction().hasFnAttribute("probe-stack"))
851 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
852 "inline-asm";
853 return false;
854}
855
857 // We can use CGFI or CLGFI.
858 return isInt<32>(Imm) || isUInt<32>(Imm);
859}
860
862 // We can use ALGFI or SLGFI.
863 return isUInt<32>(Imm) || isUInt<32>(-Imm);
864}
865
867 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
868 // Unaligned accesses should never be slower than the expanded version.
869 // We check specifically for aligned accesses in the few cases where
870 // they are required.
871 if (Fast)
872 *Fast = 1;
873 return true;
874}
875
876// Information about the addressing mode for a memory access.
878 // True if a long displacement is supported.
880
881 // True if use of index register is supported.
883
884 AddressingMode(bool LongDispl, bool IdxReg) :
885 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
886};
887
888// Return the desired addressing mode for a Load which has only one use (in
889// the same block) which is a Store.
891 Type *Ty) {
892 // With vector support a Load->Store combination may be combined to either
893 // an MVC or vector operations and it seems to work best to allow the
894 // vector addressing mode.
895 if (HasVector)
896 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
897
898 // Otherwise only the MVC case is special.
899 bool MVC = Ty->isIntegerTy(8);
900 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
901}
902
903// Return the addressing mode which seems most desirable given an LLVM
904// Instruction pointer.
905static AddressingMode
907 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
908 switch (II->getIntrinsicID()) {
909 default: break;
910 case Intrinsic::memset:
911 case Intrinsic::memmove:
912 case Intrinsic::memcpy:
913 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
914 }
915 }
916
917 if (isa<LoadInst>(I) && I->hasOneUse()) {
918 auto *SingleUser = cast<Instruction>(*I->user_begin());
919 if (SingleUser->getParent() == I->getParent()) {
920 if (isa<ICmpInst>(SingleUser)) {
921 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
922 if (C->getBitWidth() <= 64 &&
923 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
924 // Comparison of memory with 16 bit signed / unsigned immediate
925 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
926 } else if (isa<StoreInst>(SingleUser))
927 // Load->Store
928 return getLoadStoreAddrMode(HasVector, I->getType());
929 }
930 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
931 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
932 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
933 // Load->Store
934 return getLoadStoreAddrMode(HasVector, LoadI->getType());
935 }
936
937 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
938
939 // * Use LDE instead of LE/LEY for z13 to avoid partial register
940 // dependencies (LDE only supports small offsets).
941 // * Utilize the vector registers to hold floating point
942 // values (vector load / store instructions only support small
943 // offsets).
944
945 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
946 I->getOperand(0)->getType());
947 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
948 bool IsVectorAccess = MemAccessTy->isVectorTy();
949
950 // A store of an extracted vector element will be combined into a VSTE type
951 // instruction.
952 if (!IsVectorAccess && isa<StoreInst>(I)) {
953 Value *DataOp = I->getOperand(0);
954 if (isa<ExtractElementInst>(DataOp))
955 IsVectorAccess = true;
956 }
957
958 // A load which gets inserted into a vector element will be combined into a
959 // VLE type instruction.
960 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
961 User *LoadUser = *I->user_begin();
962 if (isa<InsertElementInst>(LoadUser))
963 IsVectorAccess = true;
964 }
965
966 if (IsFPAccess || IsVectorAccess)
967 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
968 }
969
970 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
971}
972
974 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
975 // Punt on globals for now, although they can be used in limited
976 // RELATIVE LONG cases.
977 if (AM.BaseGV)
978 return false;
979
980 // Require a 20-bit signed offset.
981 if (!isInt<20>(AM.BaseOffs))
982 return false;
983
984 bool RequireD12 = Subtarget.hasVector() && Ty->isVectorTy();
985 AddressingMode SupportedAM(!RequireD12, true);
986 if (I != nullptr)
987 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
988
989 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
990 return false;
991
992 if (!SupportedAM.IndexReg)
993 // No indexing allowed.
994 return AM.Scale == 0;
995 else
996 // Indexing is OK but no scale factor can be applied.
997 return AM.Scale == 0 || AM.Scale == 1;
998}
999
1001 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
1002 unsigned SrcAS, const AttributeList &FuncAttributes) const {
1003 const int MVCFastLen = 16;
1004
1005 if (Limit != ~unsigned(0)) {
1006 // Don't expand Op into scalar loads/stores in these cases:
1007 if (Op.isMemcpy() && Op.allowOverlap() && Op.size() <= MVCFastLen)
1008 return false; // Small memcpy: Use MVC
1009 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1010 return false; // Small memset (first byte with STC/MVI): Use MVC
1011 if (Op.isZeroMemset())
1012 return false; // Memset zero: Use XC
1013 }
1014
1015 return TargetLowering::findOptimalMemOpLowering(MemOps, Limit, Op, DstAS,
1016 SrcAS, FuncAttributes);
1017}
1018
1020 const AttributeList &FuncAttributes) const {
1021 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1022}
1023
1024bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1025 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1026 return false;
1027 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1028 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1029 return FromBits > ToBits;
1030}
1031
1033 if (!FromVT.isInteger() || !ToVT.isInteger())
1034 return false;
1035 unsigned FromBits = FromVT.getFixedSizeInBits();
1036 unsigned ToBits = ToVT.getFixedSizeInBits();
1037 return FromBits > ToBits;
1038}
1039
1040//===----------------------------------------------------------------------===//
1041// Inline asm support
1042//===----------------------------------------------------------------------===//
1043
1046 if (Constraint.size() == 1) {
1047 switch (Constraint[0]) {
1048 case 'a': // Address register
1049 case 'd': // Data register (equivalent to 'r')
1050 case 'f': // Floating-point register
1051 case 'h': // High-part register
1052 case 'r': // General-purpose register
1053 case 'v': // Vector register
1054 return C_RegisterClass;
1055
1056 case 'Q': // Memory with base and unsigned 12-bit displacement
1057 case 'R': // Likewise, plus an index
1058 case 'S': // Memory with base and signed 20-bit displacement
1059 case 'T': // Likewise, plus an index
1060 case 'm': // Equivalent to 'T'.
1061 return C_Memory;
1062
1063 case 'I': // Unsigned 8-bit constant
1064 case 'J': // Unsigned 12-bit constant
1065 case 'K': // Signed 16-bit constant
1066 case 'L': // Signed 20-bit displacement (on all targets we support)
1067 case 'M': // 0x7fffffff
1068 return C_Immediate;
1069
1070 default:
1071 break;
1072 }
1073 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1074 switch (Constraint[1]) {
1075 case 'Q': // Address with base and unsigned 12-bit displacement
1076 case 'R': // Likewise, plus an index
1077 case 'S': // Address with base and signed 20-bit displacement
1078 case 'T': // Likewise, plus an index
1079 return C_Address;
1080
1081 default:
1082 break;
1083 }
1084 }
1085 return TargetLowering::getConstraintType(Constraint);
1086}
1087
1090 const char *constraint) const {
1092 Value *CallOperandVal = info.CallOperandVal;
1093 // If we don't have a value, we can't do a match,
1094 // but allow it at the lowest weight.
1095 if (!CallOperandVal)
1096 return CW_Default;
1097 Type *type = CallOperandVal->getType();
1098 // Look at the constraint type.
1099 switch (*constraint) {
1100 default:
1102 break;
1103
1104 case 'a': // Address register
1105 case 'd': // Data register (equivalent to 'r')
1106 case 'h': // High-part register
1107 case 'r': // General-purpose register
1108 if (CallOperandVal->getType()->isIntegerTy())
1109 weight = CW_Register;
1110 break;
1111
1112 case 'f': // Floating-point register
1113 if (type->isFloatingPointTy())
1114 weight = CW_Register;
1115 break;
1116
1117 case 'v': // Vector register
1118 if ((type->isVectorTy() || type->isFloatingPointTy()) &&
1119 Subtarget.hasVector())
1120 weight = CW_Register;
1121 break;
1122
1123 case 'I': // Unsigned 8-bit constant
1124 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1125 if (isUInt<8>(C->getZExtValue()))
1126 weight = CW_Constant;
1127 break;
1128
1129 case 'J': // Unsigned 12-bit constant
1130 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1131 if (isUInt<12>(C->getZExtValue()))
1132 weight = CW_Constant;
1133 break;
1134
1135 case 'K': // Signed 16-bit constant
1136 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1137 if (isInt<16>(C->getSExtValue()))
1138 weight = CW_Constant;
1139 break;
1140
1141 case 'L': // Signed 20-bit displacement (on all targets we support)
1142 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1143 if (isInt<20>(C->getSExtValue()))
1144 weight = CW_Constant;
1145 break;
1146
1147 case 'M': // 0x7fffffff
1148 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1149 if (C->getZExtValue() == 0x7fffffff)
1150 weight = CW_Constant;
1151 break;
1152 }
1153 return weight;
1154}
1155
1156// Parse a "{tNNN}" register constraint for which the register type "t"
1157// has already been verified. MC is the class associated with "t" and
1158// Map maps 0-based register numbers to LLVM register numbers.
1159static std::pair<unsigned, const TargetRegisterClass *>
1161 const unsigned *Map, unsigned Size) {
1162 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1163 if (isdigit(Constraint[2])) {
1164 unsigned Index;
1165 bool Failed =
1166 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1167 if (!Failed && Index < Size && Map[Index])
1168 return std::make_pair(Map[Index], RC);
1169 }
1170 return std::make_pair(0U, nullptr);
1171}
1172
1173std::pair<unsigned, const TargetRegisterClass *>
1175 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1176 if (Constraint.size() == 1) {
1177 // GCC Constraint Letters
1178 switch (Constraint[0]) {
1179 default: break;
1180 case 'd': // Data register (equivalent to 'r')
1181 case 'r': // General-purpose register
1182 if (VT == MVT::i64)
1183 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1184 else if (VT == MVT::i128)
1185 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1186 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1187
1188 case 'a': // Address register
1189 if (VT == MVT::i64)
1190 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1191 else if (VT == MVT::i128)
1192 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1193 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1194
1195 case 'h': // High-part register (an LLVM extension)
1196 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1197
1198 case 'f': // Floating-point register
1199 if (!useSoftFloat()) {
1200 if (VT == MVT::f64)
1201 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1202 else if (VT == MVT::f128)
1203 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1204 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1205 }
1206 break;
1207 case 'v': // Vector register
1208 if (Subtarget.hasVector()) {
1209 if (VT == MVT::f32)
1210 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1211 if (VT == MVT::f64)
1212 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1213 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1214 }
1215 break;
1216 }
1217 }
1218 if (Constraint.size() > 0 && Constraint[0] == '{') {
1219 // We need to override the default register parsing for GPRs and FPRs
1220 // because the interpretation depends on VT. The internal names of
1221 // the registers are also different from the external names
1222 // (F0D and F0S instead of F0, etc.).
1223 if (Constraint[1] == 'r') {
1224 if (VT == MVT::i32)
1225 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1227 if (VT == MVT::i128)
1228 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1230 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1232 }
1233 if (Constraint[1] == 'f') {
1234 if (useSoftFloat())
1235 return std::make_pair(
1236 0u, static_cast<const TargetRegisterClass *>(nullptr));
1237 if (VT == MVT::f32)
1238 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1240 if (VT == MVT::f128)
1241 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1243 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1245 }
1246 if (Constraint[1] == 'v') {
1247 if (!Subtarget.hasVector())
1248 return std::make_pair(
1249 0u, static_cast<const TargetRegisterClass *>(nullptr));
1250 if (VT == MVT::f32)
1251 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1253 if (VT == MVT::f64)
1254 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1256 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1258 }
1259 }
1260 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1261}
1262
1263// FIXME? Maybe this could be a TableGen attribute on some registers and
1264// this table could be generated automatically from RegInfo.
1267 const MachineFunction &MF) const {
1268 Register Reg =
1270 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D : 0)
1271 .Case("r15", Subtarget.isTargetELF() ? SystemZ::R15D : 0)
1272 .Default(0);
1273
1274 if (Reg)
1275 return Reg;
1276 report_fatal_error("Invalid register name global variable");
1277}
1278
1280LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1281 std::vector<SDValue> &Ops,
1282 SelectionDAG &DAG) const {
1283 // Only support length 1 constraints for now.
1284 if (Constraint.length() == 1) {
1285 switch (Constraint[0]) {
1286 case 'I': // Unsigned 8-bit constant
1287 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1288 if (isUInt<8>(C->getZExtValue()))
1289 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1290 Op.getValueType()));
1291 return;
1292
1293 case 'J': // Unsigned 12-bit constant
1294 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1295 if (isUInt<12>(C->getZExtValue()))
1296 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1297 Op.getValueType()));
1298 return;
1299
1300 case 'K': // Signed 16-bit constant
1301 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1302 if (isInt<16>(C->getSExtValue()))
1303 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1304 Op.getValueType()));
1305 return;
1306
1307 case 'L': // Signed 20-bit displacement (on all targets we support)
1308 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1309 if (isInt<20>(C->getSExtValue()))
1310 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1311 Op.getValueType()));
1312 return;
1313
1314 case 'M': // 0x7fffffff
1315 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1316 if (C->getZExtValue() == 0x7fffffff)
1317 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1318 Op.getValueType()));
1319 return;
1320 }
1321 }
1322 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1323}
1324
1325//===----------------------------------------------------------------------===//
1326// Calling conventions
1327//===----------------------------------------------------------------------===//
1328
1329#include "SystemZGenCallingConv.inc"
1330
1332 CallingConv::ID) const {
1333 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1334 SystemZ::R14D, 0 };
1335 return ScratchRegs;
1336}
1337
1339 Type *ToType) const {
1340 return isTruncateFree(FromType, ToType);
1341}
1342
1344 return CI->isTailCall();
1345}
1346
1347// We do not yet support 128-bit single-element vector types. If the user
1348// attempts to use such types as function argument or return type, prefer
1349// to error out instead of emitting code violating the ABI.
1350static void VerifyVectorType(MVT VT, EVT ArgVT) {
1351 if (ArgVT.isVector() && !VT.isVector())
1352 report_fatal_error("Unsupported vector argument or return type");
1353}
1354
1356 for (unsigned i = 0; i < Ins.size(); ++i)
1357 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
1358}
1359
1361 for (unsigned i = 0; i < Outs.size(); ++i)
1362 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
1363}
1364
1365// Value is a value that has been passed to us in the location described by VA
1366// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1367// any loads onto Chain.
1369 CCValAssign &VA, SDValue Chain,
1370 SDValue Value) {
1371 // If the argument has been promoted from a smaller type, insert an
1372 // assertion to capture this.
1373 if (VA.getLocInfo() == CCValAssign::SExt)
1375 DAG.getValueType(VA.getValVT()));
1376 else if (VA.getLocInfo() == CCValAssign::ZExt)
1378 DAG.getValueType(VA.getValVT()));
1379
1380 if (VA.isExtInLoc())
1381 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1382 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1383 // If this is a short vector argument loaded from the stack,
1384 // extend from i64 to full vector size and then bitcast.
1385 assert(VA.getLocVT() == MVT::i64);
1386 assert(VA.getValVT().isVector());
1388 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1389 } else
1390 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1391 return Value;
1392}
1393
1394// Value is a value of type VA.getValVT() that we need to copy into
1395// the location described by VA. Return a copy of Value converted to
1396// VA.getValVT(). The caller is responsible for handling indirect values.
1398 CCValAssign &VA, SDValue Value) {
1399 switch (VA.getLocInfo()) {
1400 case CCValAssign::SExt:
1401 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1402 case CCValAssign::ZExt:
1403 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1404 case CCValAssign::AExt:
1405 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1406 case CCValAssign::BCvt: {
1407 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
1408 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
1409 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
1410 // For an f32 vararg we need to first promote it to an f64 and then
1411 // bitcast it to an i64.
1412 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
1414 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
1415 ? MVT::v2i64
1416 : VA.getLocVT();
1417 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
1418 // For ELF, this is a short vector argument to be stored to the stack,
1419 // bitcast to v2i64 and then extract first element.
1420 if (BitCastToType == MVT::v2i64)
1421 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1422 DAG.getConstant(0, DL, MVT::i32));
1423 return Value;
1424 }
1425 case CCValAssign::Full:
1426 return Value;
1427 default:
1428 llvm_unreachable("Unhandled getLocInfo()");
1429 }
1430}
1431
1433 SDLoc DL(In);
1435 DAG.getIntPtrConstant(0, DL));
1437 DAG.getIntPtrConstant(1, DL));
1438 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
1439 MVT::Untyped, Hi, Lo);
1440 return SDValue(Pair, 0);
1441}
1442
1444 SDLoc DL(In);
1445 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
1446 DL, MVT::i64, In);
1447 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
1448 DL, MVT::i64, In);
1449 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
1450}
1451
1453 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
1454 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
1455 EVT ValueVT = Val.getValueType();
1456 assert((ValueVT != MVT::i128 ||
1457 ((NumParts == 1 && PartVT == MVT::Untyped) ||
1458 (NumParts == 2 && PartVT == MVT::i64))) &&
1459 "Unknown handling of i128 value.");
1460 if (ValueVT == MVT::i128 && NumParts == 1) {
1461 // Inline assembly operand.
1462 Parts[0] = lowerI128ToGR128(DAG, Val);
1463 return true;
1464 }
1465 return false;
1466}
1467
1469 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
1470 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
1471 assert((ValueVT != MVT::i128 ||
1472 ((NumParts == 1 && PartVT == MVT::Untyped) ||
1473 (NumParts == 2 && PartVT == MVT::i64))) &&
1474 "Unknown handling of i128 value.");
1475 if (ValueVT == MVT::i128 && NumParts == 1)
1476 // Inline assembly operand.
1477 return lowerGR128ToI128(DAG, Parts[0]);
1478 return SDValue();
1479}
1480
1482 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1483 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1484 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1486 MachineFrameInfo &MFI = MF.getFrameInfo();
1488 SystemZMachineFunctionInfo *FuncInfo =
1490 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
1491 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1492
1493 // Detect unsupported vector argument types.
1494 if (Subtarget.hasVector())
1495 VerifyVectorTypes(Ins);
1496
1497 // Assign locations to all of the incoming arguments.
1499 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1500 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1501
1502 unsigned NumFixedGPRs = 0;
1503 unsigned NumFixedFPRs = 0;
1504 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1505 SDValue ArgValue;
1506 CCValAssign &VA = ArgLocs[I];
1507 EVT LocVT = VA.getLocVT();
1508 if (VA.isRegLoc()) {
1509 // Arguments passed in registers
1510 const TargetRegisterClass *RC;
1511 switch (LocVT.getSimpleVT().SimpleTy) {
1512 default:
1513 // Integers smaller than i64 should be promoted to i64.
1514 llvm_unreachable("Unexpected argument type");
1515 case MVT::i32:
1516 NumFixedGPRs += 1;
1517 RC = &SystemZ::GR32BitRegClass;
1518 break;
1519 case MVT::i64:
1520 NumFixedGPRs += 1;
1521 RC = &SystemZ::GR64BitRegClass;
1522 break;
1523 case MVT::f32:
1524 NumFixedFPRs += 1;
1525 RC = &SystemZ::FP32BitRegClass;
1526 break;
1527 case MVT::f64:
1528 NumFixedFPRs += 1;
1529 RC = &SystemZ::FP64BitRegClass;
1530 break;
1531 case MVT::f128:
1532 NumFixedFPRs += 2;
1533 RC = &SystemZ::FP128BitRegClass;
1534 break;
1535 case MVT::v16i8:
1536 case MVT::v8i16:
1537 case MVT::v4i32:
1538 case MVT::v2i64:
1539 case MVT::v4f32:
1540 case MVT::v2f64:
1541 RC = &SystemZ::VR128BitRegClass;
1542 break;
1543 }
1544
1545 Register VReg = MRI.createVirtualRegister(RC);
1546 MRI.addLiveIn(VA.getLocReg(), VReg);
1547 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1548 } else {
1549 assert(VA.isMemLoc() && "Argument not register or memory");
1550
1551 // Create the frame index object for this incoming parameter.
1552 // FIXME: Pre-include call frame size in the offset, should not
1553 // need to manually add it here.
1554 int64_t ArgSPOffset = VA.getLocMemOffset();
1555 if (Subtarget.isTargetXPLINK64()) {
1556 auto &XPRegs =
1558 ArgSPOffset += XPRegs.getCallFrameSize();
1559 }
1560 int FI =
1561 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
1562
1563 // Create the SelectionDAG nodes corresponding to a load
1564 // from this parameter. Unpromoted ints and floats are
1565 // passed as right-justified 8-byte values.
1566 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1567 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1568 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1569 DAG.getIntPtrConstant(4, DL));
1570 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1572 }
1573
1574 // Convert the value of the argument register into the value that's
1575 // being passed.
1576 if (VA.getLocInfo() == CCValAssign::Indirect) {
1577 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1579 // If the original argument was split (e.g. i128), we need
1580 // to load all parts of it here (using the same address).
1581 unsigned ArgIndex = Ins[I].OrigArgIndex;
1582 assert (Ins[I].PartOffset == 0);
1583 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1584 CCValAssign &PartVA = ArgLocs[I + 1];
1585 unsigned PartOffset = Ins[I + 1].PartOffset;
1586 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1587 DAG.getIntPtrConstant(PartOffset, DL));
1588 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1590 ++I;
1591 }
1592 } else
1593 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1594 }
1595
1596 // FIXME: Add support for lowering varargs for XPLINK64 in a later patch.
1597 if (IsVarArg && Subtarget.isTargetELF()) {
1598 // Save the number of non-varargs registers for later use by va_start, etc.
1599 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1600 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1601
1602 // Likewise the address (in the form of a frame index) of where the
1603 // first stack vararg would be. The 1-byte size here is arbitrary.
1604 int64_t StackSize = CCInfo.getNextStackOffset();
1605 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1606
1607 // ...and a similar frame index for the caller-allocated save area
1608 // that will be used to store the incoming registers.
1609 int64_t RegSaveOffset =
1610 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
1611 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1612 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1613
1614 // Store the FPR varargs in the reserved frame slots. (We store the
1615 // GPRs as part of the prologue.)
1616 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
1618 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
1619 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
1620 int FI =
1622 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1624 &SystemZ::FP64BitRegClass);
1625 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1626 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1628 }
1629 // Join the stores, which are independent of one another.
1630 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1631 ArrayRef(&MemOps[NumFixedFPRs],
1632 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
1633 }
1634 }
1635
1636 // FIXME: For XPLINK64, Add in support for handling incoming "ADA" special
1637 // register (R5)
1638 return Chain;
1639}
1640
1641static bool canUseSiblingCall(const CCState &ArgCCInfo,
1644 // Punt if there are any indirect or stack arguments, or if the call
1645 // needs the callee-saved argument register R6, or if the call uses
1646 // the callee-saved register arguments SwiftSelf and SwiftError.
1647 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1648 CCValAssign &VA = ArgLocs[I];
1650 return false;
1651 if (!VA.isRegLoc())
1652 return false;
1653 Register Reg = VA.getLocReg();
1654 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1655 return false;
1656 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1657 return false;
1658 }
1659 return true;
1660}
1661
1662SDValue
1664 SmallVectorImpl<SDValue> &InVals) const {
1665 SelectionDAG &DAG = CLI.DAG;
1666 SDLoc &DL = CLI.DL;
1668 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1670 SDValue Chain = CLI.Chain;
1671 SDValue Callee = CLI.Callee;
1672 bool &IsTailCall = CLI.IsTailCall;
1673 CallingConv::ID CallConv = CLI.CallConv;
1674 bool IsVarArg = CLI.IsVarArg;
1676 EVT PtrVT = getPointerTy(MF.getDataLayout());
1677 LLVMContext &Ctx = *DAG.getContext();
1679
1680 // FIXME: z/OS support to be added in later.
1681 if (Subtarget.isTargetXPLINK64())
1682 IsTailCall = false;
1683
1684 // Detect unsupported vector argument and return types.
1685 if (Subtarget.hasVector()) {
1686 VerifyVectorTypes(Outs);
1687 VerifyVectorTypes(Ins);
1688 }
1689
1690 // Analyze the operands of the call, assigning locations to each operand.
1692 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
1693 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1694
1695 // We don't support GuaranteedTailCallOpt, only automatically-detected
1696 // sibling calls.
1697 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1698 IsTailCall = false;
1699
1700 // Get a count of how many bytes are to be pushed on the stack.
1701 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1702
1703 if (Subtarget.isTargetXPLINK64())
1704 // Although the XPLINK specifications for AMODE64 state that minimum size
1705 // of the param area is minimum 32 bytes and no rounding is otherwise
1706 // specified, we round this area in 64 bytes increments to be compatible
1707 // with existing compilers.
1708 NumBytes = std::max(64U, (unsigned)alignTo(NumBytes, 64));
1709
1710 // Mark the start of the call.
1711 if (!IsTailCall)
1712 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1713
1714 // Copy argument values to their designated locations.
1716 SmallVector<SDValue, 8> MemOpChains;
1717 SDValue StackPtr;
1718 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1719 CCValAssign &VA = ArgLocs[I];
1720 SDValue ArgValue = OutVals[I];
1721
1722 if (VA.getLocInfo() == CCValAssign::Indirect) {
1723 // Store the argument in a stack slot and pass its address.
1724 unsigned ArgIndex = Outs[I].OrigArgIndex;
1725 EVT SlotVT;
1726 if (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1727 // Allocate the full stack space for a promoted (and split) argument.
1728 Type *OrigArgType = CLI.Args[Outs[I].OrigArgIndex].Ty;
1729 EVT OrigArgVT = getValueType(MF.getDataLayout(), OrigArgType);
1730 MVT PartVT = getRegisterTypeForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
1731 unsigned N = getNumRegistersForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
1732 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * N);
1733 } else {
1734 SlotVT = Outs[I].ArgVT;
1735 }
1736 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
1737 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1738 MemOpChains.push_back(
1739 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1741 // If the original argument was split (e.g. i128), we need
1742 // to store all parts of it here (and pass just one address).
1743 assert (Outs[I].PartOffset == 0);
1744 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1745 SDValue PartValue = OutVals[I + 1];
1746 unsigned PartOffset = Outs[I + 1].PartOffset;
1747 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1748 DAG.getIntPtrConstant(PartOffset, DL));
1749 MemOpChains.push_back(
1750 DAG.getStore(Chain, DL, PartValue, Address,
1752 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
1753 SlotVT.getStoreSize()) && "Not enough space for argument part!");
1754 ++I;
1755 }
1756 ArgValue = SpillSlot;
1757 } else
1758 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1759
1760 if (VA.isRegLoc()) {
1761 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
1762 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
1763 // and low values.
1764 if (VA.getLocVT() == MVT::i128)
1765 ArgValue = lowerI128ToGR128(DAG, ArgValue);
1766 // Queue up the argument copies and emit them at the end.
1767 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1768 } else {
1769 assert(VA.isMemLoc() && "Argument not register or memory");
1770
1771 // Work out the address of the stack slot. Unpromoted ints and
1772 // floats are passed as right-justified 8-byte values.
1773 if (!StackPtr.getNode())
1774 StackPtr = DAG.getCopyFromReg(Chain, DL,
1775 Regs->getStackPointerRegister(), PtrVT);
1776 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
1777 VA.getLocMemOffset();
1778 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1779 Offset += 4;
1780 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1782
1783 // Emit the store.
1784 MemOpChains.push_back(
1785 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1786
1787 // Although long doubles or vectors are passed through the stack when
1788 // they are vararg (non-fixed arguments), if a long double or vector
1789 // occupies the third and fourth slot of the argument list GPR3 should
1790 // still shadow the third slot of the argument list.
1791 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
1792 SDValue ShadowArgValue =
1793 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
1794 DAG.getIntPtrConstant(1, DL));
1795 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
1796 }
1797 }
1798 }
1799
1800 // Join the stores, which are independent of one another.
1801 if (!MemOpChains.empty())
1802 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1803
1804 // Accept direct calls by converting symbolic call addresses to the
1805 // associated Target* opcodes. Force %r1 to be used for indirect
1806 // tail calls.
1807 SDValue Glue;
1808 // FIXME: Add support for XPLINK using the ADA register.
1809 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1810 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1812 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1813 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1815 } else if (IsTailCall) {
1816 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1817 Glue = Chain.getValue(1);
1818 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1819 }
1820
1821 // Build a sequence of copy-to-reg nodes, chained and glued together.
1822 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1823 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1824 RegsToPass[I].second, Glue);
1825 Glue = Chain.getValue(1);
1826 }
1827
1828 // The first call operand is the chain and the second is the target address.
1830 Ops.push_back(Chain);
1831 Ops.push_back(Callee);
1832
1833 // Add argument registers to the end of the list so that they are
1834 // known live into the call.
1835 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1836 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1837 RegsToPass[I].second.getValueType()));
1838
1839 // Add a register mask operand representing the call-preserved registers.
1840 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1841 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1842 assert(Mask && "Missing call preserved mask for calling convention");
1843 Ops.push_back(DAG.getRegisterMask(Mask));
1844
1845 // Glue the call to the argument copies, if any.
1846 if (Glue.getNode())
1847 Ops.push_back(Glue);
1848
1849 // Emit the call.
1850 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1851 if (IsTailCall)
1852 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1853 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1854 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
1855 Glue = Chain.getValue(1);
1856
1857 // Mark the end of the call, which is glued to the call itself.
1858 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
1859 Glue = Chain.getValue(1);
1860
1861 // Assign locations to each value returned by this call.
1863 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
1864 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1865
1866 // Copy all of the result registers out of their specified physreg.
1867 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1868 CCValAssign &VA = RetLocs[I];
1869
1870 // Copy the value out, gluing the copy to the end of the call sequence.
1871 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1872 VA.getLocVT(), Glue);
1873 Chain = RetValue.getValue(1);
1874 Glue = RetValue.getValue(2);
1875
1876 // Convert the value of the return register into the value that's
1877 // being returned.
1878 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1879 }
1880
1881 return Chain;
1882}
1883
1884// Generate a call taking the given operands as arguments and returning a
1885// result of type RetVT.
1887 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
1888 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
1889 bool DoesNotReturn, bool IsReturnValueUsed) const {
1891 Args.reserve(Ops.size());
1892
1894 for (SDValue Op : Ops) {
1895 Entry.Node = Op;
1896 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1897 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned);
1898 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned);
1899 Args.push_back(Entry);
1900 }
1901
1902 SDValue Callee =
1903 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
1904
1905 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
1907 bool SignExtend = shouldSignExtendTypeInLibCall(RetVT, IsSigned);
1908 CLI.setDebugLoc(DL)
1909 .setChain(Chain)
1910 .setCallee(CallConv, RetTy, Callee, std::move(Args))
1911 .setNoReturn(DoesNotReturn)
1912 .setDiscardResult(!IsReturnValueUsed)
1913 .setSExtResult(SignExtend)
1914 .setZExtResult(!SignExtend);
1915 return LowerCallTo(CLI);
1916}
1917
1920 MachineFunction &MF, bool isVarArg,
1922 LLVMContext &Context) const {
1923 // Detect unsupported vector return types.
1924 if (Subtarget.hasVector())
1925 VerifyVectorTypes(Outs);
1926
1927 // Special case that we cannot easily detect in RetCC_SystemZ since
1928 // i128 is not a legal type.
1929 for (auto &Out : Outs)
1930 if (Out.ArgVT == MVT::i128)
1931 return false;
1932
1934 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1935 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1936}
1937
1938SDValue
1940 bool IsVarArg,
1942 const SmallVectorImpl<SDValue> &OutVals,
1943 const SDLoc &DL, SelectionDAG &DAG) const {
1945
1946 // Detect unsupported vector return types.
1947 if (Subtarget.hasVector())
1948 VerifyVectorTypes(Outs);
1949
1950 // Assign locations to each returned value.
1952 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1953 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1954
1955 // Quick exit for void returns
1956 if (RetLocs.empty())
1957 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1958
1959 if (CallConv == CallingConv::GHC)
1960 report_fatal_error("GHC functions return void only");
1961
1962 // Copy the result values into the output registers.
1963 SDValue Glue;
1965 RetOps.push_back(Chain);
1966 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1967 CCValAssign &VA = RetLocs[I];
1968 SDValue RetValue = OutVals[I];
1969
1970 // Make the return register live on exit.
1971 assert(VA.isRegLoc() && "Can only return in registers!");
1972
1973 // Promote the value as required.
1974 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1975
1976 // Chain and glue the copies together.
1977 Register Reg = VA.getLocReg();
1978 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1979 Glue = Chain.getValue(1);
1980 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1981 }
1982
1983 // Update chain and glue.
1984 RetOps[0] = Chain;
1985 if (Glue.getNode())
1986 RetOps.push_back(Glue);
1987
1988 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1989}
1990
1991// Return true if Op is an intrinsic node with chain that returns the CC value
1992// as its only (other) argument. Provide the associated SystemZISD opcode and
1993// the mask of valid CC values if so.
1994static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1995 unsigned &CCValid) {
1996 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1997 switch (Id) {
1998 case Intrinsic::s390_tbegin:
1999 Opcode = SystemZISD::TBEGIN;
2000 CCValid = SystemZ::CCMASK_TBEGIN;
2001 return true;
2002
2003 case Intrinsic::s390_tbegin_nofloat:
2005 CCValid = SystemZ::CCMASK_TBEGIN;
2006 return true;
2007
2008 case Intrinsic::s390_tend:
2009 Opcode = SystemZISD::TEND;
2010 CCValid = SystemZ::CCMASK_TEND;
2011 return true;
2012
2013 default:
2014 return false;
2015 }
2016}
2017
2018// Return true if Op is an intrinsic node without chain that returns the
2019// CC value as its final argument. Provide the associated SystemZISD
2020// opcode and the mask of valid CC values if so.
2021static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2022 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2023 switch (Id) {
2024 case Intrinsic::s390_vpkshs:
2025 case Intrinsic::s390_vpksfs:
2026 case Intrinsic::s390_vpksgs:
2027 Opcode = SystemZISD::PACKS_CC;
2028 CCValid = SystemZ::CCMASK_VCMP;
2029 return true;
2030
2031 case Intrinsic::s390_vpklshs:
2032 case Intrinsic::s390_vpklsfs:
2033 case Intrinsic::s390_vpklsgs:
2034 Opcode = SystemZISD::PACKLS_CC;
2035 CCValid = SystemZ::CCMASK_VCMP;
2036 return true;
2037
2038 case Intrinsic::s390_vceqbs:
2039 case Intrinsic::s390_vceqhs:
2040 case Intrinsic::s390_vceqfs:
2041 case Intrinsic::s390_vceqgs:
2042 Opcode = SystemZISD::VICMPES;
2043 CCValid = SystemZ::CCMASK_VCMP;
2044 return true;
2045
2046 case Intrinsic::s390_vchbs:
2047 case Intrinsic::s390_vchhs:
2048 case Intrinsic::s390_vchfs:
2049 case Intrinsic::s390_vchgs:
2050 Opcode = SystemZISD::VICMPHS;
2051 CCValid = SystemZ::CCMASK_VCMP;
2052 return true;
2053
2054 case Intrinsic::s390_vchlbs:
2055 case Intrinsic::s390_vchlhs:
2056 case Intrinsic::s390_vchlfs:
2057 case Intrinsic::s390_vchlgs:
2058 Opcode = SystemZISD::VICMPHLS;
2059 CCValid = SystemZ::CCMASK_VCMP;
2060 return true;
2061
2062 case Intrinsic::s390_vtm:
2063 Opcode = SystemZISD::VTM;
2064 CCValid = SystemZ::CCMASK_VCMP;
2065 return true;
2066
2067 case Intrinsic::s390_vfaebs:
2068 case Intrinsic::s390_vfaehs:
2069 case Intrinsic::s390_vfaefs:
2070 Opcode = SystemZISD::VFAE_CC;
2071 CCValid = SystemZ::CCMASK_ANY;
2072 return true;
2073
2074 case Intrinsic::s390_vfaezbs:
2075 case Intrinsic::s390_vfaezhs:
2076 case Intrinsic::s390_vfaezfs:
2077 Opcode = SystemZISD::VFAEZ_CC;
2078 CCValid = SystemZ::CCMASK_ANY;
2079 return true;
2080
2081 case Intrinsic::s390_vfeebs:
2082 case Intrinsic::s390_vfeehs:
2083 case Intrinsic::s390_vfeefs:
2084 Opcode = SystemZISD::VFEE_CC;
2085 CCValid = SystemZ::CCMASK_ANY;
2086 return true;
2087
2088 case Intrinsic::s390_vfeezbs:
2089 case Intrinsic::s390_vfeezhs:
2090 case Intrinsic::s390_vfeezfs:
2091 Opcode = SystemZISD::VFEEZ_CC;
2092 CCValid = SystemZ::CCMASK_ANY;
2093 return true;
2094
2095 case Intrinsic::s390_vfenebs:
2096 case Intrinsic::s390_vfenehs:
2097 case Intrinsic::s390_vfenefs:
2098 Opcode = SystemZISD::VFENE_CC;
2099 CCValid = SystemZ::CCMASK_ANY;
2100 return true;
2101
2102 case Intrinsic::s390_vfenezbs:
2103 case Intrinsic::s390_vfenezhs:
2104 case Intrinsic::s390_vfenezfs:
2105 Opcode = SystemZISD::VFENEZ_CC;
2106 CCValid = SystemZ::CCMASK_ANY;
2107 return true;
2108
2109 case Intrinsic::s390_vistrbs:
2110 case Intrinsic::s390_vistrhs:
2111 case Intrinsic::s390_vistrfs:
2112 Opcode = SystemZISD::VISTR_CC;
2114 return true;
2115
2116 case Intrinsic::s390_vstrcbs:
2117 case Intrinsic::s390_vstrchs:
2118 case Intrinsic::s390_vstrcfs:
2119 Opcode = SystemZISD::VSTRC_CC;
2120 CCValid = SystemZ::CCMASK_ANY;
2121 return true;
2122
2123 case Intrinsic::s390_vstrczbs:
2124 case Intrinsic::s390_vstrczhs:
2125 case Intrinsic::s390_vstrczfs:
2126 Opcode = SystemZISD::VSTRCZ_CC;
2127 CCValid = SystemZ::CCMASK_ANY;
2128 return true;
2129
2130 case Intrinsic::s390_vstrsb:
2131 case Intrinsic::s390_vstrsh:
2132 case Intrinsic::s390_vstrsf:
2133 Opcode = SystemZISD::VSTRS_CC;
2134 CCValid = SystemZ::CCMASK_ANY;
2135 return true;
2136
2137 case Intrinsic::s390_vstrszb:
2138 case Intrinsic::s390_vstrszh:
2139 case Intrinsic::s390_vstrszf:
2140 Opcode = SystemZISD::VSTRSZ_CC;
2141 CCValid = SystemZ::CCMASK_ANY;
2142 return true;
2143
2144 case Intrinsic::s390_vfcedbs:
2145 case Intrinsic::s390_vfcesbs:
2146 Opcode = SystemZISD::VFCMPES;
2147 CCValid = SystemZ::CCMASK_VCMP;
2148 return true;
2149
2150 case Intrinsic::s390_vfchdbs:
2151 case Intrinsic::s390_vfchsbs:
2152 Opcode = SystemZISD::VFCMPHS;
2153 CCValid = SystemZ::CCMASK_VCMP;
2154 return true;
2155
2156 case Intrinsic::s390_vfchedbs:
2157 case Intrinsic::s390_vfchesbs:
2158 Opcode = SystemZISD::VFCMPHES;
2159 CCValid = SystemZ::CCMASK_VCMP;
2160 return true;
2161
2162 case Intrinsic::s390_vftcidb:
2163 case Intrinsic::s390_vftcisb:
2164 Opcode = SystemZISD::VFTCI;
2165 CCValid = SystemZ::CCMASK_VCMP;
2166 return true;
2167
2168 case Intrinsic::s390_tdc:
2169 Opcode = SystemZISD::TDC;
2170 CCValid = SystemZ::CCMASK_TDC;
2171 return true;
2172
2173 default:
2174 return false;
2175 }
2176}
2177
2178// Emit an intrinsic with chain and an explicit CC register result.
2180 unsigned Opcode) {
2181 // Copy all operands except the intrinsic ID.
2182 unsigned NumOps = Op.getNumOperands();
2184 Ops.reserve(NumOps - 1);
2185 Ops.push_back(Op.getOperand(0));
2186 for (unsigned I = 2; I < NumOps; ++I)
2187 Ops.push_back(Op.getOperand(I));
2188
2189 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2190 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2191 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2192 SDValue OldChain = SDValue(Op.getNode(), 1);
2193 SDValue NewChain = SDValue(Intr.getNode(), 1);
2194 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2195 return Intr.getNode();
2196}
2197
2198// Emit an intrinsic with an explicit CC register result.
2200 unsigned Opcode) {
2201 // Copy all operands except the intrinsic ID.
2202 unsigned NumOps = Op.getNumOperands();
2204 Ops.reserve(NumOps - 1);
2205 for (unsigned I = 1; I < NumOps; ++I)
2206 Ops.push_back(Op.getOperand(I));
2207
2208 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
2209 return Intr.getNode();
2210}
2211
2212// CC is a comparison that will be implemented using an integer or
2213// floating-point comparison. Return the condition code mask for
2214// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2215// unsigned comparisons and clear for signed ones. In the floating-point
2216// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2218#define CONV(X) \
2219 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2220 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2221 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2222
2223 switch (CC) {
2224 default:
2225 llvm_unreachable("Invalid integer condition!");
2226
2227 CONV(EQ);
2228 CONV(NE);
2229 CONV(GT);
2230 CONV(GE);
2231 CONV(LT);
2232 CONV(LE);
2233
2234 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2236 }
2237#undef CONV
2238}
2239
2240// If C can be converted to a comparison against zero, adjust the operands
2241// as necessary.
2242static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2243 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2244 return;
2245
2246 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2247 if (!ConstOp1)
2248 return;
2249
2250 int64_t Value = ConstOp1->getSExtValue();
2251 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2252 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2253 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2254 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2255 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2256 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2257 }
2258}
2259
2260// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2261// adjust the operands as necessary.
2262static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2263 Comparison &C) {
2264 // For us to make any changes, it must a comparison between a single-use
2265 // load and a constant.
2266 if (!C.Op0.hasOneUse() ||
2267 C.Op0.getOpcode() != ISD::LOAD ||
2268 C.Op1.getOpcode() != ISD::Constant)
2269 return;
2270
2271 // We must have an 8- or 16-bit load.
2272 auto *Load = cast<LoadSDNode>(C.Op0);
2273 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
2274 if ((NumBits != 8 && NumBits != 16) ||
2275 NumBits != Load->getMemoryVT().getStoreSizeInBits())
2276 return;
2277
2278 // The load must be an extending one and the constant must be within the
2279 // range of the unextended value.
2280 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2281 uint64_t Value = ConstOp1->getZExtValue();
2282 uint64_t Mask = (1 << NumBits) - 1;
2283 if (Load->getExtensionType() == ISD::SEXTLOAD) {
2284 // Make sure that ConstOp1 is in range of C.Op0.
2285 int64_t SignedValue = ConstOp1->getSExtValue();
2286 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2287 return;
2288 if (C.ICmpType != SystemZICMP::SignedOnly) {
2289 // Unsigned comparison between two sign-extended values is equivalent
2290 // to unsigned comparison between two zero-extended values.
2291 Value &= Mask;
2292 } else if (NumBits == 8) {
2293 // Try to treat the comparison as unsigned, so that we can use CLI.
2294 // Adjust CCMask and Value as necessary.
2295 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2296 // Test whether the high bit of the byte is set.
2297 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2298 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2299 // Test whether the high bit of the byte is clear.
2300 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2301 else
2302 // No instruction exists for this combination.
2303 return;
2304 C.ICmpType = SystemZICMP::UnsignedOnly;
2305 }
2306 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2307 if (Value > Mask)
2308 return;
2309 // If the constant is in range, we can use any comparison.
2310 C.ICmpType = SystemZICMP::Any;
2311 } else
2312 return;
2313
2314 // Make sure that the first operand is an i32 of the right extension type.
2315 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2318 if (C.Op0.getValueType() != MVT::i32 ||
2319 Load->getExtensionType() != ExtType) {
2320 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2321 Load->getBasePtr(), Load->getPointerInfo(),
2322 Load->getMemoryVT(), Load->getAlign(),
2323 Load->getMemOperand()->getFlags());
2324 // Update the chain uses.
2325 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
2326 }
2327
2328 // Make sure that the second operand is an i32 with the right value.
2329 if (C.Op1.getValueType() != MVT::i32 ||
2330 Value != ConstOp1->getZExtValue())
2331 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
2332}
2333
2334// Return true if Op is either an unextended load, or a load suitable
2335// for integer register-memory comparisons of type ICmpType.
2336static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
2337 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
2338 if (Load) {
2339 // There are no instructions to compare a register with a memory byte.
2340 if (Load->getMemoryVT() == MVT::i8)
2341 return false;
2342 // Otherwise decide on extension type.
2343 switch (Load->getExtensionType()) {
2344 case ISD::NON_EXTLOAD:
2345 return true;
2346 case ISD::SEXTLOAD:
2347 return ICmpType != SystemZICMP::UnsignedOnly;
2348 case ISD::ZEXTLOAD:
2349 return ICmpType != SystemZICMP::SignedOnly;
2350 default:
2351 break;
2352 }
2353 }
2354 return false;
2355}
2356
2357// Return true if it is better to swap the operands of C.
2358static bool shouldSwapCmpOperands(const Comparison &C) {
2359 // Leave f128 comparisons alone, since they have no memory forms.
2360 if (C.Op0.getValueType() == MVT::f128)
2361 return false;
2362
2363 // Always keep a floating-point constant second, since comparisons with
2364 // zero can use LOAD TEST and comparisons with other constants make a
2365 // natural memory operand.
2366 if (isa<ConstantFPSDNode>(C.Op1))
2367 return false;
2368
2369 // Never swap comparisons with zero since there are many ways to optimize
2370 // those later.
2371 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2372 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
2373 return false;
2374
2375 // Also keep natural memory operands second if the loaded value is
2376 // only used here. Several comparisons have memory forms.
2377 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
2378 return false;
2379
2380 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
2381 // In that case we generally prefer the memory to be second.
2382 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
2383 // The only exceptions are when the second operand is a constant and
2384 // we can use things like CHHSI.
2385 if (!ConstOp1)
2386 return true;
2387 // The unsigned memory-immediate instructions can handle 16-bit
2388 // unsigned integers.
2389 if (C.ICmpType != SystemZICMP::SignedOnly &&
2390 isUInt<16>(ConstOp1->getZExtValue()))
2391 return false;
2392 // The signed memory-immediate instructions can handle 16-bit
2393 // signed integers.
2394 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
2395 isInt<16>(ConstOp1->getSExtValue()))
2396 return false;
2397 return true;
2398 }
2399
2400 // Try to promote the use of CGFR and CLGFR.
2401 unsigned Opcode0 = C.Op0.getOpcode();
2402 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
2403 return true;
2404 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
2405 return true;
2406 if (C.ICmpType != SystemZICMP::SignedOnly &&
2407 Opcode0 == ISD::AND &&
2408 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
2409 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
2410 return true;
2411
2412 return false;
2413}
2414
2415// Check whether C tests for equality between X and Y and whether X - Y
2416// or Y - X is also computed. In that case it's better to compare the
2417// result of the subtraction against zero.
2419 Comparison &C) {
2420 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2421 C.CCMask == SystemZ::CCMASK_CMP_NE) {
2422 for (SDNode *N : C.Op0->uses()) {
2423 if (N->getOpcode() == ISD::SUB &&
2424 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
2425 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
2426 // Disable the nsw and nuw flags: the backend needs to handle
2427 // overflow as well during comparison elimination.
2428 SDNodeFlags Flags = N->getFlags();
2429 Flags.setNoSignedWrap(false);
2430 Flags.setNoUnsignedWrap(false);
2431 N->setFlags(Flags);
2432 C.Op0 = SDValue(N, 0);
2433 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
2434 return;
2435 }
2436 }
2437 }
2438}
2439
2440// Check whether C compares a floating-point value with zero and if that
2441// floating-point value is also negated. In this case we can use the
2442// negation to set CC, so avoiding separate LOAD AND TEST and
2443// LOAD (NEGATIVE/COMPLEMENT) instructions.
2444static void adjustForFNeg(Comparison &C) {
2445 // This optimization is invalid for strict comparisons, since FNEG
2446 // does not raise any exceptions.
2447 if (C.Chain)
2448 return;
2449 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
2450 if (C1 && C1->isZero()) {
2451 for (SDNode *N : C.Op0->uses()) {
2452 if (N->getOpcode() == ISD::FNEG) {
2453 C.Op0 = SDValue(N, 0);
2454 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
2455 return;
2456 }
2457 }
2458 }
2459}
2460
2461// Check whether C compares (shl X, 32) with 0 and whether X is
2462// also sign-extended. In that case it is better to test the result
2463// of the sign extension using LTGFR.
2464//
2465// This case is important because InstCombine transforms a comparison
2466// with (sext (trunc X)) into a comparison with (shl X, 32).
2467static void adjustForLTGFR(Comparison &C) {
2468 // Check for a comparison between (shl X, 32) and 0.
2469 if (C.Op0.getOpcode() == ISD::SHL &&
2470 C.Op0.getValueType() == MVT::i64 &&
2471 C.Op1.getOpcode() == ISD::Constant &&
2472 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2473 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2474 if (C1 && C1->getZExtValue() == 32) {
2475 SDValue ShlOp0 = C.Op0.getOperand(0);
2476 // See whether X has any SIGN_EXTEND_INREG uses.
2477 for (SDNode *N : ShlOp0->uses()) {
2478 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2479 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2480 C.Op0 = SDValue(N, 0);
2481 return;
2482 }
2483 }
2484 }
2485 }
2486}
2487
2488// If C compares the truncation of an extending load, try to compare
2489// the untruncated value instead. This exposes more opportunities to
2490// reuse CC.
2491static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2492 Comparison &C) {
2493 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2494 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2495 C.Op1.getOpcode() == ISD::Constant &&
2496 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2497 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2498 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
2499 C.Op0.getValueSizeInBits().getFixedValue()) {
2500 unsigned Type = L->getExtensionType();
2501 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2502 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2503 C.Op0 = C.Op0.getOperand(0);
2504 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2505 }
2506 }
2507 }
2508}
2509
2510// Return true if shift operation N has an in-range constant shift value.
2511// Store it in ShiftVal if so.
2512static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2513 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2514 if (!Shift)
2515 return false;
2516
2517 uint64_t Amount = Shift->getZExtValue();
2518 if (Amount >= N.getValueSizeInBits())
2519 return false;
2520
2521 ShiftVal = Amount;
2522 return true;
2523}
2524
2525// Check whether an AND with Mask is suitable for a TEST UNDER MASK
2526// instruction and whether the CC value is descriptive enough to handle
2527// a comparison of type Opcode between the AND result and CmpVal.
2528// CCMask says which comparison result is being tested and BitSize is
2529// the number of bits in the operands. If TEST UNDER MASK can be used,
2530// return the corresponding CC mask, otherwise return 0.
2531static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2532 uint64_t Mask, uint64_t CmpVal,
2533 unsigned ICmpType) {
2534 assert(Mask != 0 && "ANDs with zero should have been removed by now");
2535
2536 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2537 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2538 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2539 return 0;
2540
2541 // Work out the masks for the lowest and highest bits.
2543 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
2544
2545 // Signed ordered comparisons are effectively unsigned if the sign
2546 // bit is dropped.
2547 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2548
2549 // Check for equality comparisons with 0, or the equivalent.
2550 if (CmpVal == 0) {
2551 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2553 if (CCMask == SystemZ::CCMASK_CMP_NE)
2555 }
2556 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2557 if (CCMask == SystemZ::CCMASK_CMP_LT)
2559 if (CCMask == SystemZ::CCMASK_CMP_GE)
2561 }
2562 if (EffectivelyUnsigned && CmpVal < Low) {
2563 if (CCMask == SystemZ::CCMASK_CMP_LE)
2565 if (CCMask == SystemZ::CCMASK_CMP_GT)
2567 }
2568
2569 // Check for equality comparisons with the mask, or the equivalent.
2570 if (CmpVal == Mask) {
2571 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2573 if (CCMask == SystemZ::CCMASK_CMP_NE)
2575 }
2576 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2577 if (CCMask == SystemZ::CCMASK_CMP_GT)
2579 if (CCMask == SystemZ::CCMASK_CMP_LE)
2581 }
2582 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2583 if (CCMask == SystemZ::CCMASK_CMP_GE)
2585 if (CCMask == SystemZ::CCMASK_CMP_LT)
2587 }
2588
2589 // Check for ordered comparisons with the top bit.
2590 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2591 if (CCMask == SystemZ::CCMASK_CMP_LE)
2593 if (CCMask == SystemZ::CCMASK_CMP_GT)
2595 }
2596 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2597 if (CCMask == SystemZ::CCMASK_CMP_LT)
2599 if (CCMask == SystemZ::CCMASK_CMP_GE)
2601 }
2602
2603 // If there are just two bits, we can do equality checks for Low and High
2604 // as well.
2605 if (Mask == Low + High) {
2606 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2608 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2610 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2612 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2614 }
2615
2616 // Looks like we've exhausted our options.
2617 return 0;
2618}
2619
2620// See whether C can be implemented as a TEST UNDER MASK instruction.
2621// Update the arguments with the TM version if so.
2623 Comparison &C) {
2624 // Check that we have a comparison with a constant.
2625 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2626 if (!ConstOp1)
2627 return;
2628 uint64_t CmpVal = ConstOp1->getZExtValue();
2629
2630 // Check whether the nonconstant input is an AND with a constant mask.
2631 Comparison NewC(C);
2632 uint64_t MaskVal;
2633 ConstantSDNode *Mask = nullptr;
2634 if (C.Op0.getOpcode() == ISD::AND) {
2635 NewC.Op0 = C.Op0.getOperand(0);
2636 NewC.Op1 = C.Op0.getOperand(1);
2637 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2638 if (!Mask)
2639 return;
2640 MaskVal = Mask->getZExtValue();
2641 } else {
2642 // There is no instruction to compare with a 64-bit immediate
2643 // so use TMHH instead if possible. We need an unsigned ordered
2644 // comparison with an i64 immediate.
2645 if (NewC.Op0.getValueType() != MVT::i64 ||
2646 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2647 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2648 NewC.ICmpType == SystemZICMP::SignedOnly)
2649 return;
2650 // Convert LE and GT comparisons into LT and GE.
2651 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2652 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2653 if (CmpVal == uint64_t(-1))
2654 return;
2655 CmpVal += 1;
2656 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2657 }
2658 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2659 // be masked off without changing the result.
2660 MaskVal = -(CmpVal & -CmpVal);
2661 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2662 }
2663 if (!MaskVal)
2664 return;
2665
2666 // Check whether the combination of mask, comparison value and comparison
2667 // type are suitable.
2668 unsigned BitSize = NewC.Op0.getValueSizeInBits();
2669 unsigned NewCCMask, ShiftVal;
2670 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2671 NewC.Op0.getOpcode() == ISD::SHL &&
2672 isSimpleShift(NewC.Op0, ShiftVal) &&
2673 (MaskVal >> ShiftVal != 0) &&
2674 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
2675 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2676 MaskVal >> ShiftVal,
2677 CmpVal >> ShiftVal,
2678 SystemZICMP::Any))) {
2679 NewC.Op0 = NewC.Op0.getOperand(0);
2680 MaskVal >>= ShiftVal;
2681 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2682 NewC.Op0.getOpcode() == ISD::SRL &&
2683 isSimpleShift(NewC.Op0, ShiftVal) &&
2684 (MaskVal << ShiftVal != 0) &&
2685 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
2686 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2687 MaskVal << ShiftVal,
2688 CmpVal << ShiftVal,
2690 NewC.Op0 = NewC.Op0.getOperand(0);
2691 MaskVal <<= ShiftVal;
2692 } else {
2693 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2694 NewC.ICmpType);
2695 if (!NewCCMask)
2696 return;
2697 }
2698
2699 // Go ahead and make the change.
2700 C.Opcode = SystemZISD::TM;
2701 C.Op0 = NewC.Op0;
2702 if (Mask && Mask->getZExtValue() == MaskVal)
2703 C.Op1 = SDValue(Mask, 0);
2704 else
2705 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2706 C.CCValid = SystemZ::CCMASK_TM;
2707 C.CCMask = NewCCMask;
2708}
2709
2710// See whether the comparison argument contains a redundant AND
2711// and remove it if so. This sometimes happens due to the generic
2712// BRCOND expansion.
2714 Comparison &C) {
2715 if (C.Op0.getOpcode() != ISD::AND)
2716 return;
2717 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2718 if (!Mask)
2719 return;
2720 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
2721 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
2722 return;
2723
2724 C.Op0 = C.Op0.getOperand(0);
2725}
2726
2727// Return a Comparison that tests the condition-code result of intrinsic
2728// node Call against constant integer CC using comparison code Cond.
2729// Opcode is the opcode of the SystemZISD operation for the intrinsic
2730// and CCValid is the set of possible condition-code results.
2731static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2732 SDValue Call, unsigned CCValid, uint64_t CC,
2734 Comparison C(Call, SDValue(), SDValue());
2735 C.Opcode = Opcode;
2736 C.CCValid = CCValid;
2737 if (Cond == ISD::SETEQ)
2738 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2739 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2740 else if (Cond == ISD::SETNE)
2741 // ...and the inverse of that.
2742 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2743 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2744 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2745 // always true for CC>3.
2746 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2747 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2748 // ...and the inverse of that.
2749 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2750 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2751 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2752 // always true for CC>3.
2753 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2754 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2755 // ...and the inverse of that.
2756 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2757 else
2758 llvm_unreachable("Unexpected integer comparison type");
2759 C.CCMask &= CCValid;
2760 return C;
2761}
2762
2763// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2764static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2765 ISD::CondCode Cond, const SDLoc &DL,
2766 SDValue Chain = SDValue(),
2767 bool IsSignaling = false) {
2768 if (CmpOp1.getOpcode() == ISD::Constant) {
2769 assert(!Chain);
2770 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2771 unsigned Opcode, CCValid;
2772 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2773 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2774 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2775 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2776 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2777 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2778 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2779 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2780 }
2781 Comparison C(CmpOp0, CmpOp1, Chain);
2782 C.CCMask = CCMaskForCondCode(Cond);
2783 if (C.Op0.getValueType().isFloatingPoint()) {
2784 C.CCValid = SystemZ::CCMASK_FCMP;
2785 if (!C.Chain)
2786 C.Opcode = SystemZISD::FCMP;
2787 else if (!IsSignaling)
2788 C.Opcode = SystemZISD::STRICT_FCMP;
2789 else
2790 C.Opcode = SystemZISD::STRICT_FCMPS;
2792 } else {
2793 assert(!C.Chain);
2794 C.CCValid = SystemZ::CCMASK_ICMP;
2795 C.Opcode = SystemZISD::ICMP;
2796 // Choose the type of comparison. Equality and inequality tests can
2797 // use either signed or unsigned comparisons. The choice also doesn't
2798 // matter if both sign bits are known to be clear. In those cases we
2799 // want to give the main isel code the freedom to choose whichever
2800 // form fits best.
2801 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2802 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2803 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2804 C.ICmpType = SystemZICMP::Any;
2805 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2806 C.ICmpType = SystemZICMP::UnsignedOnly;
2807 else
2808 C.ICmpType = SystemZICMP::SignedOnly;
2809 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2810 adjustForRedundantAnd(DAG, DL, C);
2811 adjustZeroCmp(DAG, DL, C);
2812 adjustSubwordCmp(DAG, DL, C);
2813 adjustForSubtraction(DAG, DL, C);
2815 adjustICmpTruncate(DAG, DL, C);
2816 }
2817
2818 if (shouldSwapCmpOperands(C)) {
2819 std::swap(C.Op0, C.Op1);
2820 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
2821 }
2822
2824 return C;
2825}
2826
2827// Emit the comparison instruction described by C.
2828static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2829 if (!C.Op1.getNode()) {
2830 SDNode *Node;
2831 switch (C.Op0.getOpcode()) {
2833 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
2834 return SDValue(Node, 0);
2836 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
2837 return SDValue(Node, Node->getNumValues() - 1);
2838 default:
2839 llvm_unreachable("Invalid comparison operands");
2840 }
2841 }
2842 if (C.Opcode == SystemZISD::ICMP)
2843 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
2844 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
2845 if (C.Opcode == SystemZISD::TM) {
2846 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2848 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
2849 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
2850 }
2851 if (C.Chain) {
2853 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
2854 }
2855 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
2856}
2857
2858// Implement a 32-bit *MUL_LOHI operation by extending both operands to
2859// 64 bits. Extend is the extension type to use. Store the high part
2860// in Hi and the low part in Lo.
2861static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2862 SDValue Op0, SDValue Op1, SDValue &Hi,
2863 SDValue &Lo) {
2864 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2865 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2866 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2867 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2868 DAG.getConstant(32, DL, MVT::i64));
2871}
2872
2873// Lower a binary operation that produces two VT results, one in each
2874// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2875// and Opcode performs the GR128 operation. Store the even register result
2876// in Even and the odd register result in Odd.
2877static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2878 unsigned Opcode, SDValue Op0, SDValue Op1,
2879 SDValue &Even, SDValue &Odd) {
2880 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2881 bool Is32Bit = is32Bit(VT);
2882 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2883 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2884}
2885
2886// Return an i32 value that is 1 if the CC value produced by CCReg is
2887// in the mask CCMask and 0 otherwise. CC is known to have a value
2888// in CCValid, so other values can be ignored.
2889static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
2890 unsigned CCValid, unsigned CCMask) {
2891 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
2892 DAG.getConstant(0, DL, MVT::i32),
2893 DAG.getTargetConstant(CCValid, DL, MVT::i32),
2894 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
2895 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
2896}
2897
2898// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2899// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
2900// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
2901// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
2902// floating-point comparisons.
2905 switch (CC) {
2906 case ISD::SETOEQ:
2907 case ISD::SETEQ:
2908 switch (Mode) {
2909 case CmpMode::Int: return SystemZISD::VICMPE;
2910 case CmpMode::FP: return SystemZISD::VFCMPE;
2911 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
2912 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
2913 }
2914 llvm_unreachable("Bad mode");
2915
2916 case ISD::SETOGE:
2917 case ISD::SETGE:
2918 switch (Mode) {
2919 case CmpMode::Int: return 0;
2920 case CmpMode::FP: return SystemZISD::VFCMPHE;
2921 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
2922 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
2923 }
2924 llvm_unreachable("Bad mode");
2925
2926 case ISD::SETOGT:
2927 case ISD::SETGT:
2928 switch (Mode) {
2929 case CmpMode::Int: return SystemZISD::VICMPH;
2930 case CmpMode::FP: return SystemZISD::VFCMPH;
2931 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
2932 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
2933 }
2934 llvm_unreachable("Bad mode");
2935
2936 case ISD::SETUGT:
2937 switch (Mode) {
2938 case CmpMode::Int: return SystemZISD::VICMPHL;
2939 case CmpMode::FP: return 0;
2940 case CmpMode::StrictFP: return 0;
2941 case CmpMode::SignalingFP: return 0;
2942 }
2943 llvm_unreachable("Bad mode");
2944
2945 default:
2946 return 0;
2947 }
2948}
2949
2950// Return the SystemZISD vector comparison operation for CC or its inverse,
2951// or 0 if neither can be done directly. Indicate in Invert whether the
2952// result is for the inverse of CC. Mode is as above.
2954 bool &Invert) {
2955 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2956 Invert = false;
2957 return Opcode;
2958 }
2959
2960 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
2961 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2962 Invert = true;
2963 return Opcode;
2964 }
2965
2966 return 0;
2967}
2968
2969// Return a v2f64 that contains the extended form of elements Start and Start+1
2970// of v4f32 value Op. If Chain is nonnull, return the strict form.
2971static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2972 SDValue Op, SDValue Chain) {
2973 int Mask[] = { Start, -1, Start + 1, -1 };
2974 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2975 if (Chain) {
2977 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
2978 }
2979 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2980}
2981
2982// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2983// producing a result of type VT. If Chain is nonnull, return the strict form.
2984SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2985 const SDLoc &DL, EVT VT,
2986 SDValue CmpOp0,
2987 SDValue CmpOp1,
2988 SDValue Chain) const {
2989 // There is no hardware support for v4f32 (unless we have the vector
2990 // enhancements facility 1), so extend the vector into two v2f64s
2991 // and compare those.
2992 if (CmpOp0.getValueType() == MVT::v4f32 &&
2993 !Subtarget.hasVectorEnhancements1()) {
2994 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
2995 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
2996 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
2997 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
2998 if (Chain) {
3000 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3001 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3002 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3003 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3004 H1.getValue(1), L1.getValue(1),
3005 HRes.getValue(1), LRes.getValue(1) };
3006 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3007 SDValue Ops[2] = { Res, NewChain };
3008 return DAG.getMergeValues(Ops, DL);
3009 }
3010 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3011 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3012 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3013 }
3014 if (Chain) {
3015 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3016 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3017 }
3018 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3019}
3020
3021// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3022// an integer mask of type VT. If Chain is nonnull, we have a strict
3023// floating-point comparison. If in addition IsSignaling is true, we have
3024// a strict signaling floating-point comparison.
3025SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3026 const SDLoc &DL, EVT VT,
3028 SDValue CmpOp0,
3029 SDValue CmpOp1,
3030 SDValue Chain,
3031 bool IsSignaling) const {
3032 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3033 assert (!Chain || IsFP);
3034 assert (!IsSignaling || Chain);
3035 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3036 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3037 bool Invert = false;
3038 SDValue Cmp;
3039 switch (CC) {
3040 // Handle tests for order using (or (ogt y x) (oge x y)).
3041 case ISD::SETUO:
3042 Invert = true;
3043 [[fallthrough]];
3044 case ISD::SETO: {
3045 assert(IsFP && "Unexpected integer comparison");
3046 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3047 DL, VT, CmpOp1, CmpOp0, Chain);
3048 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3049 DL, VT, CmpOp0, CmpOp1, Chain);
3050 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3051 if (Chain)
3052 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3053 LT.getValue(1), GE.getValue(1));
3054 break;
3055 }
3056
3057 // Handle <> tests using (or (ogt y x) (ogt x y)).
3058 case ISD::SETUEQ:
3059 Invert = true;
3060 [[fallthrough]];
3061 case ISD::SETONE: {
3062 assert(IsFP && "Unexpected integer comparison");
3063 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3064 DL, VT, CmpOp1, CmpOp0, Chain);
3065 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3066 DL, VT, CmpOp0, CmpOp1, Chain);
3067 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
3068 if (Chain)
3069 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3070 LT.getValue(1), GT.getValue(1));
3071 break;
3072 }
3073
3074 // Otherwise a single comparison is enough. It doesn't really
3075 // matter whether we try the inversion or the swap first, since
3076 // there are no cases where both work.
3077 default:
3078 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3079 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
3080 else {
3082 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3083 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
3084 else
3085 llvm_unreachable("Unhandled comparison");
3086 }
3087 if (Chain)
3088 Chain = Cmp.getValue(1);
3089 break;
3090 }
3091 if (Invert) {
3092 SDValue Mask =
3093 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
3094 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
3095 }
3096 if (Chain && Chain.getNode() != Cmp.getNode()) {
3097 SDValue Ops[2] = { Cmp, Chain };
3098 Cmp = DAG.getMergeValues(Ops, DL);
3099 }
3100 return Cmp;
3101}
3102
3103SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
3104 SelectionDAG &DAG) const {
3105 SDValue CmpOp0 = Op.getOperand(0);
3106 SDValue CmpOp1 = Op.getOperand(1);
3107 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3108 SDLoc DL(Op);
3109 EVT VT = Op.getValueType();
3110 if (VT.isVector())
3111 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
3112
3113 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3114 SDValue CCReg = emitCmp(DAG, DL, C);
3115 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3116}
3117
3118SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
3119 SelectionDAG &DAG,
3120 bool IsSignaling) const {
3121 SDValue Chain = Op.getOperand(0);
3122 SDValue CmpOp0 = Op.getOperand(1);
3123 SDValue CmpOp1 = Op.getOperand(2);
3124 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
3125 SDLoc DL(Op);
3126 EVT VT = Op.getNode()->getValueType(0);
3127 if (VT.isVector()) {
3128 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
3129 Chain, IsSignaling);
3130 return Res.getValue(Op.getResNo());
3131 }
3132
3133 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
3134 SDValue CCReg = emitCmp(DAG, DL, C);
3135 CCReg->setFlags(Op->getFlags());
3136 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3137 SDValue Ops[2] = { Result, CCReg.getValue(1) };
3138 return DAG.getMergeValues(Ops, DL);
3139}
3140
3141SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3142 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3143 SDValue CmpOp0 = Op.getOperand(2);
3144 SDValue CmpOp1 = Op.getOperand(3);
3145 SDValue Dest = Op.getOperand(4);
3146 SDLoc DL(Op);
3147
3148 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3149 SDValue CCReg = emitCmp(DAG, DL, C);
3150 return DAG.getNode(
3151 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
3152 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3153 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
3154}
3155
3156// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
3157// allowing Pos and Neg to be wider than CmpOp.
3158static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
3159 return (Neg.getOpcode() == ISD::SUB &&
3160 Neg.getOperand(0).getOpcode() == ISD::Constant &&
3161 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
3162 Neg.getOperand(1) == Pos &&
3163 (Pos == CmpOp ||
3164 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
3165 Pos.getOperand(0) == CmpOp)));
3166}
3167
3168// Return the absolute or negative absolute of Op; IsNegative decides which.
3170 bool IsNegative) {
3171 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
3172 if (IsNegative)
3173 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
3174 DAG.getConstant(0, DL, Op.getValueType()), Op);
3175 return Op;
3176}
3177
3178SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
3179 SelectionDAG &DAG) const {
3180 SDValue CmpOp0 = Op.getOperand(0);
3181 SDValue CmpOp1 = Op.getOperand(1);
3182 SDValue TrueOp = Op.getOperand(2);
3183 SDValue FalseOp = Op.getOperand(3);
3184 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3185 SDLoc DL(Op);
3186
3187 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3188
3189 // Check for absolute and negative-absolute selections, including those
3190 // where the comparison value is sign-extended (for LPGFR and LNGFR).
3191 // This check supplements the one in DAGCombiner.
3192 if (C.Opcode == SystemZISD::ICMP &&
3193 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
3194 C.CCMask != SystemZ::CCMASK_CMP_NE &&
3195 C.Op1.getOpcode() == ISD::Constant &&
3196 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
3197 if (isAbsolute(C.Op0, TrueOp, FalseOp))
3198 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
3199 if (isAbsolute(C.Op0, FalseOp, TrueOp))
3200 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
3201 }
3202
3203 SDValue CCReg = emitCmp(DAG, DL, C);
3204 SDValue Ops[] = {TrueOp, FalseOp,
3205 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3206 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
3207
3208 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
3209}
3210
3211SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
3212 SelectionDAG &DAG) const {
3213 SDLoc DL(Node);
3214 const GlobalValue *GV = Node->getGlobal();
3215 int64_t Offset = Node->getOffset();
3216 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3218
3220 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
3221 if (isInt<32>(Offset)) {
3222 // Assign anchors at 1<<12 byte boundaries.
3223 uint64_t Anchor = Offset & ~uint64_t(0xfff);
3224 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
3225 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3226
3227 // The offset can be folded into the address if it is aligned to a
3228 // halfword.
3229 Offset -= Anchor;
3230 if (Offset != 0 && (Offset & 1) == 0) {
3231 SDValue Full =
3232 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
3233 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
3234 Offset = 0;
3235 }
3236 } else {
3237 // Conservatively load a constant offset greater than 32 bits into a
3238 // register below.
3239 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
3240 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3241 }
3242 } else {
3243 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
3244 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3245 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3247 }
3248
3249 // If there was a non-zero offset that we didn't fold, create an explicit
3250 // addition for it.
3251 if (Offset != 0)
3252 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
3253 DAG.getConstant(Offset, DL, PtrVT));
3254
3255 return Result;
3256}
3257
3258SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
3259 SelectionDAG &DAG,
3260 unsigned Opcode,
3261 SDValue GOTOffset) const {
3262 SDLoc DL(Node);
3263 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3264 SDValue Chain = DAG.getEntryNode();
3265 SDValue Glue;
3266
3269 report_fatal_error("In GHC calling convention TLS is not supported");
3270
3271 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
3272 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
3273 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
3274 Glue = Chain.getValue(1);
3275 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
3276 Glue = Chain.getValue(1);
3277
3278 // The first call operand is the chain and the second is the TLS symbol.
3280 Ops.push_back(Chain);
3281 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
3282 Node->getValueType(0),
3283 0, 0));
3284
3285 // Add argument registers to the end of the list so that they are
3286 // known live into the call.
3287 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
3288 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
3289
3290 // Add a register mask operand representing the call-preserved registers.
3291 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3292 const uint32_t *Mask =
3293 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3294 assert(Mask && "Missing call preserved mask for calling convention");
3295 Ops.push_back(DAG.getRegisterMask(Mask));
3296
3297 // Glue the call to the argument copies.
3298 Ops.push_back(Glue);
3299
3300 // Emit the call.
3301 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3302 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
3303 Glue = Chain.getValue(1);
3304
3305 // Copy the return value from %r2.
3306 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
3307}
3308
3309SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
3310 SelectionDAG &DAG) const {
3311 SDValue Chain = DAG.getEntryNode();
3312 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3313
3314 // The high part of the thread pointer is in access register 0.
3315 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
3316 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
3317
3318 // The low part of the thread pointer is in access register 1.
3319 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
3320 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
3321
3322 // Merge them into a single 64-bit address.
3323 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
3324 DAG.getConstant(32, DL, PtrVT));
3325 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
3326}
3327
3328SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
3329 SelectionDAG &DAG) const {
3330 if (DAG.getTarget().useEmulatedTLS())
3331 return LowerToTLSEmulatedModel(Node, DAG);
3332 SDLoc DL(Node);
3333 const GlobalValue *GV = Node->getGlobal();
3334 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3335 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
3336
3339 report_fatal_error("In GHC calling convention TLS is not supported");
3340
3341 SDValue TP = lowerThreadPointer(DL, DAG);
3342
3343 // Get the offset of GA from the thread pointer, based on the TLS model.
3345 switch (model) {
3347 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
3350
3351 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3352 Offset = DAG.getLoad(
3353 PtrVT, DL, DAG.getEntryNode(), Offset,
3355
3356 // Call __tls_get_offset to retrieve the offset.
3357 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
3358 break;
3359 }
3360
3362 // Load the GOT offset of the module ID.
3365
3366 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3367 Offset = DAG.getLoad(
3368 PtrVT, DL, DAG.getEntryNode(), Offset,
3370
3371 // Call __tls_get_offset to retrieve the module base offset.
3372 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
3373
3374 // Note: The SystemZLDCleanupPass will remove redundant computations
3375 // of the module base offset. Count total number of local-dynamic
3376 // accesses to trigger execution of that pass.
3380
3381 // Add the per-symbol offset.
3383
3384 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3385 DTPOffset = DAG.getLoad(
3386 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
3388
3389 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
3390 break;
3391 }
3392
3393 case TLSModel::InitialExec: {
3394 // Load the offset from the GOT.
3395 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3398 Offset =
3399 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
3401 break;
3402 }
3403
3404 case TLSModel::LocalExec: {
3405 // Force the offset into the constant pool and load it from there.
3408
3409 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3410 Offset = DAG.getLoad(
3411 PtrVT, DL, DAG.getEntryNode(), Offset,
3413 break;
3414 }
3415 }
3416
3417 // Add the base and offset together.
3418 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
3419}
3420
3421SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
3422 SelectionDAG &DAG) const {
3423 SDLoc DL(Node);
3424 const BlockAddress *BA = Node->getBlockAddress();
3425 int64_t Offset = Node->getOffset();
3426 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3427
3428 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
3429 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3430 return Result;
3431}
3432
3433SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
3434 SelectionDAG &DAG) const {
3435 SDLoc DL(JT);
3436 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3437 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3438
3439 // Use LARL to load the address of the table.
3440 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3441}
3442
3443SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
3444 SelectionDAG &DAG) const {
3445 SDLoc DL(CP);
3446 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3447
3449 if (CP->isMachineConstantPoolEntry())
3450 Result =
3451 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3452 else
3453 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
3454 CP->getOffset());
3455
3456 // Use LARL to load the address of the constant pool entry.
3457 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3458}
3459
3460SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
3461 SelectionDAG &DAG) const {
3462 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
3464 MachineFrameInfo &MFI = MF.getFrameInfo();
3465 MFI.setFrameAddressIsTaken(true);
3466
3467 SDLoc DL(Op);
3468 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3469 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3470
3471 // By definition, the frame address is the address of the back chain. (In
3472 // the case of packed stack without backchain, return the address where the
3473 // backchain would have been stored. This will either be an unused space or
3474 // contain a saved register).
3475 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
3476 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
3477
3478 // FIXME The frontend should detect this case.
3479 if (Depth > 0) {
3480 report_fatal_error("Unsupported stack frame traversal count");
3481 }
3482
3483 return BackChain;
3484}
3485
3486SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
3487 SelectionDAG &DAG) const {
3489 MachineFrameInfo &MFI = MF.getFrameInfo();
3490 MFI.setReturnAddressIsTaken(true);
3491
3493 return SDValue();
3494
3495 SDLoc DL(Op);
3496 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3497 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3498
3499 // FIXME The frontend should detect this case.
3500 if (Depth > 0) {
3501 report_fatal_error("Unsupported stack frame traversal count");
3502 }
3503
3504 // Return R14D, which has the return address. Mark it an implicit live-in.
3505 Register LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
3506 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
3507}
3508
3509SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
3510 SelectionDAG &DAG) const {
3511 SDLoc DL(Op);
3512 SDValue In = Op.getOperand(0);
3513 EVT InVT = In.getValueType();
3514 EVT ResVT = Op.getValueType();
3515
3516 // Convert loads directly. This is normally done by DAGCombiner,
3517 // but we need this case for bitcasts that are created during lowering
3518 // and which are then lowered themselves.
3519 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
3520 if (ISD::isNormalLoad(LoadN)) {
3521 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
3522 LoadN->getBasePtr(), LoadN->getMemOperand());
3523 // Update the chain uses.
3524 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
3525 return NewLoad;
3526 }
3527
3528 if (InVT == MVT::i32 && ResVT == MVT::f32) {
3529 SDValue In64;
3530 if (Subtarget.hasHighWord()) {
3531 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
3532 MVT::i64);
3533 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3534 MVT::i64, SDValue(U64, 0), In);
3535 } else {
3536 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
3537 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
3538 DAG.getConstant(32, DL, MVT::i64));
3539 }
3540 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
3541 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
3542 DL, MVT::f32, Out64);
3543 }
3544 if (InVT == MVT::f32 && ResVT == MVT::i32) {
3545 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
3546 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3547 MVT::f64, SDValue(U64, 0), In);
3548 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
3549 if (Subtarget.hasHighWord())
3550 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
3551 MVT::i32, Out64);
3552 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
3553 DAG.getConstant(32, DL, MVT::i64));
3554 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
3555 }
3556 llvm_unreachable("Unexpected bitcast combination");
3557}
3558
3559SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
3560 SelectionDAG &DAG) const {
3561
3562 if (Subtarget.isTargetXPLINK64())
3563 return lowerVASTART_XPLINK(Op, DAG);
3564 else
3565 return lowerVASTART_ELF(Op, DAG);
3566}
3567
3568SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
3569 SelectionDAG &DAG) const {
3571 SystemZMachineFunctionInfo *FuncInfo =
3573
3574 SDLoc DL(Op);
3575
3576 // vastart just stores the address of the VarArgsFrameIndex slot into the
3577 // memory location argument.
3578 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3579 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3580 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3581 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3582 MachinePointerInfo(SV));
3583}
3584
3585SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
3586 SelectionDAG &DAG) const {
3588 SystemZMachineFunctionInfo *FuncInfo =
3590 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3591
3592 SDValue Chain = Op.getOperand(0);
3593 SDValue Addr = Op.getOperand(1);
3594 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3595 SDLoc DL(Op);
3596
3597 // The initial values of each field.
3598 const unsigned NumFields = 4;
3599 SDValue Fields[NumFields] = {
3600 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
3601 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
3602 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
3603 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
3604 };
3605
3606 // Store each field into its respective slot.
3607 SDValue MemOps[NumFields];
3608 unsigned Offset = 0;
3609 for (unsigned I = 0; I < NumFields; ++I) {
3610 SDValue FieldAddr = Addr;
3611 if (Offset != 0)
3612 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
3614 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
3616 Offset += 8;
3617 }
3618 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3619}
3620
3621SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
3622 SelectionDAG &DAG) const {
3623 SDValue Chain = Op.getOperand(0);
3624 SDValue DstPtr = Op.getOperand(1);
3625 SDValue SrcPtr = Op.getOperand(2);
3626 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3627 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3628 SDLoc DL(Op);
3629
3630 uint32_t Sz =
3631 Subtarget.isTargetXPLINK64() ? getTargetMachine().getPointerSize(0) : 32;
3632 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
3633 Align(8), /*isVolatile*/ false, /*AlwaysInline*/ false,
3634 /*isTailCall*/ false, MachinePointerInfo(DstSV),
3635 MachinePointerInfo(SrcSV));
3636}
3637
3638SDValue
3639SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
3640 SelectionDAG &DAG) const {
3641 if (Subtarget.isTargetXPLINK64())
3642 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
3643 else
3644 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
3645}
3646
3647SDValue
3648SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
3649 SelectionDAG &DAG) const {
3650 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3652 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
3653 SDValue Chain = Op.getOperand(0);
3654 SDValue Size = Op.getOperand(1);
3655 SDValue Align = Op.getOperand(2);
3656 SDLoc DL(Op);
3657
3658 // If user has set the no alignment function attribute, ignore
3659 // alloca alignments.
3660 uint64_t AlignVal =
3661 (RealignOpt ? cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3662
3664 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3665 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3666
3667 SDValue NeededSpace = Size;
3668
3669 // Add extra space for alignment if needed.
3670 EVT PtrVT = getPointerTy(MF.getDataLayout());
3671 if (ExtraAlignSpace)
3672 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
3673 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
3674
3675 bool IsSigned = false;
3676 bool DoesNotReturn = false;
3677 bool IsReturnValueUsed = false;
3678 EVT VT = Op.getValueType();
3679 SDValue AllocaCall =
3680 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
3681 CallingConv::C, IsSigned, DL, DoesNotReturn,
3682 IsReturnValueUsed)
3683 .first;
3684
3685 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
3686 // to end of call in order to ensure it isn't broken up from the call
3687 // sequence.
3688 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
3689 Register SPReg = Regs.getStackPointerRegister();
3690 Chain = AllocaCall.getValue(1);
3691 SDValue Glue = AllocaCall.getValue(2);
3692 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
3693 Chain = NewSPRegNode.getValue(1);
3694
3695 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
3696 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
3697 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
3698
3699 // Dynamically realign if needed.
3700 if (ExtraAlignSpace) {
3701 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
3702 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
3703 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
3704 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
3705 }
3706
3707 SDValue Ops[2] = {Result, Chain};
3708 return DAG.getMergeValues(Ops, DL);
3709}
3710
3711SDValue
3712SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
3713 SelectionDAG &DAG) const {
3714 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3716 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
3717 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
3718
3719 SDValue Chain = Op.getOperand(0);
3720 SDValue Size = Op.getOperand(1);
3721 SDValue Align = Op.getOperand(2);
3722 SDLoc DL(Op);
3723
3724 // If user has set the no alignment function attribute, ignore
3725 // alloca alignments.
3726 uint64_t AlignVal =
3727 (RealignOpt ? cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3728
3730 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3731 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3732
3734 SDValue NeededSpace = Size;
3735
3736 // Get a reference to the stack pointer.
3737 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
3738
3739 // If we need a backchain, save it now.
3740 SDValue Backchain;
3741 if (StoreBackchain)
3742 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
3744
3745 // Add extra space for alignment if needed.
3746 if (ExtraAlignSpace)
3747 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
3748 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3749
3750 // Get the new stack pointer value.
3751 SDValue NewSP;
3752 if (hasInlineStackProbe(MF)) {
3754 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
3755 Chain = NewSP.getValue(1);
3756 }
3757 else {
3758 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
3759 // Copy the new stack pointer back.
3760 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
3761 }
3762
3763 // The allocated data lives above the 160 bytes allocated for the standard
3764 // frame, plus any outgoing stack arguments. We don't know how much that
3765 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
3767 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3768
3769 // Dynamically realign if needed.
3770 if (RequiredAlign > StackAlign) {
3771 Result =
3772 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3773 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3774 Result =
3775 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3776 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3777 }
3778
3779 if (StoreBackchain)
3780 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
3782
3783 SDValue Ops[2] = { Result, Chain };
3784 return DAG.getMergeValues(Ops, DL);
3785}
3786
3787SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3788 SDValue Op, SelectionDAG &DAG) const {
3789 SDLoc DL(Op);
3790
3792}
3793
3794SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3795 SelectionDAG &DAG) const {
3796 EVT VT = Op.getValueType();
3797 SDLoc DL(Op);
3798 SDValue Ops[2];
3799 if (is32Bit(VT))
3800 // Just do a normal 64-bit multiplication and extract the results.
3801 // We define this so that it can be used for constant division.
3802 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
3803 Op.getOperand(1), Ops[1], Ops[0]);
3804 else if (Subtarget.hasMiscellaneousExtensions2())
3805 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3806 // the high result in the even register. ISD::SMUL_LOHI is defined to
3807 // return the low half first, so the results are in reverse order.
3809 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3810 else {
3811 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3812 //
3813 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3814 //
3815 // but using the fact that the upper halves are either all zeros
3816 // or all ones: