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