LLVM  6.0.0svn
SystemZISelLowering.cpp
Go to the documentation of this file.
1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SystemZISelLowering.h"
15 #include "SystemZCallingConv.h"
18 #include "SystemZTargetMachine.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/IntrinsicInst.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 a sequence for extracting a 0/1 value from an IPM result:
35 // (((X ^ XORValue) + AddValue) >> Bit)
36 struct IPMConversion {
37  IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
38  : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
39 
40  int64_t XORValue;
41  int64_t AddValue;
42  unsigned Bit;
43 };
44 
45 // Represents information about a comparison.
46 struct Comparison {
47  Comparison(SDValue Op0In, SDValue Op1In)
48  : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
49 
50  // The operands to the comparison.
51  SDValue Op0, Op1;
52 
53  // The opcode that should be used to compare Op0 and Op1.
54  unsigned Opcode;
55 
56  // A SystemZICMP value. Only used for integer comparisons.
57  unsigned ICmpType;
58 
59  // The mask of CC values that Opcode can produce.
60  unsigned CCValid;
61 
62  // The mask of CC values for which the original condition is true.
63  unsigned CCMask;
64 };
65 } // end anonymous namespace
66 
67 // Classify VT as either 32 or 64 bit.
68 static bool is32Bit(EVT VT) {
69  switch (VT.getSimpleVT().SimpleTy) {
70  case MVT::i32:
71  return true;
72  case MVT::i64:
73  return false;
74  default:
75  llvm_unreachable("Unsupported type");
76  }
77 }
78 
79 // Return a version of MachineOperand that can be safely used before the
80 // final use.
82  if (Op.isReg())
83  Op.setIsKill(false);
84  return Op;
85 }
86 
88  const SystemZSubtarget &STI)
89  : TargetLowering(TM), Subtarget(STI) {
90  MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
91 
92  // Set up the register classes.
93  if (Subtarget.hasHighWord())
94  addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
95  else
96  addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
97  addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
98  if (Subtarget.hasVector()) {
99  addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
100  addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
101  } else {
102  addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
103  addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
104  }
105  if (Subtarget.hasVectorEnhancements1())
106  addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
107  else
108  addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
109 
110  if (Subtarget.hasVector()) {
111  addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
112  addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
113  addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
114  addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
115  addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
116  addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
117  }
118 
119  // Compute derived properties from the register classes
121 
122  // Set up special registers.
124 
125  // TODO: It may be better to default to latency-oriented scheduling, however
126  // LLVM's current latency-oriented scheduler can't handle physreg definitions
127  // such as SystemZ has with CC, so set this to the register-pressure
128  // scheduler, because it can.
130 
133 
134  // Instructions are strings of 2-byte aligned 2-byte values.
136 
137  // Handle operations that are handled in a similar way for all types.
138  for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
140  ++I) {
141  MVT VT = MVT::SimpleValueType(I);
142  if (isTypeLegal(VT)) {
143  // Lower SET_CC into an IPM-based sequence.
145 
146  // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
148 
149  // Lower SELECT_CC and BR_CC into separate comparisons and branches.
152  }
153  }
154 
155  // Expand jump table branches as address arithmetic followed by an
156  // indirect jump.
158 
159  // Expand BRCOND into a BR_CC (see above).
161 
162  // Handle integer types.
163  for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
165  ++I) {
166  MVT VT = MVT::SimpleValueType(I);
167  if (isTypeLegal(VT)) {
168  // Expand individual DIV and REMs into DIVREMs.
175 
176  // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
177  // stores, putting a serialization instruction after the stores.
180 
181  // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
182  // available, or if the operand is constant.
184 
185  // Use POPCNT on z196 and above.
186  if (Subtarget.hasPopulationCount())
188  else
190 
191  // No special instructions for these.
194 
195  // Use *MUL_LOHI where possible instead of MULH*.
200 
201  // Only z196 and above have native support for conversions to unsigned.
202  // On z10, promoting to i64 doesn't generate an inexact condition for
203  // values that are outside the i32 range but in the i64 range, so use
204  // the default expansion.
205  if (!Subtarget.hasFPExtension())
207  }
208  }
209 
210  // Type legalization will convert 8- and 16-bit atomic operations into
211  // forms that operate on i32s (but still keeping the original memory VT).
212  // Lower them into full i32 operations.
224 
225  // Even though i128 is not a legal type, we still need to custom lower
226  // the atomic operations in order to exploit SystemZ instructions.
229 
230  // We can use the CC result of compare-and-swap to implement
231  // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
235 
237 
238  // Traps are legal, as we will convert them to "j .+2".
240 
241  // z10 has instructions for signed but not unsigned FP conversion.
242  // Handle unsigned 32-bit types as signed 64-bit types.
243  if (!Subtarget.hasFPExtension()) {
246  }
247 
248  // We have native support for a 64-bit CTLZ, via FLOGR.
251 
252  // Give LowerOperation the chance to replace 64-bit ORs with subregs.
254 
255  // FIXME: Can we support these natively?
259 
260  // We have native instructions for i8, i16 and i32 extensions, but not i1.
262  for (MVT VT : MVT::integer_valuetypes()) {
266  }
267 
268  // Handle the various types of symbolic address.
274 
275  // We need to handle dynamic allocations specially because of the
276  // 160-byte area at the bottom of the stack.
279 
280  // Use custom expanders so that we can force the function to use
281  // a frame pointer.
284 
285  // Handle prefetches with PFD or PFDRL.
287 
288  for (MVT VT : MVT::vector_valuetypes()) {
289  // Assume by default that all vector operations need to be expanded.
290  for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
291  if (getOperationAction(Opcode, VT) == Legal)
292  setOperationAction(Opcode, VT, Expand);
293 
294  // Likewise all truncating stores and extending loads.
295  for (MVT InnerVT : MVT::vector_valuetypes()) {
296  setTruncStoreAction(VT, InnerVT, Expand);
297  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
298  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
299  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
300  }
301 
302  if (isTypeLegal(VT)) {
303  // These operations are legal for anything that can be stored in a
304  // vector register, even if there is no native support for the format
305  // as such. In particular, we can do these for v4f32 even though there
306  // are no specific instructions for that format.
312 
313  // Likewise, except that we need to replace the nodes with something
314  // more specific.
317  }
318  }
319 
320  // Handle integer vector types.
321  for (MVT VT : MVT::integer_vector_valuetypes()) {
322  if (isTypeLegal(VT)) {
323  // These operations have direct equivalents.
328  if (VT != MVT::v2i64)
333  if (Subtarget.hasVectorEnhancements1())
335  else
339 
340  // Convert a GPR scalar to a vector by inserting it into element 0.
342 
343  // Use a series of unpacks for extensions.
346 
347  // Detect shifts by a scalar amount and convert them into
348  // V*_BY_SCALAR.
352 
353  // At present ROTL isn't matched by DAGCombiner. ROTR should be
354  // converted into ROTL.
357 
358  // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
359  // and inverting the result as necessary.
361  }
362  }
363 
364  if (Subtarget.hasVector()) {
365  // There should be no need to check for float types other than v2f64
366  // since <2 x f32> isn't a legal type.
375  }
376 
377  // Handle floating-point types.
378  for (unsigned I = MVT::FIRST_FP_VALUETYPE;
380  ++I) {
381  MVT VT = MVT::SimpleValueType(I);
382  if (isTypeLegal(VT)) {
383  // We can use FI for FRINT.
385 
386  // We can use the extended form of FI for other rounding operations.
387  if (Subtarget.hasFPExtension()) {
393  }
394 
395  // No special instructions for these.
401  }
402  }
403 
404  // Handle floating-point vector types.
405  if (Subtarget.hasVector()) {
406  // Scalar-to-vector conversion is just a subreg.
409 
410  // Some insertions and extractions can be done directly but others
411  // need to go via integers.
416 
417  // These operations have direct equivalents.
432  }
433 
434  // The vector enhancements facility 1 has instructions for these.
435  if (Subtarget.hasVectorEnhancements1()) {
450 
455 
460 
465 
470 
475  }
476 
477  // We have fused multiply-addition for f32 and f64 but not f128.
480  if (Subtarget.hasVectorEnhancements1())
482  else
484 
485  // We don't have a copysign instruction on vector registers.
486  if (Subtarget.hasVectorEnhancements1())
488 
489  // Needed so that we don't try to implement f128 constant loads using
490  // a load-and-extend of a f80 constant (in cases where the constant
491  // would fit in an f80).
492  for (MVT VT : MVT::fp_valuetypes())
494 
495  // We don't have extending load instruction on vector registers.
496  if (Subtarget.hasVectorEnhancements1()) {
499  }
500 
501  // Floating-point truncation and stores need to be done separately.
505 
506  // We have 64-bit FPR<->GPR moves, but need special handling for
507  // 32-bit forms.
508  if (!Subtarget.hasVector()) {
511  }
512 
513  // VASTART and VACOPY need to deal with the SystemZ-specific varargs
514  // structure, but VAEND is a no-op.
518 
519  // Codes for which we want to perform some z-specific combinations.
529 
530  // Handle intrinsics.
533 
534  // We want to use MVC in preference to even a single load/store pair.
535  MaxStoresPerMemcpy = 0;
537 
538  // The main memset sequence is a byte store followed by an MVC.
539  // Two STC or MV..I stores win over that, but the kind of fused stores
540  // generated by target-independent code don't when the byte value is
541  // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
542  // than "STC;MVC". Handle the choice in target-specific code instead.
543  MaxStoresPerMemset = 0;
545 }
546 
548  LLVMContext &, EVT VT) const {
549  if (!VT.isVector())
550  return MVT::i32;
552 }
553 
555  VT = VT.getScalarType();
556 
557  if (!VT.isSimple())
558  return false;
559 
560  switch (VT.getSimpleVT().SimpleTy) {
561  case MVT::f32:
562  case MVT::f64:
563  return true;
564  case MVT::f128:
565  return Subtarget.hasVectorEnhancements1();
566  default:
567  break;
568  }
569 
570  return false;
571 }
572 
573 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
574  // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
575  return Imm.isZero() || Imm.isNegZero();
576 }
577 
579  // We can use CGFI or CLGFI.
580  return isInt<32>(Imm) || isUInt<32>(Imm);
581 }
582 
584  // We can use ALGFI or SLGFI.
585  return isUInt<32>(Imm) || isUInt<32>(-Imm);
586 }
587 
589  unsigned,
590  unsigned,
591  bool *Fast) const {
592  // Unaligned accesses should never be slower than the expanded version.
593  // We check specifically for aligned accesses in the few cases where
594  // they are required.
595  if (Fast)
596  *Fast = true;
597  return true;
598 }
599 
600 // Information about the addressing mode for a memory access.
602  // True if a long displacement is supported.
604 
605  // True if use of index register is supported.
606  bool IndexReg;
607 
608  AddressingMode(bool LongDispl, bool IdxReg) :
609  LongDisplacement(LongDispl), IndexReg(IdxReg) {}
610 };
611 
612 // Return the desired addressing mode for a Load which has only one use (in
613 // the same block) which is a Store.
614 static AddressingMode getLoadStoreAddrMode(bool HasVector,
615  Type *Ty) {
616  // With vector support a Load->Store combination may be combined to either
617  // an MVC or vector operations and it seems to work best to allow the
618  // vector addressing mode.
619  if (HasVector)
620  return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
621 
622  // Otherwise only the MVC case is special.
623  bool MVC = Ty->isIntegerTy(8);
624  return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
625 }
626 
627 // Return the addressing mode which seems most desirable given an LLVM
628 // Instruction pointer.
629 static AddressingMode
631  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
632  switch (II->getIntrinsicID()) {
633  default: break;
634  case Intrinsic::memset:
635  case Intrinsic::memmove:
636  case Intrinsic::memcpy:
637  return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
638  }
639  }
640 
641  if (isa<LoadInst>(I) && I->hasOneUse()) {
642  auto *SingleUser = dyn_cast<Instruction>(*I->user_begin());
643  if (SingleUser->getParent() == I->getParent()) {
644  if (isa<ICmpInst>(SingleUser)) {
645  if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
646  if (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue()))
647  // Comparison of memory with 16 bit signed / unsigned immediate
648  return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
649  } else if (isa<StoreInst>(SingleUser))
650  // Load->Store
651  return getLoadStoreAddrMode(HasVector, I->getType());
652  }
653  } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
654  if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
655  if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
656  // Load->Store
657  return getLoadStoreAddrMode(HasVector, LoadI->getType());
658  }
659 
660  if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
661 
662  // * Use LDE instead of LE/LEY for z13 to avoid partial register
663  // dependencies (LDE only supports small offsets).
664  // * Utilize the vector registers to hold floating point
665  // values (vector load / store instructions only support small
666  // offsets).
667 
668  Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
669  I->getOperand(0)->getType());
670  bool IsFPAccess = MemAccessTy->isFloatingPointTy();
671  bool IsVectorAccess = MemAccessTy->isVectorTy();
672 
673  // A store of an extracted vector element will be combined into a VSTE type
674  // instruction.
675  if (!IsVectorAccess && isa<StoreInst>(I)) {
676  Value *DataOp = I->getOperand(0);
677  if (isa<ExtractElementInst>(DataOp))
678  IsVectorAccess = true;
679  }
680 
681  // A load which gets inserted into a vector element will be combined into a
682  // VLE type instruction.
683  if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
684  User *LoadUser = *I->user_begin();
685  if (isa<InsertElementInst>(LoadUser))
686  IsVectorAccess = true;
687  }
688 
689  if (IsFPAccess || IsVectorAccess)
690  return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
691  }
692 
693  return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
694 }
695 
697  const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
698  // Punt on globals for now, although they can be used in limited
699  // RELATIVE LONG cases.
700  if (AM.BaseGV)
701  return false;
702 
703  // Require a 20-bit signed offset.
704  if (!isInt<20>(AM.BaseOffs))
705  return false;
706 
707  AddressingMode SupportedAM(true, true);
708  if (I != nullptr)
709  SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
710 
711  if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
712  return false;
713 
714  if (!SupportedAM.IndexReg)
715  // No indexing allowed.
716  return AM.Scale == 0;
717  else
718  // Indexing is OK but no scale factor can be applied.
719  return AM.Scale == 0 || AM.Scale == 1;
720 }
721 
723  if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
724  return false;
725  unsigned FromBits = FromType->getPrimitiveSizeInBits();
726  unsigned ToBits = ToType->getPrimitiveSizeInBits();
727  return FromBits > ToBits;
728 }
729 
731  if (!FromVT.isInteger() || !ToVT.isInteger())
732  return false;
733  unsigned FromBits = FromVT.getSizeInBits();
734  unsigned ToBits = ToVT.getSizeInBits();
735  return FromBits > ToBits;
736 }
737 
738 //===----------------------------------------------------------------------===//
739 // Inline asm support
740 //===----------------------------------------------------------------------===//
741 
744  if (Constraint.size() == 1) {
745  switch (Constraint[0]) {
746  case 'a': // Address register
747  case 'd': // Data register (equivalent to 'r')
748  case 'f': // Floating-point register
749  case 'h': // High-part register
750  case 'r': // General-purpose register
751  return C_RegisterClass;
752 
753  case 'Q': // Memory with base and unsigned 12-bit displacement
754  case 'R': // Likewise, plus an index
755  case 'S': // Memory with base and signed 20-bit displacement
756  case 'T': // Likewise, plus an index
757  case 'm': // Equivalent to 'T'.
758  return C_Memory;
759 
760  case 'I': // Unsigned 8-bit constant
761  case 'J': // Unsigned 12-bit constant
762  case 'K': // Signed 16-bit constant
763  case 'L': // Signed 20-bit displacement (on all targets we support)
764  case 'M': // 0x7fffffff
765  return C_Other;
766 
767  default:
768  break;
769  }
770  }
771  return TargetLowering::getConstraintType(Constraint);
772 }
773 
776  const char *constraint) const {
777  ConstraintWeight weight = CW_Invalid;
778  Value *CallOperandVal = info.CallOperandVal;
779  // If we don't have a value, we can't do a match,
780  // but allow it at the lowest weight.
781  if (!CallOperandVal)
782  return CW_Default;
783  Type *type = CallOperandVal->getType();
784  // Look at the constraint type.
785  switch (*constraint) {
786  default:
787  weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
788  break;
789 
790  case 'a': // Address register
791  case 'd': // Data register (equivalent to 'r')
792  case 'h': // High-part register
793  case 'r': // General-purpose register
794  if (CallOperandVal->getType()->isIntegerTy())
795  weight = CW_Register;
796  break;
797 
798  case 'f': // Floating-point register
799  if (type->isFloatingPointTy())
800  weight = CW_Register;
801  break;
802 
803  case 'I': // Unsigned 8-bit constant
804  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
805  if (isUInt<8>(C->getZExtValue()))
806  weight = CW_Constant;
807  break;
808 
809  case 'J': // Unsigned 12-bit constant
810  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
811  if (isUInt<12>(C->getZExtValue()))
812  weight = CW_Constant;
813  break;
814 
815  case 'K': // Signed 16-bit constant
816  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
817  if (isInt<16>(C->getSExtValue()))
818  weight = CW_Constant;
819  break;
820 
821  case 'L': // Signed 20-bit displacement (on all targets we support)
822  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
823  if (isInt<20>(C->getSExtValue()))
824  weight = CW_Constant;
825  break;
826 
827  case 'M': // 0x7fffffff
828  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
829  if (C->getZExtValue() == 0x7fffffff)
830  weight = CW_Constant;
831  break;
832  }
833  return weight;
834 }
835 
836 // Parse a "{tNNN}" register constraint for which the register type "t"
837 // has already been verified. MC is the class associated with "t" and
838 // Map maps 0-based register numbers to LLVM register numbers.
839 static std::pair<unsigned, const TargetRegisterClass *>
841  const unsigned *Map) {
842  assert(*(Constraint.end()-1) == '}' && "Missing '}'");
843  if (isdigit(Constraint[2])) {
844  unsigned Index;
845  bool Failed =
846  Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
847  if (!Failed && Index < 16 && Map[Index])
848  return std::make_pair(Map[Index], RC);
849  }
850  return std::make_pair(0U, nullptr);
851 }
852 
853 std::pair<unsigned, const TargetRegisterClass *>
855  const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
856  if (Constraint.size() == 1) {
857  // GCC Constraint Letters
858  switch (Constraint[0]) {
859  default: break;
860  case 'd': // Data register (equivalent to 'r')
861  case 'r': // General-purpose register
862  if (VT == MVT::i64)
863  return std::make_pair(0U, &SystemZ::GR64BitRegClass);
864  else if (VT == MVT::i128)
865  return std::make_pair(0U, &SystemZ::GR128BitRegClass);
866  return std::make_pair(0U, &SystemZ::GR32BitRegClass);
867 
868  case 'a': // Address register
869  if (VT == MVT::i64)
870  return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
871  else if (VT == MVT::i128)
872  return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
873  return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
874 
875  case 'h': // High-part register (an LLVM extension)
876  return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
877 
878  case 'f': // Floating-point register
879  if (VT == MVT::f64)
880  return std::make_pair(0U, &SystemZ::FP64BitRegClass);
881  else if (VT == MVT::f128)
882  return std::make_pair(0U, &SystemZ::FP128BitRegClass);
883  return std::make_pair(0U, &SystemZ::FP32BitRegClass);
884  }
885  }
886  if (Constraint.size() > 0 && Constraint[0] == '{') {
887  // We need to override the default register parsing for GPRs and FPRs
888  // because the interpretation depends on VT. The internal names of
889  // the registers are also different from the external names
890  // (F0D and F0S instead of F0, etc.).
891  if (Constraint[1] == 'r') {
892  if (VT == MVT::i32)
893  return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
895  if (VT == MVT::i128)
896  return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
898  return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
900  }
901  if (Constraint[1] == 'f') {
902  if (VT == MVT::f32)
903  return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
905  if (VT == MVT::f128)
906  return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
908  return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
910  }
911  }
912  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
913 }
914 
916 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
917  std::vector<SDValue> &Ops,
918  SelectionDAG &DAG) const {
919  // Only support length 1 constraints for now.
920  if (Constraint.length() == 1) {
921  switch (Constraint[0]) {
922  case 'I': // Unsigned 8-bit constant
923  if (auto *C = dyn_cast<ConstantSDNode>(Op))
924  if (isUInt<8>(C->getZExtValue()))
925  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
926  Op.getValueType()));
927  return;
928 
929  case 'J': // Unsigned 12-bit constant
930  if (auto *C = dyn_cast<ConstantSDNode>(Op))
931  if (isUInt<12>(C->getZExtValue()))
932  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
933  Op.getValueType()));
934  return;
935 
936  case 'K': // Signed 16-bit constant
937  if (auto *C = dyn_cast<ConstantSDNode>(Op))
938  if (isInt<16>(C->getSExtValue()))
939  Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
940  Op.getValueType()));
941  return;
942 
943  case 'L': // Signed 20-bit displacement (on all targets we support)
944  if (auto *C = dyn_cast<ConstantSDNode>(Op))
945  if (isInt<20>(C->getSExtValue()))
946  Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
947  Op.getValueType()));
948  return;
949 
950  case 'M': // 0x7fffffff
951  if (auto *C = dyn_cast<ConstantSDNode>(Op))
952  if (C->getZExtValue() == 0x7fffffff)
953  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
954  Op.getValueType()));
955  return;
956  }
957  }
958  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
959 }
960 
961 //===----------------------------------------------------------------------===//
962 // Calling conventions
963 //===----------------------------------------------------------------------===//
964 
965 #include "SystemZGenCallingConv.inc"
966 
968  Type *ToType) const {
969  return isTruncateFree(FromType, ToType);
970 }
971 
973  return CI->isTailCall();
974 }
975 
976 // We do not yet support 128-bit single-element vector types. If the user
977 // attempts to use such types as function argument or return type, prefer
978 // to error out instead of emitting code violating the ABI.
979 static void VerifyVectorType(MVT VT, EVT ArgVT) {
980  if (ArgVT.isVector() && !VT.isVector())
981  report_fatal_error("Unsupported vector argument or return type");
982 }
983 
985  for (unsigned i = 0; i < Ins.size(); ++i)
986  VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
987 }
988 
990  for (unsigned i = 0; i < Outs.size(); ++i)
991  VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
992 }
993 
994 // Value is a value that has been passed to us in the location described by VA
995 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
996 // any loads onto Chain.
998  CCValAssign &VA, SDValue Chain,
999  SDValue Value) {
1000  // If the argument has been promoted from a smaller type, insert an
1001  // assertion to capture this.
1002  if (VA.getLocInfo() == CCValAssign::SExt)
1003  Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
1004  DAG.getValueType(VA.getValVT()));
1005  else if (VA.getLocInfo() == CCValAssign::ZExt)
1006  Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
1007  DAG.getValueType(VA.getValVT()));
1008 
1009  if (VA.isExtInLoc())
1010  Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1011  else if (VA.getLocInfo() == CCValAssign::BCvt) {
1012  // If this is a short vector argument loaded from the stack,
1013  // extend from i64 to full vector size and then bitcast.
1014  assert(VA.getLocVT() == MVT::i64);
1015  assert(VA.getValVT().isVector());
1016  Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1017  Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1018  } else
1019  assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1020  return Value;
1021 }
1022 
1023 // Value is a value of type VA.getValVT() that we need to copy into
1024 // the location described by VA. Return a copy of Value converted to
1025 // VA.getValVT(). The caller is responsible for handling indirect values.
1027  CCValAssign &VA, SDValue Value) {
1028  switch (VA.getLocInfo()) {
1029  case CCValAssign::SExt:
1030  return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1031  case CCValAssign::ZExt:
1032  return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1033  case CCValAssign::AExt:
1034  return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1035  case CCValAssign::BCvt:
1036  // If this is a short vector argument to be stored to the stack,
1037  // bitcast to v2i64 and then extract first element.
1038  assert(VA.getLocVT() == MVT::i64);
1039  assert(VA.getValVT().isVector());
1040  Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
1041  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1042  DAG.getConstant(0, DL, MVT::i32));
1043  case CCValAssign::Full:
1044  return Value;
1045  default:
1046  llvm_unreachable("Unhandled getLocInfo()");
1047  }
1048 }
1049 
1051  SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1052  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1053  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1054  MachineFunction &MF = DAG.getMachineFunction();
1055  MachineFrameInfo &MFI = MF.getFrameInfo();
1057  SystemZMachineFunctionInfo *FuncInfo =
1059  auto *TFL =
1060  static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
1061  EVT PtrVT = getPointerTy(DAG.getDataLayout());
1062 
1063  // Detect unsupported vector argument types.
1064  if (Subtarget.hasVector())
1065  VerifyVectorTypes(Ins);
1066 
1067  // Assign locations to all of the incoming arguments.
1069  SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1070  CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1071 
1072  unsigned NumFixedGPRs = 0;
1073  unsigned NumFixedFPRs = 0;
1074  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1075  SDValue ArgValue;
1076  CCValAssign &VA = ArgLocs[I];
1077  EVT LocVT = VA.getLocVT();
1078  if (VA.isRegLoc()) {
1079  // Arguments passed in registers
1080  const TargetRegisterClass *RC;
1081  switch (LocVT.getSimpleVT().SimpleTy) {
1082  default:
1083  // Integers smaller than i64 should be promoted to i64.
1084  llvm_unreachable("Unexpected argument type");
1085  case MVT::i32:
1086  NumFixedGPRs += 1;
1087  RC = &SystemZ::GR32BitRegClass;
1088  break;
1089  case MVT::i64:
1090  NumFixedGPRs += 1;
1091  RC = &SystemZ::GR64BitRegClass;
1092  break;
1093  case MVT::f32:
1094  NumFixedFPRs += 1;
1095  RC = &SystemZ::FP32BitRegClass;
1096  break;
1097  case MVT::f64:
1098  NumFixedFPRs += 1;
1099  RC = &SystemZ::FP64BitRegClass;
1100  break;
1101  case MVT::v16i8:
1102  case MVT::v8i16:
1103  case MVT::v4i32:
1104  case MVT::v2i64:
1105  case MVT::v4f32:
1106  case MVT::v2f64:
1107  RC = &SystemZ::VR128BitRegClass;
1108  break;
1109  }
1110 
1111  unsigned VReg = MRI.createVirtualRegister(RC);
1112  MRI.addLiveIn(VA.getLocReg(), VReg);
1113  ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1114  } else {
1115  assert(VA.isMemLoc() && "Argument not register or memory");
1116 
1117  // Create the frame index object for this incoming parameter.
1118  int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1119  VA.getLocMemOffset(), true);
1120 
1121  // Create the SelectionDAG nodes corresponding to a load
1122  // from this parameter. Unpromoted ints and floats are
1123  // passed as right-justified 8-byte values.
1124  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1125  if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1126  FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1127  DAG.getIntPtrConstant(4, DL));
1128  ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1130  }
1131 
1132  // Convert the value of the argument register into the value that's
1133  // being passed.
1134  if (VA.getLocInfo() == CCValAssign::Indirect) {
1135  InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1136  MachinePointerInfo()));
1137  // If the original argument was split (e.g. i128), we need
1138  // to load all parts of it here (using the same address).
1139  unsigned ArgIndex = Ins[I].OrigArgIndex;
1140  assert (Ins[I].PartOffset == 0);
1141  while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1142  CCValAssign &PartVA = ArgLocs[I + 1];
1143  unsigned PartOffset = Ins[I + 1].PartOffset;
1144  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1145  DAG.getIntPtrConstant(PartOffset, DL));
1146  InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1147  MachinePointerInfo()));
1148  ++I;
1149  }
1150  } else
1151  InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1152  }
1153 
1154  if (IsVarArg) {
1155  // Save the number of non-varargs registers for later use by va_start, etc.
1156  FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1157  FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1158 
1159  // Likewise the address (in the form of a frame index) of where the
1160  // first stack vararg would be. The 1-byte size here is arbitrary.
1161  int64_t StackSize = CCInfo.getNextStackOffset();
1162  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1163 
1164  // ...and a similar frame index for the caller-allocated save area
1165  // that will be used to store the incoming registers.
1166  int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
1167  unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1168  FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1169 
1170  // Store the FPR varargs in the reserved frame slots. (We store the
1171  // GPRs as part of the prologue.)
1172  if (NumFixedFPRs < SystemZ::NumArgFPRs) {
1173  SDValue MemOps[SystemZ::NumArgFPRs];
1174  for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1175  unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
1176  int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true);
1177  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1178  unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1179  &SystemZ::FP64BitRegClass);
1180  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1181  MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1183  }
1184  // Join the stores, which are independent of one another.
1185  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1186  makeArrayRef(&MemOps[NumFixedFPRs],
1187  SystemZ::NumArgFPRs-NumFixedFPRs));
1188  }
1189  }
1190 
1191  return Chain;
1192 }
1193 
1194 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1197  // Punt if there are any indirect or stack arguments, or if the call
1198  // needs the callee-saved argument register R6, or if the call uses
1199  // the callee-saved register arguments SwiftSelf and SwiftError.
1200  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1201  CCValAssign &VA = ArgLocs[I];
1202  if (VA.getLocInfo() == CCValAssign::Indirect)
1203  return false;
1204  if (!VA.isRegLoc())
1205  return false;
1206  unsigned Reg = VA.getLocReg();
1207  if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1208  return false;
1209  if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1210  return false;
1211  }
1212  return true;
1213 }
1214 
1215 SDValue
1217  SmallVectorImpl<SDValue> &InVals) const {
1218  SelectionDAG &DAG = CLI.DAG;
1219  SDLoc &DL = CLI.DL;
1221  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1223  SDValue Chain = CLI.Chain;
1224  SDValue Callee = CLI.Callee;
1225  bool &IsTailCall = CLI.IsTailCall;
1226  CallingConv::ID CallConv = CLI.CallConv;
1227  bool IsVarArg = CLI.IsVarArg;
1228  MachineFunction &MF = DAG.getMachineFunction();
1229  EVT PtrVT = getPointerTy(MF.getDataLayout());
1230 
1231  // Detect unsupported vector argument and return types.
1232  if (Subtarget.hasVector()) {
1233  VerifyVectorTypes(Outs);
1234  VerifyVectorTypes(Ins);
1235  }
1236 
1237  // Analyze the operands of the call, assigning locations to each operand.
1239  SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1240  ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1241 
1242  // We don't support GuaranteedTailCallOpt, only automatically-detected
1243  // sibling calls.
1244  if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1245  IsTailCall = false;
1246 
1247  // Get a count of how many bytes are to be pushed on the stack.
1248  unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1249 
1250  // Mark the start of the call.
1251  if (!IsTailCall)
1252  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1253 
1254  // Copy argument values to their designated locations.
1256  SmallVector<SDValue, 8> MemOpChains;
1257  SDValue StackPtr;
1258  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1259  CCValAssign &VA = ArgLocs[I];
1260  SDValue ArgValue = OutVals[I];
1261 
1262  if (VA.getLocInfo() == CCValAssign::Indirect) {
1263  // Store the argument in a stack slot and pass its address.
1264  SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1265  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1266  MemOpChains.push_back(
1267  DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1269  // If the original argument was split (e.g. i128), we need
1270  // to store all parts of it here (and pass just one address).
1271  unsigned ArgIndex = Outs[I].OrigArgIndex;
1272  assert (Outs[I].PartOffset == 0);
1273  while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1274  SDValue PartValue = OutVals[I + 1];
1275  unsigned PartOffset = Outs[I + 1].PartOffset;
1276  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1277  DAG.getIntPtrConstant(PartOffset, DL));
1278  MemOpChains.push_back(
1279  DAG.getStore(Chain, DL, PartValue, Address,
1281  ++I;
1282  }
1283  ArgValue = SpillSlot;
1284  } else
1285  ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1286 
1287  if (VA.isRegLoc())
1288  // Queue up the argument copies and emit them at the end.
1289  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1290  else {
1291  assert(VA.isMemLoc() && "Argument not register or memory");
1292 
1293  // Work out the address of the stack slot. Unpromoted ints and
1294  // floats are passed as right-justified 8-byte values.
1295  if (!StackPtr.getNode())
1296  StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1298  if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1299  Offset += 4;
1300  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1301  DAG.getIntPtrConstant(Offset, DL));
1302 
1303  // Emit the store.
1304  MemOpChains.push_back(
1305  DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1306  }
1307  }
1308 
1309  // Join the stores, which are independent of one another.
1310  if (!MemOpChains.empty())
1311  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1312 
1313  // Accept direct calls by converting symbolic call addresses to the
1314  // associated Target* opcodes. Force %r1 to be used for indirect
1315  // tail calls.
1316  SDValue Glue;
1317  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1318  Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1319  Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1320  } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1321  Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1322  Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1323  } else if (IsTailCall) {
1324  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1325  Glue = Chain.getValue(1);
1326  Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1327  }
1328 
1329  // Build a sequence of copy-to-reg nodes, chained and glued together.
1330  for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1331  Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1332  RegsToPass[I].second, Glue);
1333  Glue = Chain.getValue(1);
1334  }
1335 
1336  // The first call operand is the chain and the second is the target address.
1338  Ops.push_back(Chain);
1339  Ops.push_back(Callee);
1340 
1341  // Add argument registers to the end of the list so that they are
1342  // known live into the call.
1343  for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1344  Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1345  RegsToPass[I].second.getValueType()));
1346 
1347  // Add a register mask operand representing the call-preserved registers.
1348  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1349  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1350  assert(Mask && "Missing call preserved mask for calling convention");
1351  Ops.push_back(DAG.getRegisterMask(Mask));
1352 
1353  // Glue the call to the argument copies, if any.
1354  if (Glue.getNode())
1355  Ops.push_back(Glue);
1356 
1357  // Emit the call.
1358  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1359  if (IsTailCall)
1360  return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1361  Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1362  Glue = Chain.getValue(1);
1363 
1364  // Mark the end of the call, which is glued to the call itself.
1365  Chain = DAG.getCALLSEQ_END(Chain,
1366  DAG.getConstant(NumBytes, DL, PtrVT, true),
1367  DAG.getConstant(0, DL, PtrVT, true),
1368  Glue, DL);
1369  Glue = Chain.getValue(1);
1370 
1371  // Assign locations to each value returned by this call.
1373  CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1374  RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1375 
1376  // Copy all of the result registers out of their specified physreg.
1377  for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1378  CCValAssign &VA = RetLocs[I];
1379 
1380  // Copy the value out, gluing the copy to the end of the call sequence.
1381  SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1382  VA.getLocVT(), Glue);
1383  Chain = RetValue.getValue(1);
1384  Glue = RetValue.getValue(2);
1385 
1386  // Convert the value of the return register into the value that's
1387  // being returned.
1388  InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1389  }
1390 
1391  return Chain;
1392 }
1393 
1396  MachineFunction &MF, bool isVarArg,
1397  const SmallVectorImpl<ISD::OutputArg> &Outs,
1398  LLVMContext &Context) const {
1399  // Detect unsupported vector return types.
1400  if (Subtarget.hasVector())
1401  VerifyVectorTypes(Outs);
1402 
1403  // Special case that we cannot easily detect in RetCC_SystemZ since
1404  // i128 is not a legal type.
1405  for (auto &Out : Outs)
1406  if (Out.ArgVT == MVT::i128)
1407  return false;
1408 
1410  CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1411  return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1412 }
1413 
1414 SDValue
1416  bool IsVarArg,
1417  const SmallVectorImpl<ISD::OutputArg> &Outs,
1418  const SmallVectorImpl<SDValue> &OutVals,
1419  const SDLoc &DL, SelectionDAG &DAG) const {
1420  MachineFunction &MF = DAG.getMachineFunction();
1421 
1422  // Detect unsupported vector return types.
1423  if (Subtarget.hasVector())
1424  VerifyVectorTypes(Outs);
1425 
1426  // Assign locations to each returned value.
1428  CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1429  RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1430 
1431  // Quick exit for void returns
1432  if (RetLocs.empty())
1433  return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1434 
1435  // Copy the result values into the output registers.
1436  SDValue Glue;
1437  SmallVector<SDValue, 4> RetOps;
1438  RetOps.push_back(Chain);
1439  for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1440  CCValAssign &VA = RetLocs[I];
1441  SDValue RetValue = OutVals[I];
1442 
1443  // Make the return register live on exit.
1444  assert(VA.isRegLoc() && "Can only return in registers!");
1445 
1446  // Promote the value as required.
1447  RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1448 
1449  // Chain and glue the copies together.
1450  unsigned Reg = VA.getLocReg();
1451  Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1452  Glue = Chain.getValue(1);
1453  RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1454  }
1455 
1456  // Update chain and glue.
1457  RetOps[0] = Chain;
1458  if (Glue.getNode())
1459  RetOps.push_back(Glue);
1460 
1461  return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1462 }
1463 
1464 // Return true if Op is an intrinsic node with chain that returns the CC value
1465 // as its only (other) argument. Provide the associated SystemZISD opcode and
1466 // the mask of valid CC values if so.
1467 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1468  unsigned &CCValid) {
1469  unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1470  switch (Id) {
1471  case Intrinsic::s390_tbegin:
1472  Opcode = SystemZISD::TBEGIN;
1473  CCValid = SystemZ::CCMASK_TBEGIN;
1474  return true;
1475 
1476  case Intrinsic::s390_tbegin_nofloat:
1477  Opcode = SystemZISD::TBEGIN_NOFLOAT;
1478  CCValid = SystemZ::CCMASK_TBEGIN;
1479  return true;
1480 
1481  case Intrinsic::s390_tend:
1482  Opcode = SystemZISD::TEND;
1483  CCValid = SystemZ::CCMASK_TEND;
1484  return true;
1485 
1486  default:
1487  return false;
1488  }
1489 }
1490 
1491 // Return true if Op is an intrinsic node without chain that returns the
1492 // CC value as its final argument. Provide the associated SystemZISD
1493 // opcode and the mask of valid CC values if so.
1494 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1495  unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1496  switch (Id) {
1497  case Intrinsic::s390_vpkshs:
1498  case Intrinsic::s390_vpksfs:
1499  case Intrinsic::s390_vpksgs:
1500  Opcode = SystemZISD::PACKS_CC;
1501  CCValid = SystemZ::CCMASK_VCMP;
1502  return true;
1503 
1504  case Intrinsic::s390_vpklshs:
1505  case Intrinsic::s390_vpklsfs:
1506  case Intrinsic::s390_vpklsgs:
1507  Opcode = SystemZISD::PACKLS_CC;
1508  CCValid = SystemZ::CCMASK_VCMP;
1509  return true;
1510 
1511  case Intrinsic::s390_vceqbs:
1512  case Intrinsic::s390_vceqhs:
1513  case Intrinsic::s390_vceqfs:
1514  case Intrinsic::s390_vceqgs:
1515  Opcode = SystemZISD::VICMPES;
1516  CCValid = SystemZ::CCMASK_VCMP;
1517  return true;
1518 
1519  case Intrinsic::s390_vchbs:
1520  case Intrinsic::s390_vchhs:
1521  case Intrinsic::s390_vchfs:
1522  case Intrinsic::s390_vchgs:
1523  Opcode = SystemZISD::VICMPHS;
1524  CCValid = SystemZ::CCMASK_VCMP;
1525  return true;
1526 
1527  case Intrinsic::s390_vchlbs:
1528  case Intrinsic::s390_vchlhs:
1529  case Intrinsic::s390_vchlfs:
1530  case Intrinsic::s390_vchlgs:
1531  Opcode = SystemZISD::VICMPHLS;
1532  CCValid = SystemZ::CCMASK_VCMP;
1533  return true;
1534 
1535  case Intrinsic::s390_vtm:
1536  Opcode = SystemZISD::VTM;
1537  CCValid = SystemZ::CCMASK_VCMP;
1538  return true;
1539 
1540  case Intrinsic::s390_vfaebs:
1541  case Intrinsic::s390_vfaehs:
1542  case Intrinsic::s390_vfaefs:
1543  Opcode = SystemZISD::VFAE_CC;
1544  CCValid = SystemZ::CCMASK_ANY;
1545  return true;
1546 
1547  case Intrinsic::s390_vfaezbs:
1548  case Intrinsic::s390_vfaezhs:
1549  case Intrinsic::s390_vfaezfs:
1550  Opcode = SystemZISD::VFAEZ_CC;
1551  CCValid = SystemZ::CCMASK_ANY;
1552  return true;
1553 
1554  case Intrinsic::s390_vfeebs:
1555  case Intrinsic::s390_vfeehs:
1556  case Intrinsic::s390_vfeefs:
1557  Opcode = SystemZISD::VFEE_CC;
1558  CCValid = SystemZ::CCMASK_ANY;
1559  return true;
1560 
1561  case Intrinsic::s390_vfeezbs:
1562  case Intrinsic::s390_vfeezhs:
1563  case Intrinsic::s390_vfeezfs:
1564  Opcode = SystemZISD::VFEEZ_CC;
1565  CCValid = SystemZ::CCMASK_ANY;
1566  return true;
1567 
1568  case Intrinsic::s390_vfenebs:
1569  case Intrinsic::s390_vfenehs:
1570  case Intrinsic::s390_vfenefs:
1571  Opcode = SystemZISD::VFENE_CC;
1572  CCValid = SystemZ::CCMASK_ANY;
1573  return true;
1574 
1575  case Intrinsic::s390_vfenezbs:
1576  case Intrinsic::s390_vfenezhs:
1577  case Intrinsic::s390_vfenezfs:
1578  Opcode = SystemZISD::VFENEZ_CC;
1579  CCValid = SystemZ::CCMASK_ANY;
1580  return true;
1581 
1582  case Intrinsic::s390_vistrbs:
1583  case Intrinsic::s390_vistrhs:
1584  case Intrinsic::s390_vistrfs:
1585  Opcode = SystemZISD::VISTR_CC;
1587  return true;
1588 
1589  case Intrinsic::s390_vstrcbs:
1590  case Intrinsic::s390_vstrchs:
1591  case Intrinsic::s390_vstrcfs:
1592  Opcode = SystemZISD::VSTRC_CC;
1593  CCValid = SystemZ::CCMASK_ANY;
1594  return true;
1595 
1596  case Intrinsic::s390_vstrczbs:
1597  case Intrinsic::s390_vstrczhs:
1598  case Intrinsic::s390_vstrczfs:
1599  Opcode = SystemZISD::VSTRCZ_CC;
1600  CCValid = SystemZ::CCMASK_ANY;
1601  return true;
1602 
1603  case Intrinsic::s390_vfcedbs:
1604  case Intrinsic::s390_vfcesbs:
1605  Opcode = SystemZISD::VFCMPES;
1606  CCValid = SystemZ::CCMASK_VCMP;
1607  return true;
1608 
1609  case Intrinsic::s390_vfchdbs:
1610  case Intrinsic::s390_vfchsbs:
1611  Opcode = SystemZISD::VFCMPHS;
1612  CCValid = SystemZ::CCMASK_VCMP;
1613  return true;
1614 
1615  case Intrinsic::s390_vfchedbs:
1616  case Intrinsic::s390_vfchesbs:
1617  Opcode = SystemZISD::VFCMPHES;
1618  CCValid = SystemZ::CCMASK_VCMP;
1619  return true;
1620 
1621  case Intrinsic::s390_vftcidb:
1622  case Intrinsic::s390_vftcisb:
1623  Opcode = SystemZISD::VFTCI;
1624  CCValid = SystemZ::CCMASK_VCMP;
1625  return true;
1626 
1627  case Intrinsic::s390_tdc:
1628  Opcode = SystemZISD::TDC;
1629  CCValid = SystemZ::CCMASK_TDC;
1630  return true;
1631 
1632  default:
1633  return false;
1634  }
1635 }
1636 
1637 // Emit an intrinsic with chain with a glued value instead of its CC result.
1639  unsigned Opcode) {
1640  // Copy all operands except the intrinsic ID.
1641  unsigned NumOps = Op.getNumOperands();
1643  Ops.reserve(NumOps - 1);
1644  Ops.push_back(Op.getOperand(0));
1645  for (unsigned I = 2; I < NumOps; ++I)
1646  Ops.push_back(Op.getOperand(I));
1647 
1648  assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1649  SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1650  SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1651  SDValue OldChain = SDValue(Op.getNode(), 1);
1652  SDValue NewChain = SDValue(Intr.getNode(), 0);
1653  DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1654  return Intr;
1655 }
1656 
1657 // Emit an intrinsic with a glued value instead of its CC result.
1659  unsigned Opcode) {
1660  // Copy all operands except the intrinsic ID.
1661  unsigned NumOps = Op.getNumOperands();
1663  Ops.reserve(NumOps - 1);
1664  for (unsigned I = 1; I < NumOps; ++I)
1665  Ops.push_back(Op.getOperand(I));
1666 
1667  if (Op->getNumValues() == 1)
1668  return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1669  assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1670  SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1671  return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1672 }
1673 
1674 // CC is a comparison that will be implemented using an integer or
1675 // floating-point comparison. Return the condition code mask for
1676 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1677 // unsigned comparisons and clear for signed ones. In the floating-point
1678 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1679 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1680 #define CONV(X) \
1681  case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1682  case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1683  case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1684 
1685  switch (CC) {
1686  default:
1687  llvm_unreachable("Invalid integer condition!");
1688 
1689  CONV(EQ);
1690  CONV(NE);
1691  CONV(GT);
1692  CONV(GE);
1693  CONV(LT);
1694  CONV(LE);
1695 
1696  case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1697  case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1698  }
1699 #undef CONV
1700 }
1701 
1702 // Return a sequence for getting a 1 from an IPM result when CC has a
1703 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1704 // The handling of CC values outside CCValid doesn't matter.
1705 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1706  // Deal with cases where the result can be taken directly from a bit
1707  // of the IPM result.
1708  if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1709  return IPMConversion(0, 0, SystemZ::IPM_CC);
1710  if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1711  return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1712 
1713  // Deal with cases where we can add a value to force the sign bit
1714  // to contain the right value. Putting the bit in 31 means we can
1715  // use SRL rather than RISBG(L), and also makes it easier to get a
1716  // 0/-1 value, so it has priority over the other tests below.
1717  //
1718  // These sequences rely on the fact that the upper two bits of the
1719  // IPM result are zero.
1720  uint64_t TopBit = uint64_t(1) << 31;
1721  if (CCMask == (CCValid & SystemZ::CCMASK_0))
1722  return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1723  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1724  return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1725  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1727  | SystemZ::CCMASK_2)))
1728  return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1729  if (CCMask == (CCValid & SystemZ::CCMASK_3))
1730  return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1731  if (CCMask == (CCValid & (SystemZ::CCMASK_1
1733  | SystemZ::CCMASK_3)))
1734  return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1735 
1736  // Next try inverting the value and testing a bit. 0/1 could be
1737  // handled this way too, but we dealt with that case above.
1738  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1739  return IPMConversion(-1, 0, SystemZ::IPM_CC);
1740 
1741  // Handle cases where adding a value forces a non-sign bit to contain
1742  // the right value.
1743  if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1744  return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1745  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1746  return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1747 
1748  // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1749  // can be done by inverting the low CC bit and applying one of the
1750  // sign-based extractions above.
1751  if (CCMask == (CCValid & SystemZ::CCMASK_1))
1752  return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1753  if (CCMask == (CCValid & SystemZ::CCMASK_2))
1754  return IPMConversion(1 << SystemZ::IPM_CC,
1755  TopBit - (3 << SystemZ::IPM_CC), 31);
1756  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1757  | SystemZ::CCMASK_1
1758  | SystemZ::CCMASK_3)))
1759  return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1760  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1761  | SystemZ::CCMASK_2
1762  | SystemZ::CCMASK_3)))
1763  return IPMConversion(1 << SystemZ::IPM_CC,
1764  TopBit - (1 << SystemZ::IPM_CC), 31);
1765 
1766  llvm_unreachable("Unexpected CC combination");
1767 }
1768 
1769 // If C can be converted to a comparison against zero, adjust the operands
1770 // as necessary.
1771 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1772  if (C.ICmpType == SystemZICMP::UnsignedOnly)
1773  return;
1774 
1775  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1776  if (!ConstOp1)
1777  return;
1778 
1779  int64_t Value = ConstOp1->getSExtValue();
1780  if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1781  (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1782  (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1783  (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1784  C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1785  C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1786  }
1787 }
1788 
1789 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1790 // adjust the operands as necessary.
1791 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1792  Comparison &C) {
1793  // For us to make any changes, it must a comparison between a single-use
1794  // load and a constant.
1795  if (!C.Op0.hasOneUse() ||
1796  C.Op0.getOpcode() != ISD::LOAD ||
1797  C.Op1.getOpcode() != ISD::Constant)
1798  return;
1799 
1800  // We must have an 8- or 16-bit load.
1801  auto *Load = cast<LoadSDNode>(C.Op0);
1802  unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1803  if (NumBits != 8 && NumBits != 16)
1804  return;
1805 
1806  // The load must be an extending one and the constant must be within the
1807  // range of the unextended value.
1808  auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1809  uint64_t Value = ConstOp1->getZExtValue();
1810  uint64_t Mask = (1 << NumBits) - 1;
1811  if (Load->getExtensionType() == ISD::SEXTLOAD) {
1812  // Make sure that ConstOp1 is in range of C.Op0.
1813  int64_t SignedValue = ConstOp1->getSExtValue();
1814  if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1815  return;
1816  if (C.ICmpType != SystemZICMP::SignedOnly) {
1817  // Unsigned comparison between two sign-extended values is equivalent
1818  // to unsigned comparison between two zero-extended values.
1819  Value &= Mask;
1820  } else if (NumBits == 8) {
1821  // Try to treat the comparison as unsigned, so that we can use CLI.
1822  // Adjust CCMask and Value as necessary.
1823  if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1824  // Test whether the high bit of the byte is set.
1825  Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1826  else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1827  // Test whether the high bit of the byte is clear.
1828  Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1829  else
1830  // No instruction exists for this combination.
1831  return;
1832  C.ICmpType = SystemZICMP::UnsignedOnly;
1833  }
1834  } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1835  if (Value > Mask)
1836  return;
1837  // If the constant is in range, we can use any comparison.
1838  C.ICmpType = SystemZICMP::Any;
1839  } else
1840  return;
1841 
1842  // Make sure that the first operand is an i32 of the right extension type.
1843  ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1844  ISD::SEXTLOAD :
1845  ISD::ZEXTLOAD);
1846  if (C.Op0.getValueType() != MVT::i32 ||
1847  Load->getExtensionType() != ExtType)
1848  C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
1849  Load->getBasePtr(), Load->getPointerInfo(),
1850  Load->getMemoryVT(), Load->getAlignment(),
1851  Load->getMemOperand()->getFlags());
1852 
1853  // Make sure that the second operand is an i32 with the right value.
1854  if (C.Op1.getValueType() != MVT::i32 ||
1855  Value != ConstOp1->getZExtValue())
1856  C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1857 }
1858 
1859 // Return true if Op is either an unextended load, or a load suitable
1860 // for integer register-memory comparisons of type ICmpType.
1861 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1862  auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1863  if (Load) {
1864  // There are no instructions to compare a register with a memory byte.
1865  if (Load->getMemoryVT() == MVT::i8)
1866  return false;
1867  // Otherwise decide on extension type.
1868  switch (Load->getExtensionType()) {
1869  case ISD::NON_EXTLOAD:
1870  return true;
1871  case ISD::SEXTLOAD:
1872  return ICmpType != SystemZICMP::UnsignedOnly;
1873  case ISD::ZEXTLOAD:
1874  return ICmpType != SystemZICMP::SignedOnly;
1875  default:
1876  break;
1877  }
1878  }
1879  return false;
1880 }
1881 
1882 // Return true if it is better to swap the operands of C.
1883 static bool shouldSwapCmpOperands(const Comparison &C) {
1884  // Leave f128 comparisons alone, since they have no memory forms.
1885  if (C.Op0.getValueType() == MVT::f128)
1886  return false;
1887 
1888  // Always keep a floating-point constant second, since comparisons with
1889  // zero can use LOAD TEST and comparisons with other constants make a
1890  // natural memory operand.
1891  if (isa<ConstantFPSDNode>(C.Op1))
1892  return false;
1893 
1894  // Never swap comparisons with zero since there are many ways to optimize
1895  // those later.
1896  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1897  if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1898  return false;
1899 
1900  // Also keep natural memory operands second if the loaded value is
1901  // only used here. Several comparisons have memory forms.
1902  if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1903  return false;
1904 
1905  // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1906  // In that case we generally prefer the memory to be second.
1907  if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1908  // The only exceptions are when the second operand is a constant and
1909  // we can use things like CHHSI.
1910  if (!ConstOp1)
1911  return true;
1912  // The unsigned memory-immediate instructions can handle 16-bit
1913  // unsigned integers.
1914  if (C.ICmpType != SystemZICMP::SignedOnly &&
1915  isUInt<16>(ConstOp1->getZExtValue()))
1916  return false;
1917  // The signed memory-immediate instructions can handle 16-bit
1918  // signed integers.
1919  if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1920  isInt<16>(ConstOp1->getSExtValue()))
1921  return false;
1922  return true;
1923  }
1924 
1925  // Try to promote the use of CGFR and CLGFR.
1926  unsigned Opcode0 = C.Op0.getOpcode();
1927  if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1928  return true;
1929  if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1930  return true;
1931  if (C.ICmpType != SystemZICMP::SignedOnly &&
1932  Opcode0 == ISD::AND &&
1933  C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1934  cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1935  return true;
1936 
1937  return false;
1938 }
1939 
1940 // Return a version of comparison CC mask CCMask in which the LT and GT
1941 // actions are swapped.
1942 static unsigned reverseCCMask(unsigned CCMask) {
1943  return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1945  (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1946  (CCMask & SystemZ::CCMASK_CMP_UO));
1947 }
1948 
1949 // Check whether C tests for equality between X and Y and whether X - Y
1950 // or Y - X is also computed. In that case it's better to compare the
1951 // result of the subtraction against zero.
1952 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
1953  Comparison &C) {
1954  if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1955  C.CCMask == SystemZ::CCMASK_CMP_NE) {
1956  for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1957  SDNode *N = *I;
1958  if (N->getOpcode() == ISD::SUB &&
1959  ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1960  (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1961  C.Op0 = SDValue(N, 0);
1962  C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1963  return;
1964  }
1965  }
1966  }
1967 }
1968 
1969 // Check whether C compares a floating-point value with zero and if that
1970 // floating-point value is also negated. In this case we can use the
1971 // negation to set CC, so avoiding separate LOAD AND TEST and
1972 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1973 static void adjustForFNeg(Comparison &C) {
1974  auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1975  if (C1 && C1->isZero()) {
1976  for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1977  SDNode *N = *I;
1978  if (N->getOpcode() == ISD::FNEG) {
1979  C.Op0 = SDValue(N, 0);
1980  C.CCMask = reverseCCMask(C.CCMask);
1981  return;
1982  }
1983  }
1984  }
1985 }
1986 
1987 // Check whether C compares (shl X, 32) with 0 and whether X is
1988 // also sign-extended. In that case it is better to test the result
1989 // of the sign extension using LTGFR.
1990 //
1991 // This case is important because InstCombine transforms a comparison
1992 // with (sext (trunc X)) into a comparison with (shl X, 32).
1993 static void adjustForLTGFR(Comparison &C) {
1994  // Check for a comparison between (shl X, 32) and 0.
1995  if (C.Op0.getOpcode() == ISD::SHL &&
1996  C.Op0.getValueType() == MVT::i64 &&
1997  C.Op1.getOpcode() == ISD::Constant &&
1998  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1999  auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2000  if (C1 && C1->getZExtValue() == 32) {
2001  SDValue ShlOp0 = C.Op0.getOperand(0);
2002  // See whether X has any SIGN_EXTEND_INREG uses.
2003  for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
2004  SDNode *N = *I;
2005  if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2006  cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2007  C.Op0 = SDValue(N, 0);
2008  return;
2009  }
2010  }
2011  }
2012  }
2013 }
2014 
2015 // If C compares the truncation of an extending load, try to compare
2016 // the untruncated value instead. This exposes more opportunities to
2017 // reuse CC.
2018 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2019  Comparison &C) {
2020  if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2021  C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2022  C.Op1.getOpcode() == ISD::Constant &&
2023  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2024  auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2025  if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
2026  unsigned Type = L->getExtensionType();
2027  if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2028  (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2029  C.Op0 = C.Op0.getOperand(0);
2030  C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2031  }
2032  }
2033  }
2034 }
2035 
2036 // Return true if shift operation N has an in-range constant shift value.
2037 // Store it in ShiftVal if so.
2038 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2039  auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2040  if (!Shift)
2041  return false;
2042 
2043  uint64_t Amount = Shift->getZExtValue();
2044  if (Amount >= N.getValueSizeInBits())
2045  return false;
2046 
2047  ShiftVal = Amount;
2048  return true;
2049 }
2050 
2051 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
2052 // instruction and whether the CC value is descriptive enough to handle
2053 // a comparison of type Opcode between the AND result and CmpVal.
2054 // CCMask says which comparison result is being tested and BitSize is
2055 // the number of bits in the operands. If TEST UNDER MASK can be used,
2056 // return the corresponding CC mask, otherwise return 0.
2057 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2058  uint64_t Mask, uint64_t CmpVal,
2059  unsigned ICmpType) {
2060  assert(Mask != 0 && "ANDs with zero should have been removed by now");
2061 
2062  // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2063  if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2064  !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2065  return 0;
2066 
2067  // Work out the masks for the lowest and highest bits.
2068  unsigned HighShift = 63 - countLeadingZeros(Mask);
2069  uint64_t High = uint64_t(1) << HighShift;
2070  uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
2071 
2072  // Signed ordered comparisons are effectively unsigned if the sign
2073  // bit is dropped.
2074  bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2075 
2076  // Check for equality comparisons with 0, or the equivalent.
2077  if (CmpVal == 0) {
2078  if (CCMask == SystemZ::CCMASK_CMP_EQ)
2079  return SystemZ::CCMASK_TM_ALL_0;
2080  if (CCMask == SystemZ::CCMASK_CMP_NE)
2082  }
2083  if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2084  if (CCMask == SystemZ::CCMASK_CMP_LT)
2085  return SystemZ::CCMASK_TM_ALL_0;
2086  if (CCMask == SystemZ::CCMASK_CMP_GE)
2088  }
2089  if (EffectivelyUnsigned && CmpVal < Low) {
2090  if (CCMask == SystemZ::CCMASK_CMP_LE)
2091  return SystemZ::CCMASK_TM_ALL_0;
2092  if (CCMask == SystemZ::CCMASK_CMP_GT)
2094  }
2095 
2096  // Check for equality comparisons with the mask, or the equivalent.
2097  if (CmpVal == Mask) {
2098  if (CCMask == SystemZ::CCMASK_CMP_EQ)
2099  return SystemZ::CCMASK_TM_ALL_1;
2100  if (CCMask == SystemZ::CCMASK_CMP_NE)
2102  }
2103  if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2104  if (CCMask == SystemZ::CCMASK_CMP_GT)
2105  return SystemZ::CCMASK_TM_ALL_1;
2106  if (CCMask == SystemZ::CCMASK_CMP_LE)
2108  }
2109  if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2110  if (CCMask == SystemZ::CCMASK_CMP_GE)
2111  return SystemZ::CCMASK_TM_ALL_1;
2112  if (CCMask == SystemZ::CCMASK_CMP_LT)
2114  }
2115 
2116  // Check for ordered comparisons with the top bit.
2117  if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2118  if (CCMask == SystemZ::CCMASK_CMP_LE)
2119  return SystemZ::CCMASK_TM_MSB_0;
2120  if (CCMask == SystemZ::CCMASK_CMP_GT)
2121  return SystemZ::CCMASK_TM_MSB_1;
2122  }
2123  if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2124  if (CCMask == SystemZ::CCMASK_CMP_LT)
2125  return SystemZ::CCMASK_TM_MSB_0;
2126  if (CCMask == SystemZ::CCMASK_CMP_GE)
2127  return SystemZ::CCMASK_TM_MSB_1;
2128  }
2129 
2130  // If there are just two bits, we can do equality checks for Low and High
2131  // as well.
2132  if (Mask == Low + High) {
2133  if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2135  if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2137  if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2139  if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2141  }
2142 
2143  // Looks like we've exhausted our options.
2144  return 0;
2145 }
2146 
2147 // See whether C can be implemented as a TEST UNDER MASK instruction.
2148 // Update the arguments with the TM version if so.
2149 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2150  Comparison &C) {
2151  // Check that we have a comparison with a constant.
2152  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2153  if (!ConstOp1)
2154  return;
2155  uint64_t CmpVal = ConstOp1->getZExtValue();
2156 
2157  // Check whether the nonconstant input is an AND with a constant mask.
2158  Comparison NewC(C);
2159  uint64_t MaskVal;
2160  ConstantSDNode *Mask = nullptr;
2161  if (C.Op0.getOpcode() == ISD::AND) {
2162  NewC.Op0 = C.Op0.getOperand(0);
2163  NewC.Op1 = C.Op0.getOperand(1);
2164  Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2165  if (!Mask)
2166  return;
2167  MaskVal = Mask->getZExtValue();
2168  } else {
2169  // There is no instruction to compare with a 64-bit immediate
2170  // so use TMHH instead if possible. We need an unsigned ordered
2171  // comparison with an i64 immediate.
2172  if (NewC.Op0.getValueType() != MVT::i64 ||
2173  NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2174  NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2175  NewC.ICmpType == SystemZICMP::SignedOnly)
2176  return;
2177  // Convert LE and GT comparisons into LT and GE.
2178  if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2179  NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2180  if (CmpVal == uint64_t(-1))
2181  return;
2182  CmpVal += 1;
2183  NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2184  }
2185  // If the low N bits of Op1 are zero than the low N bits of Op0 can
2186  // be masked off without changing the result.
2187  MaskVal = -(CmpVal & -CmpVal);
2188  NewC.ICmpType = SystemZICMP::UnsignedOnly;
2189  }
2190  if (!MaskVal)
2191  return;
2192 
2193  // Check whether the combination of mask, comparison value and comparison
2194  // type are suitable.
2195  unsigned BitSize = NewC.Op0.getValueSizeInBits();
2196  unsigned NewCCMask, ShiftVal;
2197  if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2198  NewC.Op0.getOpcode() == ISD::SHL &&
2199  isSimpleShift(NewC.Op0, ShiftVal) &&
2200  (MaskVal >> ShiftVal != 0) &&
2201  (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2202  MaskVal >> ShiftVal,
2203  CmpVal >> ShiftVal,
2204  SystemZICMP::Any))) {
2205  NewC.Op0 = NewC.Op0.getOperand(0);
2206  MaskVal >>= ShiftVal;
2207  } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2208  NewC.Op0.getOpcode() == ISD::SRL &&
2209  isSimpleShift(NewC.Op0, ShiftVal) &&
2210  (MaskVal << ShiftVal != 0) &&
2211  (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2212  MaskVal << ShiftVal,
2213  CmpVal << ShiftVal,
2215  NewC.Op0 = NewC.Op0.getOperand(0);
2216  MaskVal <<= ShiftVal;
2217  } else {
2218  NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2219  NewC.ICmpType);
2220  if (!NewCCMask)
2221  return;
2222  }
2223 
2224  // Go ahead and make the change.
2225  C.Opcode = SystemZISD::TM;
2226  C.Op0 = NewC.Op0;
2227  if (Mask && Mask->getZExtValue() == MaskVal)
2228  C.Op1 = SDValue(Mask, 0);
2229  else
2230  C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2231  C.CCValid = SystemZ::CCMASK_TM;
2232  C.CCMask = NewCCMask;
2233 }
2234 
2235 // Return a Comparison that tests the condition-code result of intrinsic
2236 // node Call against constant integer CC using comparison code Cond.
2237 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2238 // and CCValid is the set of possible condition-code results.
2239 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2240  SDValue Call, unsigned CCValid, uint64_t CC,
2241  ISD::CondCode Cond) {
2242  Comparison C(Call, SDValue());
2243  C.Opcode = Opcode;
2244  C.CCValid = CCValid;
2245  if (Cond == ISD::SETEQ)
2246  // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2247  C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2248  else if (Cond == ISD::SETNE)
2249  // ...and the inverse of that.
2250  C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2251  else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2252  // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2253  // always true for CC>3.
2254  C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2255  else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2256  // ...and the inverse of that.
2257  C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2258  else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2259  // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2260  // always true for CC>3.
2261  C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2262  else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2263  // ...and the inverse of that.
2264  C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2265  else
2266  llvm_unreachable("Unexpected integer comparison type");
2267  C.CCMask &= CCValid;
2268  return C;
2269 }
2270 
2271 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2272 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2273  ISD::CondCode Cond, const SDLoc &DL) {
2274  if (CmpOp1.getOpcode() == ISD::Constant) {
2275  uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2276  unsigned Opcode, CCValid;
2277  if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2278  CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2279  isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2280  return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2281  if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2282  CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2283  isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2284  return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2285  }
2286  Comparison C(CmpOp0, CmpOp1);
2287  C.CCMask = CCMaskForCondCode(Cond);
2288  if (C.Op0.getValueType().isFloatingPoint()) {
2289  C.CCValid = SystemZ::CCMASK_FCMP;
2290  C.Opcode = SystemZISD::FCMP;
2291  adjustForFNeg(C);
2292  } else {
2293  C.CCValid = SystemZ::CCMASK_ICMP;
2294  C.Opcode = SystemZISD::ICMP;
2295  // Choose the type of comparison. Equality and inequality tests can
2296  // use either signed or unsigned comparisons. The choice also doesn't
2297  // matter if both sign bits are known to be clear. In those cases we
2298  // want to give the main isel code the freedom to choose whichever
2299  // form fits best.
2300  if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2301  C.CCMask == SystemZ::CCMASK_CMP_NE ||
2302  (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2303  C.ICmpType = SystemZICMP::Any;
2304  else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2305  C.ICmpType = SystemZICMP::UnsignedOnly;
2306  else
2307  C.ICmpType = SystemZICMP::SignedOnly;
2308  C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2309  adjustZeroCmp(DAG, DL, C);
2310  adjustSubwordCmp(DAG, DL, C);
2311  adjustForSubtraction(DAG, DL, C);
2312  adjustForLTGFR(C);
2313  adjustICmpTruncate(DAG, DL, C);
2314  }
2315 
2316  if (shouldSwapCmpOperands(C)) {
2317  std::swap(C.Op0, C.Op1);
2318  C.CCMask = reverseCCMask(C.CCMask);
2319  }
2320 
2321  adjustForTestUnderMask(DAG, DL, C);
2322  return C;
2323 }
2324 
2325 // Emit the comparison instruction described by C.
2326 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2327  if (!C.Op1.getNode()) {
2328  SDValue Op;
2329  switch (C.Op0.getOpcode()) {
2331  Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2332  break;
2334  Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2335  break;
2336  default:
2337  llvm_unreachable("Invalid comparison operands");
2338  }
2339  return SDValue(Op.getNode(), Op->getNumValues() - 1);
2340  }
2341  if (C.Opcode == SystemZISD::ICMP)
2342  return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2343  DAG.getConstant(C.ICmpType, DL, MVT::i32));
2344  if (C.Opcode == SystemZISD::TM) {
2345  bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2346  bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2347  return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2348  DAG.getConstant(RegisterOnly, DL, MVT::i32));
2349  }
2350  return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2351 }
2352 
2353 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2354 // 64 bits. Extend is the extension type to use. Store the high part
2355 // in Hi and the low part in Lo.
2356 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2357  SDValue Op0, SDValue Op1, SDValue &Hi,
2358  SDValue &Lo) {
2359  Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2360  Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2361  SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2362  Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2363  DAG.getConstant(32, DL, MVT::i64));
2364  Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2365  Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2366 }
2367 
2368 // Lower a binary operation that produces two VT results, one in each
2369 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2370 // and Opcode performs the GR128 operation. Store the even register result
2371 // in Even and the odd register result in Odd.
2372 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2373  unsigned Opcode, SDValue Op0, SDValue Op1,
2374  SDValue &Even, SDValue &Odd) {
2375  SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2376  bool Is32Bit = is32Bit(VT);
2377  Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2378  Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2379 }
2380 
2381 // Return an i32 value that is 1 if the CC value produced by Glue is
2382 // in the mask CCMask and 0 otherwise. CC is known to have a value
2383 // in CCValid, so other values can be ignored.
2384 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue Glue,
2385  unsigned CCValid, unsigned CCMask) {
2386  IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2387  SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2388 
2389  if (Conversion.XORValue)
2390  Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2391  DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2392 
2393  if (Conversion.AddValue)
2394  Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2395  DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2396 
2397  // The SHR/AND sequence should get optimized to an RISBG.
2398  Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2399  DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2400  if (Conversion.Bit != 31)
2401  Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2402  DAG.getConstant(1, DL, MVT::i32));
2403  return Result;
2404 }
2405 
2406 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2407 // be done directly. IsFP is true if CC is for a floating-point rather than
2408 // integer comparison.
2409 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2410  switch (CC) {
2411  case ISD::SETOEQ:
2412  case ISD::SETEQ:
2413  return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2414 
2415  case ISD::SETOGE:
2416  case ISD::SETGE:
2417  return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2418 
2419  case ISD::SETOGT:
2420  case ISD::SETGT:
2421  return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2422 
2423  case ISD::SETUGT:
2424  return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2425 
2426  default:
2427  return 0;
2428  }
2429 }
2430 
2431 // Return the SystemZISD vector comparison operation for CC or its inverse,
2432 // or 0 if neither can be done directly. Indicate in Invert whether the
2433 // result is for the inverse of CC. IsFP is true if CC is for a
2434 // floating-point rather than integer comparison.
2435 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2436  bool &Invert) {
2437  if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2438  Invert = false;
2439  return Opcode;
2440  }
2441 
2442  CC = ISD::getSetCCInverse(CC, !IsFP);
2443  if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2444  Invert = true;
2445  return Opcode;
2446  }
2447 
2448  return 0;
2449 }
2450 
2451 // Return a v2f64 that contains the extended form of elements Start and Start+1
2452 // of v4f32 value Op.
2453 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2454  SDValue Op) {
2455  int Mask[] = { Start, -1, Start + 1, -1 };
2456  Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2457  return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2458 }
2459 
2460 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2461 // producing a result of type VT.
2462 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2463  const SDLoc &DL, EVT VT,
2464  SDValue CmpOp0,
2465  SDValue CmpOp1) const {
2466  // There is no hardware support for v4f32 (unless we have the vector
2467  // enhancements facility 1), so extend the vector into two v2f64s
2468  // and compare those.
2469  if (CmpOp0.getValueType() == MVT::v4f32 &&
2470  !Subtarget.hasVectorEnhancements1()) {
2471  SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2472  SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2473  SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2474  SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2475  SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2476  SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2477  return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2478  }
2479  return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2480 }
2481 
2482 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2483 // an integer mask of type VT.
2484 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
2485  const SDLoc &DL, EVT VT,
2486  ISD::CondCode CC,
2487  SDValue CmpOp0,
2488  SDValue CmpOp1) const {
2489  bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2490  bool Invert = false;
2491  SDValue Cmp;
2492  switch (CC) {
2493  // Handle tests for order using (or (ogt y x) (oge x y)).
2494  case ISD::SETUO:
2495  Invert = true;
2497  case ISD::SETO: {
2498  assert(IsFP && "Unexpected integer comparison");
2499  SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2500  SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2501  Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2502  break;
2503  }
2504 
2505  // Handle <> tests using (or (ogt y x) (ogt x y)).
2506  case ISD::SETUEQ:
2507  Invert = true;
2509  case ISD::SETONE: {
2510  assert(IsFP && "Unexpected integer comparison");
2511  SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2512  SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2513  Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2514  break;
2515  }
2516 
2517  // Otherwise a single comparison is enough. It doesn't really
2518  // matter whether we try the inversion or the swap first, since
2519  // there are no cases where both work.
2520  default:
2521  if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2522  Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2523  else {
2525  if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2526  Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2527  else
2528  llvm_unreachable("Unhandled comparison");
2529  }
2530  break;
2531  }
2532  if (Invert) {
2534  DAG.getConstant(65535, DL, MVT::i32));
2535  Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2536  Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2537  }
2538  return Cmp;
2539 }
2540 
2541 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2542  SelectionDAG &DAG) const {
2543  SDValue CmpOp0 = Op.getOperand(0);
2544  SDValue CmpOp1 = Op.getOperand(1);
2545  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2546  SDLoc DL(Op);
2547  EVT VT = Op.getValueType();
2548  if (VT.isVector())
2549  return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2550 
2551  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2552  SDValue Glue = emitCmp(DAG, DL, C);
2553  return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2554 }
2555 
2556 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2557  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2558  SDValue CmpOp0 = Op.getOperand(2);
2559  SDValue CmpOp1 = Op.getOperand(3);
2560  SDValue Dest = Op.getOperand(4);
2561  SDLoc DL(Op);
2562 
2563  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2564  SDValue Glue = emitCmp(DAG, DL, C);
2565  return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2566  Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2567  DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2568 }
2569 
2570 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2571 // allowing Pos and Neg to be wider than CmpOp.
2572 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2573  return (Neg.getOpcode() == ISD::SUB &&
2574  Neg.getOperand(0).getOpcode() == ISD::Constant &&
2575  cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2576  Neg.getOperand(1) == Pos &&
2577  (Pos == CmpOp ||
2578  (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2579  Pos.getOperand(0) == CmpOp)));
2580 }
2581 
2582 // Return the absolute or negative absolute of Op; IsNegative decides which.
2583 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2584  bool IsNegative) {
2585  Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2586  if (IsNegative)
2587  Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2588  DAG.getConstant(0, DL, Op.getValueType()), Op);
2589  return Op;
2590 }
2591 
2592 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2593  SelectionDAG &DAG) const {
2594  SDValue CmpOp0 = Op.getOperand(0);
2595  SDValue CmpOp1 = Op.getOperand(1);
2596  SDValue TrueOp = Op.getOperand(2);
2597  SDValue FalseOp = Op.getOperand(3);
2598  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2599  SDLoc DL(Op);
2600 
2601  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2602 
2603  // Check for absolute and negative-absolute selections, including those
2604  // where the comparison value is sign-extended (for LPGFR and LNGFR).
2605  // This check supplements the one in DAGCombiner.
2606  if (C.Opcode == SystemZISD::ICMP &&
2607  C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2608  C.CCMask != SystemZ::CCMASK_CMP_NE &&
2609  C.Op1.getOpcode() == ISD::Constant &&
2610  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2611  if (isAbsolute(C.Op0, TrueOp, FalseOp))
2612  return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2613  if (isAbsolute(C.Op0, FalseOp, TrueOp))
2614  return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2615  }
2616 
2617  SDValue Glue = emitCmp(DAG, DL, C);
2618 
2619  // Special case for handling -1/0 results. The shifts we use here
2620  // should get optimized with the IPM conversion sequence.
2621  auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2622  auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2623  if (TrueC && FalseC) {
2624  int64_t TrueVal = TrueC->getSExtValue();
2625  int64_t FalseVal = FalseC->getSExtValue();
2626  if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2627  // Invert the condition if we want -1 on false.
2628  if (TrueVal == 0)
2629  C.CCMask ^= C.CCValid;
2630  SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2631  EVT VT = Op.getValueType();
2632  // Extend the result to VT. Upper bits are ignored.
2633  if (!is32Bit(VT))
2634  Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2635  // Sign-extend from the low bit.
2636  SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2637  SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2638  return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2639  }
2640  }
2641 
2642  SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2643  DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2644 
2645  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2646  return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2647 }
2648 
2649 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2650  SelectionDAG &DAG) const {
2651  SDLoc DL(Node);
2652  const GlobalValue *GV = Node->getGlobal();
2653  int64_t Offset = Node->getOffset();
2654  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2656 
2657  SDValue Result;
2658  if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2659  // Assign anchors at 1<<12 byte boundaries.
2660  uint64_t Anchor = Offset & ~uint64_t(0xfff);
2661  Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2662  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2663 
2664  // The offset can be folded into the address if it is aligned to a halfword.
2665  Offset -= Anchor;
2666  if (Offset != 0 && (Offset & 1) == 0) {
2667  SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2668  Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2669  Offset = 0;
2670  }
2671  } else {
2672  Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2673  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2674  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2676  }
2677 
2678  // If there was a non-zero offset that we didn't fold, create an explicit
2679  // addition for it.
2680  if (Offset != 0)
2681  Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2682  DAG.getConstant(Offset, DL, PtrVT));
2683 
2684  return Result;
2685 }
2686 
2687 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2688  SelectionDAG &DAG,
2689  unsigned Opcode,
2690  SDValue GOTOffset) const {
2691  SDLoc DL(Node);
2692  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2693  SDValue Chain = DAG.getEntryNode();
2694  SDValue Glue;
2695 
2696  // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2697  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2698  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2699  Glue = Chain.getValue(1);
2700  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2701  Glue = Chain.getValue(1);
2702 
2703  // The first call operand is the chain and the second is the TLS symbol.
2705  Ops.push_back(Chain);
2706  Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2707  Node->getValueType(0),
2708  0, 0));
2709 
2710  // Add argument registers to the end of the list so that they are
2711  // known live into the call.
2712  Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2713  Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2714 
2715  // Add a register mask operand representing the call-preserved registers.
2716  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2717  const uint32_t *Mask =
2719  assert(Mask && "Missing call preserved mask for calling convention");
2720  Ops.push_back(DAG.getRegisterMask(Mask));
2721 
2722  // Glue the call to the argument copies.
2723  Ops.push_back(Glue);
2724 
2725  // Emit the call.
2726  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2727  Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2728  Glue = Chain.getValue(1);
2729 
2730  // Copy the return value from %r2.
2731  return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2732 }
2733 
2734 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2735  SelectionDAG &DAG) const {
2736  SDValue Chain = DAG.getEntryNode();
2737  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2738 
2739  // The high part of the thread pointer is in access register 0.
2740  SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
2741  TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2742 
2743  // The low part of the thread pointer is in access register 1.
2744  SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
2745  TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2746 
2747  // Merge them into a single 64-bit address.
2748  SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2749  DAG.getConstant(32, DL, PtrVT));
2750  return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2751 }
2752 
2753 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2754  SelectionDAG &DAG) const {
2755  if (DAG.getTarget().Options.EmulatedTLS)
2756  return LowerToTLSEmulatedModel(Node, DAG);
2757  SDLoc DL(Node);
2758  const GlobalValue *GV = Node->getGlobal();
2759  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2760  TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2761 
2762  SDValue TP = lowerThreadPointer(DL, DAG);
2763 
2764  // Get the offset of GA from the thread pointer, based on the TLS model.
2765  SDValue Offset;
2766  switch (model) {
2767  case TLSModel::GeneralDynamic: {
2768  // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2771 
2772  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2773  Offset = DAG.getLoad(
2774  PtrVT, DL, DAG.getEntryNode(), Offset,
2776 
2777  // Call __tls_get_offset to retrieve the offset.
2778  Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2779  break;
2780  }
2781 
2782  case TLSModel::LocalDynamic: {
2783  // Load the GOT offset of the module ID.
2786 
2787  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2788  Offset = DAG.getLoad(
2789  PtrVT, DL, DAG.getEntryNode(), Offset,
2791 
2792  // Call __tls_get_offset to retrieve the module base offset.
2793  Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2794 
2795  // Note: The SystemZLDCleanupPass will remove redundant computations
2796  // of the module base offset. Count total number of local-dynamic
2797  // accesses to trigger execution of that pass.
2801 
2802  // Add the per-symbol offset.
2804 
2805  SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2806  DTPOffset = DAG.getLoad(
2807  PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2809 
2810  Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2811  break;
2812  }
2813 
2814  case TLSModel::InitialExec: {
2815  // Load the offset from the GOT.
2816  Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2818  Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2819  Offset =
2820  DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2822  break;
2823  }
2824 
2825  case TLSModel::LocalExec: {
2826  // Force the offset into the constant pool and load it from there.
2829 
2830  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2831  Offset = DAG.getLoad(
2832  PtrVT, DL, DAG.getEntryNode(), Offset,
2834  break;
2835  }
2836  }
2837 
2838  // Add the base and offset together.
2839  return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2840 }
2841 
2842 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2843  SelectionDAG &DAG) const {
2844  SDLoc DL(Node);
2845  const BlockAddress *BA = Node->getBlockAddress();
2846  int64_t Offset = Node->getOffset();
2847  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2848 
2849  SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2850  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2851  return Result;
2852 }
2853 
2854 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2855  SelectionDAG &DAG) const {
2856  SDLoc DL(JT);
2857  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2858  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2859 
2860  // Use LARL to load the address of the table.
2861  return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2862 }
2863 
2864 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2865  SelectionDAG &DAG) const {
2866  SDLoc DL(CP);
2867  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2868 
2869  SDValue Result;
2870  if (CP->isMachineConstantPoolEntry())
2871  Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2872  CP->getAlignment());
2873  else
2874  Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2875  CP->getAlignment(), CP->getOffset());
2876 
2877  // Use LARL to load the address of the constant pool entry.
2878  return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2879 }
2880 
2881 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2882  SelectionDAG &DAG) const {
2883  MachineFunction &MF = DAG.getMachineFunction();
2884  MachineFrameInfo &MFI = MF.getFrameInfo();
2885  MFI.setFrameAddressIsTaken(true);
2886 
2887  SDLoc DL(Op);
2888  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2889  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2890 
2891  // If the back chain frame index has not been allocated yet, do so.
2893  int BackChainIdx = FI->getFramePointerSaveIndex();
2894  if (!BackChainIdx) {
2895  // By definition, the frame address is the address of the back chain.
2896  BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2897  FI->setFramePointerSaveIndex(BackChainIdx);
2898  }
2899  SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2900 
2901  // FIXME The frontend should detect this case.
2902  if (Depth > 0) {
2903  report_fatal_error("Unsupported stack frame traversal count");
2904  }
2905 
2906  return BackChain;
2907 }
2908 
2909 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2910  SelectionDAG &DAG) const {
2911  MachineFunction &MF = DAG.getMachineFunction();
2912  MachineFrameInfo &MFI = MF.getFrameInfo();
2913  MFI.setReturnAddressIsTaken(true);
2914 
2916  return SDValue();
2917 
2918  SDLoc DL(Op);
2919  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2920  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2921 
2922  // FIXME The frontend should detect this case.
2923  if (Depth > 0) {
2924  report_fatal_error("Unsupported stack frame traversal count");
2925  }
2926 
2927  // Return R14D, which has the return address. Mark it an implicit live-in.
2928  unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2929  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2930 }
2931 
2932 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2933  SelectionDAG &DAG) const {
2934  SDLoc DL(Op);
2935  SDValue In = Op.getOperand(0);
2936  EVT InVT = In.getValueType();
2937  EVT ResVT = Op.getValueType();
2938 
2939  // Convert loads directly. This is normally done by DAGCombiner,
2940  // but we need this case for bitcasts that are created during lowering
2941  // and which are then lowered themselves.
2942  if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2943  if (ISD::isNormalLoad(LoadN))
2944  return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2945  LoadN->getMemOperand());
2946 
2947  if (InVT == MVT::i32 && ResVT == MVT::f32) {
2948  SDValue In64;
2949  if (Subtarget.hasHighWord()) {
2950  SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2951  MVT::i64);
2952  In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2953  MVT::i64, SDValue(U64, 0), In);
2954  } else {
2955  In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2956  In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2957  DAG.getConstant(32, DL, MVT::i64));
2958  }
2959  SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2960  return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2961  DL, MVT::f32, Out64);
2962  }
2963  if (InVT == MVT::f32 && ResVT == MVT::i32) {
2964  SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2965  SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2966  MVT::f64, SDValue(U64, 0), In);
2967  SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2968  if (Subtarget.hasHighWord())
2969  return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2970  MVT::i32, Out64);
2971  SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2972  DAG.getConstant(32, DL, MVT::i64));
2973  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2974  }
2975  llvm_unreachable("Unexpected bitcast combination");
2976 }
2977 
2978 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2979  SelectionDAG &DAG) const {
2980  MachineFunction &MF = DAG.getMachineFunction();
2981  SystemZMachineFunctionInfo *FuncInfo =
2983  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2984 
2985  SDValue Chain = Op.getOperand(0);
2986  SDValue Addr = Op.getOperand(1);
2987  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2988  SDLoc DL(Op);
2989 
2990  // The initial values of each field.
2991  const unsigned NumFields = 4;
2992  SDValue Fields[NumFields] = {
2993  DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2994  DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2995  DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2996  DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2997  };
2998 
2999  // Store each field into its respective slot.
3000  SDValue MemOps[NumFields];
3001  unsigned Offset = 0;
3002  for (unsigned I = 0; I < NumFields; ++I) {
3003  SDValue FieldAddr = Addr;
3004  if (Offset != 0)
3005  FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
3006  DAG.getIntPtrConstant(Offset, DL));
3007  MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
3008  MachinePointerInfo(SV, Offset));
3009  Offset += 8;
3010  }
3011  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3012 }
3013 
3014 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
3015  SelectionDAG &DAG) const {
3016  SDValue Chain = Op.getOperand(0);
3017  SDValue DstPtr = Op.getOperand(1);
3018  SDValue SrcPtr = Op.getOperand(2);
3019  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3020  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3021  SDLoc DL(Op);
3022 
3023  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
3024  /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
3025  /*isTailCall*/false,
3026  MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
3027 }
3028 
3029 SDValue SystemZTargetLowering::
3030 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
3031  const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3032  MachineFunction &MF = DAG.getMachineFunction();
3033  bool RealignOpt = !MF.getFunction()-> hasFnAttribute("no-realign-stack");
3034  bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3035 
3036  SDValue Chain = Op.getOperand(0);
3037  SDValue Size = Op.getOperand(1);
3038  SDValue Align = Op.getOperand(2);
3039  SDLoc DL(Op);
3040 
3041  // If user has set the no alignment function attribute, ignore
3042  // alloca alignments.
3043  uint64_t AlignVal = (RealignOpt ?
3044  dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3045 
3046  uint64_t StackAlign = TFI->getStackAlignment();
3047  uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3048  uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3049 
3050  unsigned SPReg = getStackPointerRegisterToSaveRestore();
3051  SDValue NeededSpace = Size;
3052 
3053  // Get a reference to the stack pointer.
3054  SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
3055 
3056  // If we need a backchain, save it now.
3057  SDValue Backchain;
3058  if (StoreBackchain)
3059  Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3060 
3061  // Add extra space for alignment if needed.
3062  if (ExtraAlignSpace)
3063  NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
3064  DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3065 
3066  // Get the new stack pointer value.
3067  SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
3068 
3069  // Copy the new stack pointer back.
3070  Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
3071 
3072  // The allocated data lives above the 160 bytes allocated for the standard
3073  // frame, plus any outgoing stack arguments. We don't know how much that
3074  // amounts to yet, so emit a special ADJDYNALLOC placeholder.
3075  SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3076  SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3077 
3078  // Dynamically realign if needed.
3079  if (RequiredAlign > StackAlign) {
3080  Result =
3081  DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3082  DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3083  Result =
3084  DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3085  DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3086  }
3087 
3088  if (StoreBackchain)
3089  Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3090 
3091  SDValue Ops[2] = { Result, Chain };
3092  return DAG.getMergeValues(Ops, DL);
3093 }
3094 
3095 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3096  SDValue Op, SelectionDAG &DAG) const {
3097  SDLoc DL(Op);
3098 
3099  return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3100 }
3101 
3102 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3103  SelectionDAG &DAG) const {
3104  EVT VT = Op.getValueType();
3105  SDLoc DL(Op);
3106  SDValue Ops[2];
3107  if (is32Bit(VT))
3108  // Just do a normal 64-bit multiplication and extract the results.
3109  // We define this so that it can be used for constant division.
3111  Op.getOperand(1), Ops[1], Ops[0]);
3112  else if (Subtarget.hasMiscellaneousExtensions2())
3113  // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3114  // the high result in the even register. ISD::SMUL_LOHI is defined to
3115  // return the low half first, so the results are in reverse order.
3117  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3118  else {
3119  // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3120  //
3121  // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3122  //
3123  // but using the fact that the upper halves are either all zeros
3124  // or all ones:
3125  //
3126  // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
3127  //
3128  // and grouping the right terms together since they are quicker than the
3129  // multiplication:
3130  //
3131  // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
3132  SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
3133  SDValue LL = Op.getOperand(0);
3134  SDValue RL = Op.getOperand(1);
3135  SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
3136  SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
3137  // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3138  // the high result in the even register. ISD::SMUL_LOHI is defined to
3139  // return the low half first, so the results are in reverse order.
3141  LL, RL, Ops[1], Ops[0]);
3142  SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
3143  SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
3144  SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
3145  Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
3146  }
3147  return DAG.getMergeValues(Ops, DL);
3148 }
3149 
3150 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3151  SelectionDAG &DAG) const {
3152  EVT VT = Op.getValueType();
3153  SDLoc DL(Op);
3154  SDValue Ops[2];
3155  if (is32Bit(VT))
3156  // Just do a normal 64-bit multiplication and extract the results.
3157  // We define this so that it can be used for constant division.
3159  Op.getOperand(1), Ops[1], Ops[0]);
3160  else
3161  // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3162  // the high result in the even register. ISD::UMUL_LOHI is defined to
3163  // return the low half first, so the results are in reverse order.
3165  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3166  return DAG.getMergeValues(Ops, DL);
3167 }
3168 
3169 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3170  SelectionDAG &DAG) const {
3171  SDValue Op0 = Op.getOperand(0);
3172  SDValue Op1 = Op.getOperand(1);
3173  EVT VT = Op.getValueType();
3174  SDLoc DL(Op);
3175 
3176  // We use DSGF for 32-bit division. This means the first operand must
3177  // always be 64-bit, and the second operand should be 32-bit whenever
3178  // that is possible, to improve performance.
3179  if (is32Bit(VT))
3180  Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3181  else if (DAG.ComputeNumSignBits(Op1) > 32)
3182  Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3183 
3184  // DSG(F) returns the remainder in the even register and the
3185  // quotient in the odd register.
3186  SDValue Ops[2];
3187  lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
3188  return DAG.getMergeValues(Ops, DL);
3189 }
3190 
3191 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3192  SelectionDAG &DAG) const {
3193  EVT VT = Op.getValueType();
3194  SDLoc DL(Op);
3195 
3196  // DL(G) returns the remainder in the even register and the
3197  // quotient in the odd register.
3198  SDValue Ops[2];
3200  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3201  return DAG.getMergeValues(Ops, DL);
3202 }
3203 
3204 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3205  assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3206 
3207  // Get the known-zero masks for each operand.
3208  SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3209  KnownBits Known[2];
3210  DAG.computeKnownBits(Ops[0], Known[0]);
3211  DAG.computeKnownBits(Ops[1], Known[1]);
3212 
3213  // See if the upper 32 bits of one operand and the lower 32 bits of the
3214  // other are known zero. They are the low and high operands respectively.
3215  uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3216  Known[1].Zero.getZExtValue() };
3217  unsigned High, Low;
3218  if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3219  High = 1, Low = 0;
3220  else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3221  High = 0, Low = 1;
3222  else
3223  return Op;
3224 
3225  SDValue LowOp = Ops[Low];
3226  SDValue HighOp = Ops[High];
3227 
3228  // If the high part is a constant, we're better off using IILH.
3229  if (HighOp.getOpcode() == ISD::Constant)
3230  return Op;
3231 
3232  // If the low part is a constant that is outside the range of LHI,
3233  // then we're better off using IILF.
3234  if (LowOp.getOpcode() == ISD::Constant) {
3235  int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3236  if (!isInt<16>(Value))
3237  return Op;
3238  }
3239 
3240  // Check whether the high part is an AND that doesn't change the
3241  // high 32 bits and just masks out low bits. We can skip it if so.
3242  if (HighOp.getOpcode() == ISD::AND &&
3243  HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3244  SDValue HighOp0 = HighOp.getOperand(0);
3245  uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3246  if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3247  HighOp = HighOp0;
3248  }
3249 
3250  // Take advantage of the fact that all GR32 operations only change the
3251  // low 32 bits by truncating Low to an i32 and inserting it directly
3252  // using a subreg. The interesting cases are those where the truncation
3253  // can be folded.
3254  SDLoc DL(Op);
3255  SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3256  return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3257  MVT::i64, HighOp, Low32);
3258 }
3259 
3260 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3261  SelectionDAG &DAG) const {
3262  EVT VT = Op.getValueType();
3263  SDLoc DL(Op);
3264  Op = Op.getOperand(0);
3265 
3266  // Handle vector types via VPOPCT.
3267  if (VT.isVector()) {
3268  Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3269  Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3270  switch (VT.getScalarSizeInBits()) {
3271  case 8:
3272  break;
3273  case 16: {
3274  Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3275  SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3276  SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3277  Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3278  Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3279  break;
3280  }
3281  case 32: {
3283  DAG.getConstant(0, DL, MVT::i32));
3284  Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3285  break;
3286  }
3287  case 64: {
3289  DAG.getConstant(0, DL, MVT::i32));
3290  Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3291  Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3292  break;
3293  }
3294  default:
3295  llvm_unreachable("Unexpected type");
3296  }
3297  return Op;
3298  }
3299 
3300  // Get the known-zero mask for the operand.
3301  KnownBits Known;
3302  DAG.computeKnownBits(Op, Known);
3303  unsigned NumSignificantBits = (~Known.Zero).getActiveBits();
3304  if (NumSignificantBits == 0)
3305  return DAG.getConstant(0, DL, VT);
3306 
3307  // Skip known-zero high parts of the operand.
3308  int64_t OrigBitSize = VT.getSizeInBits();
3309  int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3310  BitSize = std::min(BitSize, OrigBitSize);
3311 
3312  // The POPCNT instruction counts the number of bits in each byte.
3313  Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3314  Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3315  Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3316 
3317  // Add up per-byte counts in a binary tree. All bits of Op at
3318  // position larger than BitSize remain zero throughout.
3319  for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3320  SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3321  if (BitSize != OrigBitSize)
3322  Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3323  DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3324  Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3325  }
3326 
3327  // Extract overall result from high byte.
3328  if (BitSize > 8)
3329  Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3330  DAG.getConstant(BitSize - 8, DL, VT));
3331 
3332  return Op;
3333 }
3334 
3335 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3336  SelectionDAG &DAG) const {
3337  SDLoc DL(Op);
3338  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3339  cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3340  SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
3341  cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3342 
3343  // The only fence that needs an instruction is a sequentially-consistent
3344  // cross-thread fence.
3345  if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3346  FenceSSID == SyncScope::System) {
3347  return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3348  Op.getOperand(0)),
3349  0);
3350  }
3351 
3352  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3353  return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3354 }
3355 
3356 // Op is an atomic load. Lower it into a normal volatile load.
3357 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3358  SelectionDAG &DAG) const {
3359  auto *Node = cast<AtomicSDNode>(Op.getNode());
3360  return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3361  Node->getChain(), Node->getBasePtr(),
3362  Node->getMemoryVT(), Node->getMemOperand());
3363 }
3364 
3365 // Op is an atomic store. Lower it into a normal volatile store.
3366 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3367  SelectionDAG &DAG) const {
3368  auto *Node = cast<AtomicSDNode>(Op.getNode());
3369  SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3370  Node->getBasePtr(), Node->getMemoryVT(),
3371  Node->getMemOperand());
3372  // We have to enforce sequential consistency by performing a
3373  // serialization operation after the store.
3374  if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent)
3375  Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
3376  MVT::Other, Chain), 0);
3377  return Chain;
3378 }
3379 
3380 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3381 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3382 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3383  SelectionDAG &DAG,
3384  unsigned Opcode) const {
3385  auto *Node = cast<AtomicSDNode>(Op.getNode());
3386 
3387  // 32-bit operations need no code outside the main loop.
3388  EVT NarrowVT = Node->getMemoryVT();
3389  EVT WideVT = MVT::i32;
3390  if (NarrowVT == WideVT)
3391  return Op;
3392 
3393  int64_t BitSize = NarrowVT.getSizeInBits();
3394  SDValue ChainIn = Node->getChain();
3395  SDValue Addr = Node->getBasePtr();
3396  SDValue Src2 = Node->getVal();
3397  MachineMemOperand *MMO = Node->getMemOperand();
3398  SDLoc DL(Node);
3399  EVT PtrVT = Addr.getValueType();
3400 
3401  // Convert atomic subtracts of constants into additions.
3402  if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3403  if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3405  Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3406  }
3407 
3408  // Get the address of the containing word.
3409  SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3410  DAG.getConstant(-4, DL, PtrVT));
3411 
3412  // Get the number of bits that the word must be rotated left in order
3413  // to bring the field to the top bits of a GR32.
3414  SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3415  DAG.getConstant(3, DL, PtrVT));
3416  BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3417 
3418  // Get the complementing shift amount, for rotating a field in the top
3419  // bits back to its proper position.
3420  SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3421  DAG.getConstant(0, DL, WideVT), BitShift);
3422 
3423  // Extend the source operand to 32 bits and prepare it for the inner loop.
3424  // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3425  // operations require the source to be shifted in advance. (This shift
3426  // can be folded if the source is constant.) For AND and NAND, the lower
3427  // bits must be set, while for other opcodes they should be left clear.
3428  if (Opcode != SystemZISD::ATOMIC_SWAPW)
3429  Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3430  DAG.getConstant(32 - BitSize, DL, WideVT));
3431  if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3433  Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3434  DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3435 
3436  // Construct the ATOMIC_LOADW_* node.
3437  SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3438  SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3439  DAG.getConstant(BitSize, DL, WideVT) };
3440  SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3441  NarrowVT, MMO);
3442 
3443  // Rotate the result of the final CS so that the field is in the lower
3444  // bits of a GR32, then truncate it.
3445  SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3446  DAG.getConstant(BitSize, DL, WideVT));
3447  SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3448 
3449  SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3450  return DAG.getMergeValues(RetOps, DL);
3451 }
3452 
3453 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3454 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3455 // operations into additions.
3456 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3457  SelectionDAG &DAG) const {
3458  auto *Node = cast<AtomicSDNode>(Op.getNode());
3459  EVT MemVT = Node->getMemoryVT();
3460  if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3461  // A full-width operation.
3462  assert(Op.getValueType() == MemVT && "Mismatched VTs");
3463  SDValue Src2 = Node->getVal();
3464  SDValue NegSrc2;
3465  SDLoc DL(Src2);
3466 
3467  if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3468  // Use an addition if the operand is constant and either LAA(G) is
3469  // available or the negative value is in the range of A(G)FHI.
3470  int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3471  if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3472  NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3473  } else if (Subtarget.hasInterlockedAccess1())
3474  // Use LAA(G) if available.
3475  NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3476  Src2);
3477 
3478  if (NegSrc2.getNode())
3479  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3480  Node->getChain(), Node->getBasePtr(), NegSrc2,
3481  Node->getMemOperand());
3482 
3483  // Use the node as-is.
3484  return Op;
3485  }
3486 
3487  return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3488 }
3489 
3490 // Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
3491 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3492  SelectionDAG &DAG) const {
3493  auto *Node = cast<AtomicSDNode>(Op.getNode());
3494  SDValue ChainIn = Node->getOperand(0);
3495  SDValue Addr = Node->getOperand(1);
3496  SDValue CmpVal = Node->getOperand(2);
3497  SDValue SwapVal = Node->getOperand(3);
3498  MachineMemOperand *MMO = Node->getMemOperand();
3499  SDLoc DL(Node);
3500 
3501  // We have native support for 32-bit and 64-bit compare and swap, but we
3502  // still need to expand extracting the "success" result from the CC.
3503  EVT NarrowVT = Node->getMemoryVT();
3504  EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
3505  if (NarrowVT == WideVT) {
3506  SDVTList Tys = DAG.getVTList(WideVT, MVT::Other, MVT::Glue);
3507  SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
3509  DL, Tys, Ops, NarrowVT, MMO);
3510  SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(2),
3512 
3513  DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
3515  DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(1));
3516  return SDValue();
3517  }
3518 
3519  // Convert 8-bit and 16-bit compare and swap to a loop, implemented
3520  // via a fullword ATOMIC_CMP_SWAPW operation.
3521  int64_t BitSize = NarrowVT.getSizeInBits();
3522  EVT PtrVT = Addr.getValueType();
3523 
3524  // Get the address of the containing word.
3525  SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3526  DAG.getConstant(-4, DL, PtrVT));
3527 
3528  // Get the number of bits that the word must be rotated left in order
3529  // to bring the field to the top bits of a GR32.
3530  SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3531  DAG.getConstant(3, DL, PtrVT));
3532  BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3533 
3534  // Get the complementing shift amount, for rotating a field in the top
3535  // bits back to its proper position.
3536  SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3537  DAG.getConstant(0, DL, WideVT), BitShift);
3538 
3539  // Construct the ATOMIC_CMP_SWAPW node.
3540  SDVTList VTList = DAG.getVTList(WideVT, MVT::Other, MVT::Glue);
3541  SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3542  NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3544  VTList, Ops, NarrowVT, MMO);
3545  SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(2),
3547 
3548  DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
3550  DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(1));
3551  return SDValue();
3552 }
3553 
3554 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3555  SelectionDAG &DAG) const {
3556  MachineFunction &MF = DAG.getMachineFunction();
3557  MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3558  return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3559  SystemZ::R15D, Op.getValueType());
3560 }
3561 
3562 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3563  SelectionDAG &DAG) const {
3564  MachineFunction &MF = DAG.getMachineFunction();
3565  MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3566  bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3567 
3568  SDValue Chain = Op.getOperand(0);
3569  SDValue NewSP = Op.getOperand(1);
3570  SDValue Backchain;
3571  SDLoc DL(Op);
3572 
3573  if (StoreBackchain) {
3574  SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
3575  Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3576  }
3577 
3578  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
3579 
3580  if (StoreBackchain)
3581  Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3582 
3583  return Chain;
3584 }
3585 
3586 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3587  SelectionDAG &DAG) const {
3588  bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3589  if (!IsData)
3590  // Just preserve the chain.
3591  return Op.getOperand(0);
3592 
3593  SDLoc DL(Op);
3594  bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3595  unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3596  auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3597  SDValue Ops[] = {
3598  Op.getOperand(0),
3599  DAG.getConstant(Code, DL, MVT::i32),
3600  Op.getOperand(1)
3601  };
3603  Node->getVTList(), Ops,
3604  Node->getMemoryVT(), Node->getMemOperand());
3605 }
3606 
3607 // Return an i32 that contains the value of CC immediately after After,
3608 // whose final operand must be MVT::Glue.
3609 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3610  SDLoc DL(After);
3611  SDValue Glue = SDValue(After, After->getNumValues() - 1);
3612  SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3613  return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3615 }
3616 
3617 SDValue
3618 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3619  SelectionDAG &DAG) const {
3620  unsigned Opcode, CCValid;
3621  if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3622  assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3623  SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3624  SDValue CC = getCCResult(DAG, Glued.getNode());
3625  DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3626  return SDValue();
3627  }
3628 
3629  return SDValue();
3630 }
3631 
3632 SDValue
3633 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3634  SelectionDAG &DAG) const {
3635  unsigned Opcode, CCValid;
3636  if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3637  SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3638  SDValue CC = getCCResult(DAG, Glued.getNode());
3639  if (Op->getNumValues() == 1)
3640  return CC;
3641  assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3642  return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3643  CC);
3644  }
3645 
3646  unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3647  switch (Id) {
3648  case Intrinsic::thread_pointer:
3649  return lowerThreadPointer(SDLoc(Op), DAG);
3650 
3651  case Intrinsic::s390_vpdi:
3652  return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3653  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3654 
3655  case Intrinsic::s390_vperm:
3656  return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3657  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3658 
3659  case Intrinsic::s390_vuphb:
3660  case Intrinsic::s390_vuphh:
3661  case Intrinsic::s390_vuphf:
3662  return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3663  Op.getOperand(1));
3664 
3665  case Intrinsic::s390_vuplhb:
3666  case Intrinsic::s390_vuplhh:
3667  case Intrinsic::s390_vuplhf:
3668  return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3669  Op.getOperand(1));
3670 
3671  case Intrinsic::s390_vuplb:
3672  case Intrinsic::s390_vuplhw:
3673  case Intrinsic::s390_vuplf:
3674  return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3675  Op.getOperand(1));
3676 
3677  case Intrinsic::s390_vupllb:
3678  case Intrinsic::s390_vupllh:
3679  case Intrinsic::s390_vupllf:
3680  return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3681  Op.getOperand(1));
3682 
3683  case Intrinsic::s390_vsumb:
3684  case Intrinsic::s390_vsumh:
3685  case Intrinsic::s390_vsumgh:
3686  case Intrinsic::s390_vsumgf:
3687  case Intrinsic::s390_vsumqf:
3688  case Intrinsic::s390_vsumqg:
3689  return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3690  Op.getOperand(1), Op.getOperand(2));
3691  }
3692 
3693  return SDValue();
3694 }
3695 
3696 namespace {
3697 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3698 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3699 // Operand is the constant third operand, otherwise it is the number of
3700 // bytes in each element of the result.
3701 struct Permute {
3702  unsigned Opcode;
3703  unsigned Operand;
3704  unsigned char Bytes[SystemZ::VectorBytes];
3705 };
3706 }
3707 
3708 static const Permute PermuteForms[] = {
3709  // VMRHG
3711  { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3712  // VMRHF
3714  { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3715  // VMRHH
3717  { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3718  // VMRHB
3720  { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3721  // VMRLG
3722  { SystemZISD::MERGE_LOW, 8,
3723  { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3724  // VMRLF
3725  { SystemZISD::MERGE_LOW, 4,
3726  { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3727  // VMRLH
3728  { SystemZISD::MERGE_LOW, 2,
3729  { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3730  // VMRLB
3731  { SystemZISD::MERGE_LOW, 1,
3732  { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3733  // VPKG
3734  { SystemZISD::PACK, 4,
3735  { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3736  // VPKF
3737  { SystemZISD::PACK, 2,
3738  { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3739  // VPKH
3740  { SystemZISD::PACK, 1,
3741  { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3742  // VPDI V1, V2, 4 (low half of V1, high half of V2)
3744  { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3745  // VPDI V1, V2, 1 (high half of V1, low half of V2)
3747  { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3748 };
3749 
3750 // Called after matching a vector shuffle against a particular pattern.
3751 // Both the original shuffle and the pattern have two vector operands.
3752 // OpNos[0] is the operand of the original shuffle that should be used for
3753 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3754 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3755 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3756 // for operands 0 and 1 of the pattern.
3757 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3758  if (OpNos[0] < 0) {
3759  if (OpNos[1] < 0)
3760  return false;
3761  OpNo0 = OpNo1 = OpNos[1];
3762  } else if (OpNos[1] < 0) {
3763  OpNo0 = OpNo1 = OpNos[0];
3764  } else {
3765  OpNo0 = OpNos[0];
3766  OpNo1 = OpNos[1];
3767  }
3768  return true;
3769 }
3770 
3771 // Bytes is a VPERM-like permute vector, except that -1 is used for
3772 // undefined bytes. Return true if the VPERM can be implemented using P.
3773 // When returning true set OpNo0 to the VPERM operand that should be
3774 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3775 //
3776 // For example, if swapping the VPERM operands allows P to match, OpNo0
3777 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3778 // operand, but rewriting it to use two duplicated operands allows it to
3779 // match P, then OpNo0 and OpNo1 will be the same.
3780 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3781  unsigned &OpNo0, unsigned &OpNo1) {
3782  int OpNos[] = { -1, -1 };
3783  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3784  int Elt = Bytes[I];
3785  if (Elt >= 0) {
3786  // Make sure that the two permute vectors use the same suboperand
3787  // byte number. Only the operand numbers (the high bits) are
3788  // allowed to differ.
3789  if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3790  return false;
3791  int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3792  int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3793  // Make sure that the operand mappings are consistent with previous
3794  // elements.
3795  if (OpNos[ModelOpNo] == 1 - RealOpNo)
3796  return false;
3797  OpNos[ModelOpNo] = RealOpNo;
3798  }
3799  }
3800  return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3801 }
3802 
3803 // As above, but search for a matching permute.
3804 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3805  unsigned &OpNo0, unsigned &OpNo1) {
3806  for (auto &P : PermuteForms)
3807  if (matchPermute(Bytes, P, OpNo0, OpNo1))
3808  return &P;
3809  return nullptr;
3810 }
3811 
3812 // Bytes is a VPERM-like permute vector, except that -1 is used for
3813 // undefined bytes. This permute is an operand of an outer permute.
3814 // See whether redistributing the -1 bytes gives a shuffle that can be
3815 // implemented using P. If so, set Transform to a VPERM-like permute vector
3816 // that, when applied to the result of P, gives the original permute in Bytes.
3817 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3818  const Permute &P,
3819  SmallVectorImpl<int> &Transform) {
3820  unsigned To = 0;
3821  for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3822  int Elt = Bytes[From];
3823  if (Elt < 0)
3824  // Byte number From of the result is undefined.
3825  Transform[From] = -1;
3826  else {
3827  while (P.Bytes[To] != Elt) {
3828  To += 1;
3829  if (To == SystemZ::VectorBytes)
3830  return false;
3831  }
3832  Transform[From] = To;
3833  }
3834  }
3835  return true;
3836 }
3837 
3838 // As above, but search for a matching permute.
3839 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3840  SmallVectorImpl<int> &Transform) {
3841  for (auto &P : PermuteForms)
3842  if (matchDoublePermute(Bytes, P, Transform))
3843  return &P;
3844  return nullptr;
3845 }
3846 
3847 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3848 // as if it had type vNi8.
3850  SmallVectorImpl<int> &Bytes) {
3851  EVT VT = VSN->getValueType(0);
3852  unsigned NumElements = VT.getVectorNumElements();
3853  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3854  Bytes.resize(NumElements * BytesPerElement, -1);
3855  for (unsigned I = 0; I < NumElements; ++I) {
3856  int Index = VSN->getMaskElt(I);
3857  if (Index >= 0)
3858  for (unsigned J = 0; J < BytesPerElement; ++J)
3859  Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3860  }
3861 }
3862 
3863 // Bytes is a VPERM-like permute vector, except that -1 is used for
3864 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3865 // the result come from a contiguous sequence of bytes from one input.
3866 // Set Base to the selector for the first byte if so.
3867 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3868  unsigned BytesPerElement, int &Base) {
3869  Base = -1;
3870  for (unsigned I = 0; I < BytesPerElement; ++I) {
3871  if (Bytes[Start + I] >= 0) {
3872  unsigned Elem = Bytes[Start + I];
3873  if (Base < 0) {
3874  Base = Elem - I;
3875  // Make sure the bytes would come from one input operand.
3876  if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3877  return false;
3878  } else if (unsigned(Base) != Elem - I)
3879  return false;
3880  }
3881  }
3882  return true;
3883 }
3884 
3885 // Bytes is a VPERM-like permute vector, except that -1 is used for
3886 // undefined bytes. Return true if it can be performed using VSLDI.
3887 // When returning true, set StartIndex to the shift amount and OpNo0
3888 // and OpNo1 to the VPERM operands that should be used as the first
3889 // and second shift operand respectively.
3890 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3891  unsigned &StartIndex, unsigned &OpNo0,
3892  unsigned &OpNo1) {
3893  int OpNos[] = { -1, -1 };
3894  int Shift = -1;
3895  for (unsigned I = 0; I < 16; ++I) {
3896  int Index = Bytes[I];
3897  if (Index >= 0) {
3898  int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3899  int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3900  int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3901  if (Shift < 0)
3902  Shift = ExpectedShift;
3903  else if (Shift != ExpectedShift)
3904  return false;
3905  // Make sure that the operand mappings are consistent with previous
3906  // elements.
3907  if (OpNos[ModelOpNo] == 1 - RealOpNo)
3908  return false;
3909  OpNos[ModelOpNo] = RealOpNo;
3910  }
3911  }
3912  StartIndex = Shift;
3913  return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3914 }
3915 
3916 // Create a node that performs P on operands Op0 and Op1, casting the
3917 // operands to the appropriate type. The type of the result is determined by P.
3918 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3919  const Permute &P, SDValue Op0, SDValue Op1) {
3920  // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3921  // elements of a PACK are twice as wide as the outputs.
3922  unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3923  P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3924  P.Operand);
3925  // Cast both operands to the appropriate type.
3926  MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3927  SystemZ::VectorBytes / InBytes);
3928  Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3929  Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3930  SDValue Op;
3931  if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3932  SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3933  Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3934  } else if (P.Opcode == SystemZISD::PACK) {
3935  MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3936  SystemZ::VectorBytes / P.Operand);
3937  Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3938  } else {
3939  Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3940  }
3941  return Op;
3942 }
3943 
3944 // Bytes is a VPERM-like permute vector, except that -1 is used for
3945 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3946 // VSLDI or VPERM.
3948  SDValue *Ops,
3949  const SmallVectorImpl<int> &Bytes) {
3950  for (unsigned I = 0; I < 2; ++I)
3951  Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3952 
3953  // First see whether VSLDI can be used.
3954  unsigned StartIndex, OpNo0, OpNo1;
3955  if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3956  return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3957  Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3958 
3959  // Fall back on VPERM. Construct an SDNode for the permute vector.
3960  SDValue IndexNodes[SystemZ::VectorBytes];
3961  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3962  if (Bytes[I] >= 0)
3963  IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3964  else
3965  IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3966  SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3967  return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3968 }
3969 
3970 namespace {
3971 // Describes a general N-operand vector shuffle.
3972 struct GeneralShuffle {
3973  GeneralShuffle(EVT vt) : VT(vt) {}
3974  void addUndef();
3975  bool add(SDValue, unsigned);
3976  SDValue getNode(SelectionDAG &, const SDLoc &);
3977 
3978  // The operands of the shuffle.
3980 
3981  // Index I is -1 if byte I of the result is undefined. Otherwise the
3982  // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3983  // Bytes[I] / SystemZ::VectorBytes.
3985 
3986  // The type of the shuffle result.
3987  EVT VT;
3988 };
3989 }
3990 
3991 // Add an extra undefined element to the shuffle.
3992 void GeneralShuffle::addUndef() {
3993  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3994  for (unsigned I = 0; I < BytesPerElement; ++I)
3995  Bytes.push_back(-1);
3996 }
3997 
3998 // Add an extra element to the shuffle, taking it from element Elem of Op.
3999 // A null Op indicates a vector input whose value will be calculated later;
4000 // there is at most one such input per shuffle and it always has the same
4001 // type as the result. Aborts and returns false if the source vector elements
4002 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
4003 // LLVM they become implicitly extended, but this is rare and not optimized.
4004 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
4005  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4006 
4007  // The source vector can have wider elements than the result,
4008  // either through an explicit TRUNCATE or because of type legalization.
4009  // We want the least significant part.
4010  EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
4011  unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
4012 
4013  // Return false if the source elements are smaller than their destination
4014  // elements.
4015  if (FromBytesPerElement < BytesPerElement)
4016  return false;
4017 
4018  unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
4019  (FromBytesPerElement - BytesPerElement));
4020 
4021  // Look through things like shuffles and bitcasts.
4022  while (Op.getNode()) {
4023  if (Op.getOpcode() == ISD::BITCAST)
4024  Op = Op.getOperand(0);
4025  else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
4026  // See whether the bytes we need come from a contiguous part of one
4027  // operand.
4029  getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
4030  int NewByte;
4031  if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
4032  break;
4033  if (NewByte < 0) {
4034  addUndef();
4035  return true;
4036  }
4037  Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
4038  Byte = unsigned(NewByte) % SystemZ::VectorBytes;
4039  } else if (Op.isUndef()) {
4040  addUndef();
4041  return true;
4042  } else
4043  break;
4044  }
4045 
4046  // Make sure that the source of the extraction is in Ops.
4047  unsigned OpNo = 0;
4048  for (; OpNo < Ops.size(); ++OpNo)
4049  if (Ops[OpNo] == Op)
4050  break;
4051  if (OpNo == Ops.size())
4052  Ops.push_back(Op);
4053 
4054  // Add the element to Bytes.
4055  unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
4056  for (unsigned I = 0; I < BytesPerElement; ++I)
4057  Bytes.push_back(Base + I);
4058 
4059  return true;
4060 }
4061 
4062 // Return SDNodes for the completed shuffle.
4063 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
4064  assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
4065 
4066  if (Ops.size() == 0)
4067  return DAG.getUNDEF(VT);
4068 
4069  // Make sure that there are at least two shuffle operands.
4070  if (Ops.size() == 1)
4071  Ops.push_back(DAG.getUNDEF(MVT::v16i8));
4072 
4073  // Create a tree of shuffles, deferring root node until after the loop.
4074  // Try to redistribute the undefined elements of non-root nodes so that
4075  // the non-root shuffles match something like a pack or merge, then adjust
4076  // the parent node's permute vector to compensate for the new order.
4077  // Among other things, this copes with vectors like <2 x i16> that were
4078  // padded with undefined elements during type legalization.
4079  //
4080  // In the best case this redistribution will lead to the whole tree
4081  // using packs and merges. It should rarely be a loss in other cases.
4082  unsigned Stride = 1;
4083  for (; Stride * 2 < Ops.size(); Stride *= 2) {
4084  for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
4085  SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
4086 
4087  // Create a mask for just these two operands.
4089  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4090  unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
4091  unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
4092  if (OpNo == I)
4093  NewBytes[J] = Byte;
4094  else if (OpNo == I + Stride)
4095  NewBytes[J] = SystemZ::VectorBytes + Byte;
4096  else
4097  NewBytes[J] = -1;
4098  }
4099  // See if it would be better to reorganize NewMask to avoid using VPERM.
4100  SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
4101  if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
4102  Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
4103  // Applying NewBytesMap to Ops[I] gets back to NewBytes.
4104  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4105  if (NewBytes[J] >= 0) {
4106  assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
4107  "Invalid double permute");
4108  Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
4109  } else
4110  assert(NewBytesMap[J] < 0 && "Invalid double permute");
4111  }
4112  } else {
4113  // Just use NewBytes on the operands.
4114  Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
4115  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
4116  if (NewBytes[J] >= 0)
4117  Bytes[J] = I * SystemZ::VectorBytes + J;
4118  }
4119  }
4120  }
4121 
4122  // Now we just have 2 inputs. Put the second operand in Ops[1].
4123  if (Stride > 1) {
4124  Ops[1] = Ops[Stride];
4125  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4126  if (Bytes[I] >= int(SystemZ::VectorBytes))
4127  Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
4128  }
4129 
4130  // Look for an instruction that can do the permute without resorting
4131  // to VPERM.
4132  unsigned OpNo0, OpNo1;
4133  SDValue Op;
4134  if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
4135  Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
4136  else
4137  Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
4138  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4139 }
4140 
4141 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
4142 static bool isScalarToVector(SDValue Op) {
4143  for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
4144  if (!Op.getOperand(I).isUndef())
4145  return false;
4146  return true;
4147 }
4148 
4149 // Return a vector of type VT that contains Value in the first element.
4150 // The other elements don't matter.
4151 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4152  SDValue Value) {
4153  // If we have a constant, replicate it to all elements and let the
4154  // BUILD_VECTOR lowering take care of it.
4155  if (Value.getOpcode() == ISD::Constant ||
4156  Value.getOpcode() == ISD::ConstantFP) {
4158  return DAG.getBuildVector(VT, DL, Ops);
4159  }
4160  if (Value.isUndef())
4161  return DAG.getUNDEF(VT);
4162  return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4163 }
4164 
4165 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4166 // element 1. Used for cases in which replication is cheap.
4167 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4168  SDValue Op0, SDValue Op1) {
4169  if (Op0.isUndef()) {
4170  if (Op1.isUndef())
4171  return DAG.getUNDEF(VT);
4172  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4173  }
4174  if (Op1.isUndef())
4175  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4176  return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4177  buildScalarToVector(DAG, DL, VT, Op0),
4178  buildScalarToVector(DAG, DL, VT, Op1));
4179 }
4180 
4181 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4182 // vector for them.
4183 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4184  SDValue Op1) {
4185  if (Op0.isUndef() && Op1.isUndef())
4186  return DAG.getUNDEF(MVT::v2i64);
4187  // If one of the two inputs is undefined then replicate the other one,
4188  // in order to avoid using another register unnecessarily.
4189  if (Op0.isUndef())
4190  Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4191  else if (Op1.isUndef())
4192  Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4193  else {
4194  Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4195  Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4196  }
4197  return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4198 }
4199 
4200 // Try to represent constant BUILD_VECTOR node BVN using a
4201 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
4202 // on success.
4203 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
4204  EVT ElemVT = BVN->getValueType(0).getVectorElementType();
4205  unsigned BytesPerElement = ElemVT.getStoreSize();
4206  for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
4207  SDValue Op = BVN->getOperand(I);
4208  if (!Op.isUndef()) {
4209  uint64_t Value;
4210  if (Op.getOpcode() == ISD::Constant)
4211  Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
4212  else if (Op.getOpcode() == ISD::ConstantFP)
4213  Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
4214  .getZExtValue());
4215  else
4216  return false;
4217  for (unsigned J = 0; J < BytesPerElement; ++J) {
4218  uint64_t Byte = (Value >> (J * 8)) & 0xff;
4219  if (Byte == 0xff)
4220  Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
4221  else if (Byte != 0)
4222  return false;
4223  }
4224  }
4225  }
4226  return true;
4227 }
4228 
4229 // Try to load a vector constant in which BitsPerElement-bit value Value
4230 // is replicated to fill the vector. VT is the type of the resulting
4231 // constant, which may have elements of a different size from BitsPerElement.
4232 // Return the SDValue of the constant on success, otherwise return
4233 // an empty value.
4235  const SystemZInstrInfo *TII,
4236  const SDLoc &DL, EVT VT, uint64_t Value,
4237  unsigned BitsPerElement) {
4238  // Signed 16-bit values can be replicated using VREPI.
4239  int64_t SignedValue = SignExtend64(Value, BitsPerElement);
4240  if (isInt<16>(SignedValue)) {
4241  MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4242  SystemZ::VectorBits / BitsPerElement);
4243  SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
4244  DAG.getConstant(SignedValue, DL, MVT::i32));
4245  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4246  }
4247  // See whether rotating the constant left some N places gives a value that
4248  // is one less than a power of 2 (i.e. all zeros followed by all ones).
4249  // If so we can use VGM.
4250  unsigned Start, End;
4251  if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4252  // isRxSBGMask returns the bit numbers for a full 64-bit value,
4253  // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
4254  // bit numbers for an BitsPerElement value, so that 0 denotes
4255  // 1 << (BitsPerElement-1).
4256  Start -= 64 - BitsPerElement;
4257  End -= 64 - BitsPerElement;
4258  MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4259  SystemZ::VectorBits / BitsPerElement);
4260  SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4261  DAG.getConstant(Start, DL, MVT::i32),
4262  DAG.getConstant(End, DL, MVT::i32));
4263  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4264  }
4265  return SDValue();
4266 }
4267 
4268 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4269 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4270 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4271 // would benefit from this representation and return it if so.
4273  BuildVectorSDNode *BVN) {
4274  EVT VT = BVN->getValueType(0);
4275  unsigned NumElements = VT.getVectorNumElements();
4276 
4277  // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4278  // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4279  // need a BUILD_VECTOR, add an additional placeholder operand for that
4280  // BUILD_VECTOR and store its operands in ResidueOps.
4281  GeneralShuffle GS(VT);
4283  bool FoundOne = false;
4284  for (unsigned I = 0; I < NumElements; ++I) {
4285  SDValue Op = BVN->getOperand(I);
4286  if (Op.getOpcode() == ISD::TRUNCATE)
4287  Op = Op.getOperand(0);
4288  if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4289  Op.getOperand(1).getOpcode() == ISD::Constant) {
4290  unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4291  if (!GS.add(Op.getOperand(0), Elem))
4292  return SDValue();
4293  FoundOne = true;
4294  } else if (Op.isUndef()) {
4295  GS.addUndef();
4296  } else {
4297  if (!GS.add(SDValue(), ResidueOps.size()))
4298  return SDValue();
4299  ResidueOps.push_back(BVN->getOperand(I));
4300  }
4301  }
4302 
4303  // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4304  if (!FoundOne)
4305  return SDValue();
4306 
4307  // Create the BUILD_VECTOR for the remaining elements, if any.
4308  if (!ResidueOps.empty()) {
4309  while (ResidueOps.size() < NumElements)
4310  ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4311  for (auto &Op : GS.Ops) {
4312  if (!Op.getNode()) {
4313  Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4314  break;
4315  }
4316  }
4317  }
4318  return GS.getNode(DAG, SDLoc(BVN));
4319 }
4320 
4321 // Combine GPR scalar values Elems into a vector of type VT.
4322 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4323  SmallVectorImpl<SDValue> &Elems) {
4324  // See whether there is a single replicated value.
4325  SDValue Single;
4326  unsigned int NumElements = Elems.size();
4327  unsigned int Count = 0;
4328  for (auto Elem : Elems) {
4329  if (!Elem.isUndef()) {
4330  if (!Single.getNode())
4331  Single = Elem;
4332  else if (Elem != Single) {
4333  Single = SDValue();
4334  break;
4335  }
4336  Count += 1;
4337  }
4338  }
4339  // There are three cases here:
4340  //
4341  // - if the only defined element is a loaded one, the best sequence
4342  // is a replicating load.
4343  //
4344  // - otherwise, if the only defined element is an i64 value, we will
4345  // end up with the same VLVGP sequence regardless of whether we short-cut
4346  // for replication or fall through to the later code.
4347  //
4348  // - otherwise, if the only defined element is an i32 or smaller value,
4349  // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4350  // This is only a win if the single defined element is used more than once.
4351  // In other cases we're better off using a single VLVGx.
4352  if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4353  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4354 
4355  // If all elements are loads, use VLREP/VLEs (below).
4356  bool AllLoads = true;
4357  for (auto Elem : Elems)
4358  if (Elem.getOpcode() != ISD::LOAD || cast<LoadSDNode>(Elem)->isIndexed()) {
4359  AllLoads = false;
4360  break;
4361  }
4362 
4363  // The best way of building a v2i64 from two i64s is to use VLVGP.
4364  if (VT == MVT::v2i64 && !AllLoads)
4365  return joinDwords(DAG, DL, Elems[0], Elems[1]);
4366 
4367  // Use a 64-bit merge high to combine two doubles.
4368  if (VT == MVT::v2f64 && !AllLoads)
4369  return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4370 
4371  // Build v4f32 values directly from the FPRs:
4372  //
4373  // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4374  // V V VMRHF
4375  // <ABxx> <CDxx>
4376  // V VMRHG
4377  // <ABCD>
4378  if (VT == MVT::v4f32 && !AllLoads) {
4379  SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4380  SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4381  // Avoid unnecessary undefs by reusing the other operand.
4382  if (Op01.isUndef())
4383  Op01 = Op23;
4384  else if (Op23.isUndef())
4385  Op23 = Op01;
4386  // Merging identical replications is a no-op.
4387  if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4388  return Op01;
4389  Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4390  Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4392  DL, MVT::v2i64, Op01, Op23);
4393  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4394  }
4395 
4396  // Collect the constant terms.
4398  SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4399 
4400  unsigned NumConstants = 0;
4401  for (unsigned I = 0; I < NumElements; ++I) {
4402  SDValue Elem = Elems[I];
4403  if (Elem.getOpcode() == ISD::Constant ||
4404  Elem.getOpcode() == ISD::ConstantFP) {
4405  NumConstants += 1;
4406  Constants[I] = Elem;
4407  Done[I] = true;
4408  }
4409  }
4410  // If there was at least one constant, fill in the other elements of
4411  // Constants with undefs to get a full vector constant and use that
4412  // as the starting point.
4413  SDValue Result;
4414  if (NumConstants > 0) {
4415  for (unsigned I = 0; I < NumElements; ++I)
4416  if (!Constants[I].getNode())
4417  Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4418  Result = DAG.getBuildVector(VT, DL, Constants);
4419  } else {
4420  // Otherwise try to use VLREP or VLVGP to start the sequence in order to
4421  // avoid a false dependency on any previous contents of the vector
4422  // register.
4423 
4424  // Use a VLREP if at least one element is a load.
4425  unsigned LoadElIdx = UINT_MAX;
4426  for (unsigned I = 0; I < NumElements; ++I)
4427  if (Elems[I].getOpcode() == ISD::LOAD &&
4428  cast<LoadSDNode>(Elems[I])->isUnindexed()) {
4429  LoadElIdx = I;
4430  break;
4431  }
4432  if (LoadElIdx != UINT_MAX) {
4433  Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, Elems[LoadElIdx]);
4434  Done[LoadElIdx] = true;
4435  } else {
4436  // Try to use VLVGP.
4437  unsigned I1 = NumElements / 2 - 1;
4438  unsigned I2 = NumElements - 1;
4439  bool Def1 = !Elems[I1].isUndef();
4440  bool Def2 = !Elems[I2].isUndef();
4441  if (Def1 || Def2) {
4442  SDValue Elem1 = Elems[Def1 ? I1 : I2];
4443  SDValue Elem2 = Elems[Def2 ? I2 : I1];
4444  Result = DAG.getNode(ISD::BITCAST, DL, VT,
4445  joinDwords(DAG, DL, Elem1, Elem2));
4446  Done[I1] = true;
4447  Done[I2] = true;
4448  } else
4449  Result = DAG.getUNDEF(VT);
4450  }
4451  }
4452 
4453  // Use VLVGx to insert the other elements.
4454  for (unsigned I = 0; I < NumElements; ++I)
4455  if (!Done[I] && !Elems[I].isUndef())
4456  Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4457  DAG.getConstant(I, DL, MVT::i32));
4458  return Result;
4459 }
4460 
4461 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4462  SelectionDAG &DAG) const {
4463  const SystemZInstrInfo *TII =
4464  static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4465  auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4466  SDLoc DL(Op);
4467  EVT VT = Op.getValueType();
4468 
4469  if (BVN->isConstant()) {
4470  // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
4471  // preferred way of creating all-zero and all-one vectors so give it
4472  // priority over other methods below.
4473  uint64_t Mask = 0;
4474  if (tryBuildVectorByteMask(BVN, Mask)) {
4476  DAG.getConstant(Mask, DL, MVT::i32));
4477  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4478  }
4479 
4480  // Try using some form of replication.
4481  APInt SplatBits, SplatUndef;
4482  unsigned SplatBitSize;
4483  bool HasAnyUndefs;
4484  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4485  8, true) &&
4486  SplatBitSize <= 64) {
4487  // First try assuming that any undefined bits above the highest set bit
4488  // and below the lowest set bit are 1s. This increases the likelihood of
4489  // being able to use a sign-extended element value in VECTOR REPLICATE
4490  // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4491  uint64_t SplatBitsZ = SplatBits.getZExtValue();
4492  uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4493  uint64_t Lower = (SplatUndefZ
4494  & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4495  uint64_t Upper = (SplatUndefZ
4496  & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4497  uint64_t Value = SplatBitsZ | Upper | Lower;
4498  SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4499  SplatBitSize);
4500  if (Op.getNode())
4501  return Op;
4502 
4503  // Now try assuming that any undefined bits between the first and
4504  // last defined set bits are set. This increases the chances of
4505  // using a non-wraparound mask.
4506  uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4507  Value = SplatBitsZ | Middle;
4508  Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4509  if (Op.getNode())
4510  return Op;
4511  }
4512 
4513  // Fall back to loading it from memory.
4514  return SDValue();
4515  }
4516 
4517  // See if we should use shuffles to construct the vector from other vectors.
4518  if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4519  return Res;
4520 
4521  // Detect SCALAR_TO_VECTOR conversions.
4523  return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4524 
4525  // Otherwise use buildVector to build the vector up from GPRs.
4526  unsigned NumElements = Op.getNumOperands();
4528  for (unsigned I = 0; I < NumElements; ++I)
4529  Ops[I] = Op.getOperand(I);
4530  return buildVector(DAG, DL, VT, Ops);
4531 }
4532 
4533 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4534  SelectionDAG &DAG) const {
4535  auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4536  SDLoc DL(Op);
4537  EVT VT = Op.getValueType();
4538  unsigned NumElements = VT.getVectorNumElements();
4539 
4540  if (VSN->isSplat()) {
4541  SDValue Op0 = Op.getOperand(0);
4542  unsigned Index = VSN->getSplatIndex();
4543  assert(Index < VT.getVectorNumElements() &&
4544  "Splat index should be defined and in first operand");
4545  // See whether the value we're splatting is directly available as a scalar.
4546  if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4547  Op0.getOpcode() == ISD::BUILD_VECTOR)
4548  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4549  // Otherwise keep it as a vector-to-vector operation.
4550  return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4551  DAG.getConstant(Index, DL, MVT::i32));
4552  }
4553 
4554  GeneralShuffle GS(VT);
4555  for (unsigned I = 0; I < NumElements; ++I) {
4556  int Elt = VSN->getMaskElt(I);
4557  if (Elt < 0)
4558  GS.addUndef();
4559  else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4560  unsigned(Elt) % NumElements))
4561  return SDValue();
4562  }
4563  return GS.getNode(DAG, SDLoc(VSN));
4564 }
4565 
4566 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4567  SelectionDAG &DAG) const {
4568  SDLoc DL(Op);
4569  // Just insert the scalar into element 0 of an undefined vector.
4570  return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4571  Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4572  Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4573 }
4574 
4575 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4576  SelectionDAG &DAG) const {
4577  // Handle insertions of floating-point values.
4578  SDLoc DL(Op);
4579  SDValue Op0 = Op.getOperand(0);
4580  SDValue Op1 = Op.getOperand(1);
4581  SDValue Op2 = Op.getOperand(2);
4582  EVT VT = Op.getValueType();
4583 
4584  // Insertions into constant indices of a v2f64 can be done using VPDI.
4585  // However, if the inserted value is a bitcast or a constant then it's
4586  // better to use GPRs, as below.
4587  if (VT == MVT::v2f64 &&
4588  Op1.getOpcode() != ISD::BITCAST &&
4589  Op1.getOpcode() != ISD::ConstantFP &&
4590  Op2.getOpcode() == ISD::Constant) {
4591  uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4592  unsigned Mask = VT.getVectorNumElements() - 1;
4593  if (Index <= Mask)
4594  return Op;
4595  }
4596 
4597  // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4599  MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4600  SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4601  DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4602  DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4603  return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4604 }
4605 
4606 SDValue
4607 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4608  SelectionDAG &DAG) const {
4609  // Handle extractions of floating-point values.
4610  SDLoc DL(Op);
4611  SDValue Op0 = Op.getOperand(0);
4612  SDValue Op1 = Op.getOperand(1);
4613  EVT VT = Op.getValueType();
4614  EVT VecVT = Op0.getValueType();
4615 
4616  // Extractions of constant indices can be done directly.
4617  if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4618  uint64_t Index = CIndexN->getZExtValue();
4619