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