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