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