[SystemZ] Provide basic TargetTransformInfo implementation
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelLowering.cpp
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"
16 #include "SystemZConstantPoolValue.h"
17 #include "SystemZMachineFunctionInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23 #include <cctype>
24
25 using namespace llvm;
26
27 #define DEBUG_TYPE "systemz-lower"
28
29 namespace {
30 // Represents a sequence for extracting a 0/1 value from an IPM result:
31 // (((X ^ XORValue) + AddValue) >> Bit)
32 struct IPMConversion {
33   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
34     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
35
36   int64_t XORValue;
37   int64_t AddValue;
38   unsigned Bit;
39 };
40
41 // Represents information about a comparison.
42 struct Comparison {
43   Comparison(SDValue Op0In, SDValue Op1In)
44     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
45
46   // The operands to the comparison.
47   SDValue Op0, Op1;
48
49   // The opcode that should be used to compare Op0 and Op1.
50   unsigned Opcode;
51
52   // A SystemZICMP value.  Only used for integer comparisons.
53   unsigned ICmpType;
54
55   // The mask of CC values that Opcode can produce.
56   unsigned CCValid;
57
58   // The mask of CC values for which the original condition is true.
59   unsigned CCMask;
60 };
61 } // end anonymous namespace
62
63 // Classify VT as either 32 or 64 bit.
64 static bool is32Bit(EVT VT) {
65   switch (VT.getSimpleVT().SimpleTy) {
66   case MVT::i32:
67     return true;
68   case MVT::i64:
69     return false;
70   default:
71     llvm_unreachable("Unsupported type");
72   }
73 }
74
75 // Return a version of MachineOperand that can be safely used before the
76 // final use.
77 static MachineOperand earlyUseOperand(MachineOperand Op) {
78   if (Op.isReg())
79     Op.setIsKill(false);
80   return Op;
81 }
82
83 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &tm,
84                                              const SystemZSubtarget &STI)
85     : TargetLowering(tm), Subtarget(STI) {
86   MVT PtrVT = getPointerTy();
87
88   // Set up the register classes.
89   if (Subtarget.hasHighWord())
90     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
91   else
92     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
93   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
94   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
95   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
96   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
97
98   // Compute derived properties from the register classes
99   computeRegisterProperties(Subtarget.getRegisterInfo());
100
101   // Set up special registers.
102   setExceptionPointerRegister(SystemZ::R6D);
103   setExceptionSelectorRegister(SystemZ::R7D);
104   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
105
106   // TODO: It may be better to default to latency-oriented scheduling, however
107   // LLVM's current latency-oriented scheduler can't handle physreg definitions
108   // such as SystemZ has with CC, so set this to the register-pressure
109   // scheduler, because it can.
110   setSchedulingPreference(Sched::RegPressure);
111
112   setBooleanContents(ZeroOrOneBooleanContent);
113   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
114
115   // Instructions are strings of 2-byte aligned 2-byte values.
116   setMinFunctionAlignment(2);
117
118   // Handle operations that are handled in a similar way for all types.
119   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
120        I <= MVT::LAST_FP_VALUETYPE;
121        ++I) {
122     MVT VT = MVT::SimpleValueType(I);
123     if (isTypeLegal(VT)) {
124       // Lower SET_CC into an IPM-based sequence.
125       setOperationAction(ISD::SETCC, VT, Custom);
126
127       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
128       setOperationAction(ISD::SELECT, VT, Expand);
129
130       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
131       setOperationAction(ISD::SELECT_CC, VT, Custom);
132       setOperationAction(ISD::BR_CC,     VT, Custom);
133     }
134   }
135
136   // Expand jump table branches as address arithmetic followed by an
137   // indirect jump.
138   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
139
140   // Expand BRCOND into a BR_CC (see above).
141   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
142
143   // Handle integer types.
144   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
145        I <= MVT::LAST_INTEGER_VALUETYPE;
146        ++I) {
147     MVT VT = MVT::SimpleValueType(I);
148     if (isTypeLegal(VT)) {
149       // Expand individual DIV and REMs into DIVREMs.
150       setOperationAction(ISD::SDIV, VT, Expand);
151       setOperationAction(ISD::UDIV, VT, Expand);
152       setOperationAction(ISD::SREM, VT, Expand);
153       setOperationAction(ISD::UREM, VT, Expand);
154       setOperationAction(ISD::SDIVREM, VT, Custom);
155       setOperationAction(ISD::UDIVREM, VT, Custom);
156
157       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
158       // stores, putting a serialization instruction after the stores.
159       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
160       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
161
162       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
163       // available, or if the operand is constant.
164       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
165
166       // No special instructions for these.
167       setOperationAction(ISD::CTPOP,           VT, Expand);
168       setOperationAction(ISD::CTTZ,            VT, Expand);
169       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
170       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
171       setOperationAction(ISD::ROTR,            VT, Expand);
172
173       // Use *MUL_LOHI where possible instead of MULH*.
174       setOperationAction(ISD::MULHS, VT, Expand);
175       setOperationAction(ISD::MULHU, VT, Expand);
176       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
177       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
178
179       // Only z196 and above have native support for conversions to unsigned.
180       if (!Subtarget.hasFPExtension())
181         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
182     }
183   }
184
185   // Type legalization will convert 8- and 16-bit atomic operations into
186   // forms that operate on i32s (but still keeping the original memory VT).
187   // Lower them into full i32 operations.
188   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
189   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
190   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
191   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
192   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
193   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
194   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
195   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
196   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
197   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
198   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
199   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
200
201   // z10 has instructions for signed but not unsigned FP conversion.
202   // Handle unsigned 32-bit types as signed 64-bit types.
203   if (!Subtarget.hasFPExtension()) {
204     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
205     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
206   }
207
208   // We have native support for a 64-bit CTLZ, via FLOGR.
209   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
210   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
211
212   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
213   setOperationAction(ISD::OR, MVT::i64, Custom);
214
215   // FIXME: Can we support these natively?
216   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
217   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
218   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
219
220   // We have native instructions for i8, i16 and i32 extensions, but not i1.
221   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222   for (MVT VT : MVT::integer_valuetypes()) {
223     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
225     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1, Promote);
226   }
227
228   // Handle the various types of symbolic address.
229   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
230   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
231   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
232   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
233   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
234
235   // We need to handle dynamic allocations specially because of the
236   // 160-byte area at the bottom of the stack.
237   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
238
239   // Use custom expanders so that we can force the function to use
240   // a frame pointer.
241   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
242   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
243
244   // Handle prefetches with PFD or PFDRL.
245   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
246
247   // Handle floating-point types.
248   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
249        I <= MVT::LAST_FP_VALUETYPE;
250        ++I) {
251     MVT VT = MVT::SimpleValueType(I);
252     if (isTypeLegal(VT)) {
253       // We can use FI for FRINT.
254       setOperationAction(ISD::FRINT, VT, Legal);
255
256       // We can use the extended form of FI for other rounding operations.
257       if (Subtarget.hasFPExtension()) {
258         setOperationAction(ISD::FNEARBYINT, VT, Legal);
259         setOperationAction(ISD::FFLOOR, VT, Legal);
260         setOperationAction(ISD::FCEIL, VT, Legal);
261         setOperationAction(ISD::FTRUNC, VT, Legal);
262         setOperationAction(ISD::FROUND, VT, Legal);
263       }
264
265       // No special instructions for these.
266       setOperationAction(ISD::FSIN, VT, Expand);
267       setOperationAction(ISD::FCOS, VT, Expand);
268       setOperationAction(ISD::FREM, VT, Expand);
269     }
270   }
271
272   // We have fused multiply-addition for f32 and f64 but not f128.
273   setOperationAction(ISD::FMA, MVT::f32,  Legal);
274   setOperationAction(ISD::FMA, MVT::f64,  Legal);
275   setOperationAction(ISD::FMA, MVT::f128, Expand);
276
277   // Needed so that we don't try to implement f128 constant loads using
278   // a load-and-extend of a f80 constant (in cases where the constant
279   // would fit in an f80).
280   for (MVT VT : MVT::fp_valuetypes())
281     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
282
283   // Floating-point truncation and stores need to be done separately.
284   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
285   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
286   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
287
288   // We have 64-bit FPR<->GPR moves, but need special handling for
289   // 32-bit forms.
290   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
291   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
292
293   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
294   // structure, but VAEND is a no-op.
295   setOperationAction(ISD::VASTART, MVT::Other, Custom);
296   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
297   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
298
299   // Codes for which we want to perform some z-specific combinations.
300   setTargetDAGCombine(ISD::SIGN_EXTEND);
301
302   // We want to use MVC in preference to even a single load/store pair.
303   MaxStoresPerMemcpy = 0;
304   MaxStoresPerMemcpyOptSize = 0;
305
306   // The main memset sequence is a byte store followed by an MVC.
307   // Two STC or MV..I stores win over that, but the kind of fused stores
308   // generated by target-independent code don't when the byte value is
309   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
310   // than "STC;MVC".  Handle the choice in target-specific code instead.
311   MaxStoresPerMemset = 0;
312   MaxStoresPerMemsetOptSize = 0;
313 }
314
315 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
316   if (!VT.isVector())
317     return MVT::i32;
318   return VT.changeVectorElementTypeToInteger();
319 }
320
321 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
322   VT = VT.getScalarType();
323
324   if (!VT.isSimple())
325     return false;
326
327   switch (VT.getSimpleVT().SimpleTy) {
328   case MVT::f32:
329   case MVT::f64:
330     return true;
331   case MVT::f128:
332     return false;
333   default:
334     break;
335   }
336
337   return false;
338 }
339
340 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
341   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
342   return Imm.isZero() || Imm.isNegZero();
343 }
344
345 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
346   // We can use CGFI or CLGFI.
347   return isInt<32>(Imm) || isUInt<32>(Imm);
348 }
349
350 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
351   // We can use ALGFI or SLGFI.
352   return isUInt<32>(Imm) || isUInt<32>(-Imm);
353 }
354
355 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
356                                                            unsigned,
357                                                            unsigned,
358                                                            bool *Fast) const {
359   // Unaligned accesses should never be slower than the expanded version.
360   // We check specifically for aligned accesses in the few cases where
361   // they are required.
362   if (Fast)
363     *Fast = true;
364   return true;
365 }
366   
367 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
368                                                   Type *Ty) const {
369   // Punt on globals for now, although they can be used in limited
370   // RELATIVE LONG cases.
371   if (AM.BaseGV)
372     return false;
373
374   // Require a 20-bit signed offset.
375   if (!isInt<20>(AM.BaseOffs))
376     return false;
377
378   // Indexing is OK but no scale factor can be applied.
379   return AM.Scale == 0 || AM.Scale == 1;
380 }
381
382 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
383   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
384     return false;
385   unsigned FromBits = FromType->getPrimitiveSizeInBits();
386   unsigned ToBits = ToType->getPrimitiveSizeInBits();
387   return FromBits > ToBits;
388 }
389
390 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
391   if (!FromVT.isInteger() || !ToVT.isInteger())
392     return false;
393   unsigned FromBits = FromVT.getSizeInBits();
394   unsigned ToBits = ToVT.getSizeInBits();
395   return FromBits > ToBits;
396 }
397
398 //===----------------------------------------------------------------------===//
399 // Inline asm support
400 //===----------------------------------------------------------------------===//
401
402 TargetLowering::ConstraintType
403 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
404   if (Constraint.size() == 1) {
405     switch (Constraint[0]) {
406     case 'a': // Address register
407     case 'd': // Data register (equivalent to 'r')
408     case 'f': // Floating-point register
409     case 'h': // High-part register
410     case 'r': // General-purpose register
411       return C_RegisterClass;
412
413     case 'Q': // Memory with base and unsigned 12-bit displacement
414     case 'R': // Likewise, plus an index
415     case 'S': // Memory with base and signed 20-bit displacement
416     case 'T': // Likewise, plus an index
417     case 'm': // Equivalent to 'T'.
418       return C_Memory;
419
420     case 'I': // Unsigned 8-bit constant
421     case 'J': // Unsigned 12-bit constant
422     case 'K': // Signed 16-bit constant
423     case 'L': // Signed 20-bit displacement (on all targets we support)
424     case 'M': // 0x7fffffff
425       return C_Other;
426
427     default:
428       break;
429     }
430   }
431   return TargetLowering::getConstraintType(Constraint);
432 }
433
434 TargetLowering::ConstraintWeight SystemZTargetLowering::
435 getSingleConstraintMatchWeight(AsmOperandInfo &info,
436                                const char *constraint) const {
437   ConstraintWeight weight = CW_Invalid;
438   Value *CallOperandVal = info.CallOperandVal;
439   // If we don't have a value, we can't do a match,
440   // but allow it at the lowest weight.
441   if (!CallOperandVal)
442     return CW_Default;
443   Type *type = CallOperandVal->getType();
444   // Look at the constraint type.
445   switch (*constraint) {
446   default:
447     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
448     break;
449
450   case 'a': // Address register
451   case 'd': // Data register (equivalent to 'r')
452   case 'h': // High-part register
453   case 'r': // General-purpose register
454     if (CallOperandVal->getType()->isIntegerTy())
455       weight = CW_Register;
456     break;
457
458   case 'f': // Floating-point register
459     if (type->isFloatingPointTy())
460       weight = CW_Register;
461     break;
462
463   case 'I': // Unsigned 8-bit constant
464     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
465       if (isUInt<8>(C->getZExtValue()))
466         weight = CW_Constant;
467     break;
468
469   case 'J': // Unsigned 12-bit constant
470     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
471       if (isUInt<12>(C->getZExtValue()))
472         weight = CW_Constant;
473     break;
474
475   case 'K': // Signed 16-bit constant
476     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
477       if (isInt<16>(C->getSExtValue()))
478         weight = CW_Constant;
479     break;
480
481   case 'L': // Signed 20-bit displacement (on all targets we support)
482     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
483       if (isInt<20>(C->getSExtValue()))
484         weight = CW_Constant;
485     break;
486
487   case 'M': // 0x7fffffff
488     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
489       if (C->getZExtValue() == 0x7fffffff)
490         weight = CW_Constant;
491     break;
492   }
493   return weight;
494 }
495
496 // Parse a "{tNNN}" register constraint for which the register type "t"
497 // has already been verified.  MC is the class associated with "t" and
498 // Map maps 0-based register numbers to LLVM register numbers.
499 static std::pair<unsigned, const TargetRegisterClass *>
500 parseRegisterNumber(const std::string &Constraint,
501                     const TargetRegisterClass *RC, const unsigned *Map) {
502   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
503   if (isdigit(Constraint[2])) {
504     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
505     unsigned Index = atoi(Suffix.c_str());
506     if (Index < 16 && Map[Index])
507       return std::make_pair(Map[Index], RC);
508   }
509   return std::make_pair(0U, nullptr);
510 }
511
512 std::pair<unsigned, const TargetRegisterClass *>
513 SystemZTargetLowering::getRegForInlineAsmConstraint(
514     const TargetRegisterInfo *TRI, const std::string &Constraint,
515     MVT VT) const {
516   if (Constraint.size() == 1) {
517     // GCC Constraint Letters
518     switch (Constraint[0]) {
519     default: break;
520     case 'd': // Data register (equivalent to 'r')
521     case 'r': // General-purpose register
522       if (VT == MVT::i64)
523         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
524       else if (VT == MVT::i128)
525         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
526       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
527
528     case 'a': // Address register
529       if (VT == MVT::i64)
530         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
531       else if (VT == MVT::i128)
532         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
533       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
534
535     case 'h': // High-part register (an LLVM extension)
536       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
537
538     case 'f': // Floating-point register
539       if (VT == MVT::f64)
540         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
541       else if (VT == MVT::f128)
542         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
543       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
544     }
545   }
546   if (Constraint[0] == '{') {
547     // We need to override the default register parsing for GPRs and FPRs
548     // because the interpretation depends on VT.  The internal names of
549     // the registers are also different from the external names
550     // (F0D and F0S instead of F0, etc.).
551     if (Constraint[1] == 'r') {
552       if (VT == MVT::i32)
553         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
554                                    SystemZMC::GR32Regs);
555       if (VT == MVT::i128)
556         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
557                                    SystemZMC::GR128Regs);
558       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
559                                  SystemZMC::GR64Regs);
560     }
561     if (Constraint[1] == 'f') {
562       if (VT == MVT::f32)
563         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
564                                    SystemZMC::FP32Regs);
565       if (VT == MVT::f128)
566         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
567                                    SystemZMC::FP128Regs);
568       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
569                                  SystemZMC::FP64Regs);
570     }
571   }
572   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
573 }
574
575 void SystemZTargetLowering::
576 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
577                              std::vector<SDValue> &Ops,
578                              SelectionDAG &DAG) const {
579   // Only support length 1 constraints for now.
580   if (Constraint.length() == 1) {
581     switch (Constraint[0]) {
582     case 'I': // Unsigned 8-bit constant
583       if (auto *C = dyn_cast<ConstantSDNode>(Op))
584         if (isUInt<8>(C->getZExtValue()))
585           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
586                                               Op.getValueType()));
587       return;
588
589     case 'J': // Unsigned 12-bit constant
590       if (auto *C = dyn_cast<ConstantSDNode>(Op))
591         if (isUInt<12>(C->getZExtValue()))
592           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
593                                               Op.getValueType()));
594       return;
595
596     case 'K': // Signed 16-bit constant
597       if (auto *C = dyn_cast<ConstantSDNode>(Op))
598         if (isInt<16>(C->getSExtValue()))
599           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
600                                               Op.getValueType()));
601       return;
602
603     case 'L': // Signed 20-bit displacement (on all targets we support)
604       if (auto *C = dyn_cast<ConstantSDNode>(Op))
605         if (isInt<20>(C->getSExtValue()))
606           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
607                                               Op.getValueType()));
608       return;
609
610     case 'M': // 0x7fffffff
611       if (auto *C = dyn_cast<ConstantSDNode>(Op))
612         if (C->getZExtValue() == 0x7fffffff)
613           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
614                                               Op.getValueType()));
615       return;
616     }
617   }
618   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
619 }
620
621 //===----------------------------------------------------------------------===//
622 // Calling conventions
623 //===----------------------------------------------------------------------===//
624
625 #include "SystemZGenCallingConv.inc"
626
627 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
628                                                      Type *ToType) const {
629   return isTruncateFree(FromType, ToType);
630 }
631
632 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
633   if (!CI->isTailCall())
634     return false;
635   return true;
636 }
637
638 // Value is a value that has been passed to us in the location described by VA
639 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
640 // any loads onto Chain.
641 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
642                                    CCValAssign &VA, SDValue Chain,
643                                    SDValue Value) {
644   // If the argument has been promoted from a smaller type, insert an
645   // assertion to capture this.
646   if (VA.getLocInfo() == CCValAssign::SExt)
647     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
648                         DAG.getValueType(VA.getValVT()));
649   else if (VA.getLocInfo() == CCValAssign::ZExt)
650     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
651                         DAG.getValueType(VA.getValVT()));
652
653   if (VA.isExtInLoc())
654     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
655   else if (VA.getLocInfo() == CCValAssign::Indirect)
656     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
657                         MachinePointerInfo(), false, false, false, 0);
658   else
659     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
660   return Value;
661 }
662
663 // Value is a value of type VA.getValVT() that we need to copy into
664 // the location described by VA.  Return a copy of Value converted to
665 // VA.getValVT().  The caller is responsible for handling indirect values.
666 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
667                                    CCValAssign &VA, SDValue Value) {
668   switch (VA.getLocInfo()) {
669   case CCValAssign::SExt:
670     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
671   case CCValAssign::ZExt:
672     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
673   case CCValAssign::AExt:
674     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
675   case CCValAssign::Full:
676     return Value;
677   default:
678     llvm_unreachable("Unhandled getLocInfo()");
679   }
680 }
681
682 SDValue SystemZTargetLowering::
683 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
684                      const SmallVectorImpl<ISD::InputArg> &Ins,
685                      SDLoc DL, SelectionDAG &DAG,
686                      SmallVectorImpl<SDValue> &InVals) const {
687   MachineFunction &MF = DAG.getMachineFunction();
688   MachineFrameInfo *MFI = MF.getFrameInfo();
689   MachineRegisterInfo &MRI = MF.getRegInfo();
690   SystemZMachineFunctionInfo *FuncInfo =
691       MF.getInfo<SystemZMachineFunctionInfo>();
692   auto *TFL =
693       static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
694
695   // Assign locations to all of the incoming arguments.
696   SmallVector<CCValAssign, 16> ArgLocs;
697   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
698   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
699
700   unsigned NumFixedGPRs = 0;
701   unsigned NumFixedFPRs = 0;
702   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
703     SDValue ArgValue;
704     CCValAssign &VA = ArgLocs[I];
705     EVT LocVT = VA.getLocVT();
706     if (VA.isRegLoc()) {
707       // Arguments passed in registers
708       const TargetRegisterClass *RC;
709       switch (LocVT.getSimpleVT().SimpleTy) {
710       default:
711         // Integers smaller than i64 should be promoted to i64.
712         llvm_unreachable("Unexpected argument type");
713       case MVT::i32:
714         NumFixedGPRs += 1;
715         RC = &SystemZ::GR32BitRegClass;
716         break;
717       case MVT::i64:
718         NumFixedGPRs += 1;
719         RC = &SystemZ::GR64BitRegClass;
720         break;
721       case MVT::f32:
722         NumFixedFPRs += 1;
723         RC = &SystemZ::FP32BitRegClass;
724         break;
725       case MVT::f64:
726         NumFixedFPRs += 1;
727         RC = &SystemZ::FP64BitRegClass;
728         break;
729       }
730
731       unsigned VReg = MRI.createVirtualRegister(RC);
732       MRI.addLiveIn(VA.getLocReg(), VReg);
733       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
734     } else {
735       assert(VA.isMemLoc() && "Argument not register or memory");
736
737       // Create the frame index object for this incoming parameter.
738       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
739                                       VA.getLocMemOffset(), true);
740
741       // Create the SelectionDAG nodes corresponding to a load
742       // from this parameter.  Unpromoted ints and floats are
743       // passed as right-justified 8-byte values.
744       EVT PtrVT = getPointerTy();
745       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
746       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
747         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
748       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
749                              MachinePointerInfo::getFixedStack(FI),
750                              false, false, false, 0);
751     }
752
753     // Convert the value of the argument register into the value that's
754     // being passed.
755     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
756   }
757
758   if (IsVarArg) {
759     // Save the number of non-varargs registers for later use by va_start, etc.
760     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
761     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
762
763     // Likewise the address (in the form of a frame index) of where the
764     // first stack vararg would be.  The 1-byte size here is arbitrary.
765     int64_t StackSize = CCInfo.getNextStackOffset();
766     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
767
768     // ...and a similar frame index for the caller-allocated save area
769     // that will be used to store the incoming registers.
770     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
771     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
772     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
773
774     // Store the FPR varargs in the reserved frame slots.  (We store the
775     // GPRs as part of the prologue.)
776     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
777       SDValue MemOps[SystemZ::NumArgFPRs];
778       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
779         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
780         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
781         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
782         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
783                                      &SystemZ::FP64BitRegClass);
784         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
785         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
786                                  MachinePointerInfo::getFixedStack(FI),
787                                  false, false, 0);
788
789       }
790       // Join the stores, which are independent of one another.
791       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
792                           makeArrayRef(&MemOps[NumFixedFPRs],
793                                        SystemZ::NumArgFPRs-NumFixedFPRs));
794     }
795   }
796
797   return Chain;
798 }
799
800 static bool canUseSiblingCall(const CCState &ArgCCInfo,
801                               SmallVectorImpl<CCValAssign> &ArgLocs) {
802   // Punt if there are any indirect or stack arguments, or if the call
803   // needs the call-saved argument register R6.
804   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
805     CCValAssign &VA = ArgLocs[I];
806     if (VA.getLocInfo() == CCValAssign::Indirect)
807       return false;
808     if (!VA.isRegLoc())
809       return false;
810     unsigned Reg = VA.getLocReg();
811     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
812       return false;
813   }
814   return true;
815 }
816
817 SDValue
818 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
819                                  SmallVectorImpl<SDValue> &InVals) const {
820   SelectionDAG &DAG = CLI.DAG;
821   SDLoc &DL = CLI.DL;
822   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
823   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
824   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
825   SDValue Chain = CLI.Chain;
826   SDValue Callee = CLI.Callee;
827   bool &IsTailCall = CLI.IsTailCall;
828   CallingConv::ID CallConv = CLI.CallConv;
829   bool IsVarArg = CLI.IsVarArg;
830   MachineFunction &MF = DAG.getMachineFunction();
831   EVT PtrVT = getPointerTy();
832
833   // Analyze the operands of the call, assigning locations to each operand.
834   SmallVector<CCValAssign, 16> ArgLocs;
835   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
836   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
837
838   // We don't support GuaranteedTailCallOpt, only automatically-detected
839   // sibling calls.
840   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
841     IsTailCall = false;
842
843   // Get a count of how many bytes are to be pushed on the stack.
844   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
845
846   // Mark the start of the call.
847   if (!IsTailCall)
848     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
849                                  DL);
850
851   // Copy argument values to their designated locations.
852   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
853   SmallVector<SDValue, 8> MemOpChains;
854   SDValue StackPtr;
855   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
856     CCValAssign &VA = ArgLocs[I];
857     SDValue ArgValue = OutVals[I];
858
859     if (VA.getLocInfo() == CCValAssign::Indirect) {
860       // Store the argument in a stack slot and pass its address.
861       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
862       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
863       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
864                                          MachinePointerInfo::getFixedStack(FI),
865                                          false, false, 0));
866       ArgValue = SpillSlot;
867     } else
868       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
869
870     if (VA.isRegLoc())
871       // Queue up the argument copies and emit them at the end.
872       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
873     else {
874       assert(VA.isMemLoc() && "Argument not register or memory");
875
876       // Work out the address of the stack slot.  Unpromoted ints and
877       // floats are passed as right-justified 8-byte values.
878       if (!StackPtr.getNode())
879         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
880       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
881       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
882         Offset += 4;
883       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
884                                     DAG.getIntPtrConstant(Offset));
885
886       // Emit the store.
887       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
888                                          MachinePointerInfo(),
889                                          false, false, 0));
890     }
891   }
892
893   // Join the stores, which are independent of one another.
894   if (!MemOpChains.empty())
895     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
896
897   // Accept direct calls by converting symbolic call addresses to the
898   // associated Target* opcodes.  Force %r1 to be used for indirect
899   // tail calls.
900   SDValue Glue;
901   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
902     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
903     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
904   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
905     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
906     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
907   } else if (IsTailCall) {
908     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
909     Glue = Chain.getValue(1);
910     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
911   }
912
913   // Build a sequence of copy-to-reg nodes, chained and glued together.
914   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
915     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
916                              RegsToPass[I].second, Glue);
917     Glue = Chain.getValue(1);
918   }
919
920   // The first call operand is the chain and the second is the target address.
921   SmallVector<SDValue, 8> Ops;
922   Ops.push_back(Chain);
923   Ops.push_back(Callee);
924
925   // Add argument registers to the end of the list so that they are
926   // known live into the call.
927   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
928     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
929                                   RegsToPass[I].second.getValueType()));
930
931   // Add a register mask operand representing the call-preserved registers.
932   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
933   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
934   assert(Mask && "Missing call preserved mask for calling convention");
935   Ops.push_back(DAG.getRegisterMask(Mask));
936
937   // Glue the call to the argument copies, if any.
938   if (Glue.getNode())
939     Ops.push_back(Glue);
940
941   // Emit the call.
942   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
943   if (IsTailCall)
944     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
945   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
946   Glue = Chain.getValue(1);
947
948   // Mark the end of the call, which is glued to the call itself.
949   Chain = DAG.getCALLSEQ_END(Chain,
950                              DAG.getConstant(NumBytes, PtrVT, true),
951                              DAG.getConstant(0, PtrVT, true),
952                              Glue, DL);
953   Glue = Chain.getValue(1);
954
955   // Assign locations to each value returned by this call.
956   SmallVector<CCValAssign, 16> RetLocs;
957   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
958   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
959
960   // Copy all of the result registers out of their specified physreg.
961   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
962     CCValAssign &VA = RetLocs[I];
963
964     // Copy the value out, gluing the copy to the end of the call sequence.
965     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
966                                           VA.getLocVT(), Glue);
967     Chain = RetValue.getValue(1);
968     Glue = RetValue.getValue(2);
969
970     // Convert the value of the return register into the value that's
971     // being returned.
972     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
973   }
974
975   return Chain;
976 }
977
978 SDValue
979 SystemZTargetLowering::LowerReturn(SDValue Chain,
980                                    CallingConv::ID CallConv, bool IsVarArg,
981                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
982                                    const SmallVectorImpl<SDValue> &OutVals,
983                                    SDLoc DL, SelectionDAG &DAG) const {
984   MachineFunction &MF = DAG.getMachineFunction();
985
986   // Assign locations to each returned value.
987   SmallVector<CCValAssign, 16> RetLocs;
988   CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
989   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
990
991   // Quick exit for void returns
992   if (RetLocs.empty())
993     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
994
995   // Copy the result values into the output registers.
996   SDValue Glue;
997   SmallVector<SDValue, 4> RetOps;
998   RetOps.push_back(Chain);
999   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1000     CCValAssign &VA = RetLocs[I];
1001     SDValue RetValue = OutVals[I];
1002
1003     // Make the return register live on exit.
1004     assert(VA.isRegLoc() && "Can only return in registers!");
1005
1006     // Promote the value as required.
1007     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1008
1009     // Chain and glue the copies together.
1010     unsigned Reg = VA.getLocReg();
1011     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1012     Glue = Chain.getValue(1);
1013     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1014   }
1015
1016   // Update chain and glue.
1017   RetOps[0] = Chain;
1018   if (Glue.getNode())
1019     RetOps.push_back(Glue);
1020
1021   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1022 }
1023
1024 SDValue SystemZTargetLowering::
1025 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1026   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1027 }
1028
1029 // CC is a comparison that will be implemented using an integer or
1030 // floating-point comparison.  Return the condition code mask for
1031 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
1032 // unsigned comparisons and clear for signed ones.  In the floating-point
1033 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1034 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1035 #define CONV(X) \
1036   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1037   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1038   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1039
1040   switch (CC) {
1041   default:
1042     llvm_unreachable("Invalid integer condition!");
1043
1044   CONV(EQ);
1045   CONV(NE);
1046   CONV(GT);
1047   CONV(GE);
1048   CONV(LT);
1049   CONV(LE);
1050
1051   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
1052   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1053   }
1054 #undef CONV
1055 }
1056
1057 // Return a sequence for getting a 1 from an IPM result when CC has a
1058 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1059 // The handling of CC values outside CCValid doesn't matter.
1060 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1061   // Deal with cases where the result can be taken directly from a bit
1062   // of the IPM result.
1063   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1064     return IPMConversion(0, 0, SystemZ::IPM_CC);
1065   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1066     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1067
1068   // Deal with cases where we can add a value to force the sign bit
1069   // to contain the right value.  Putting the bit in 31 means we can
1070   // use SRL rather than RISBG(L), and also makes it easier to get a
1071   // 0/-1 value, so it has priority over the other tests below.
1072   //
1073   // These sequences rely on the fact that the upper two bits of the
1074   // IPM result are zero.
1075   uint64_t TopBit = uint64_t(1) << 31;
1076   if (CCMask == (CCValid & SystemZ::CCMASK_0))
1077     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1078   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1079     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1080   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1081                             | SystemZ::CCMASK_1
1082                             | SystemZ::CCMASK_2)))
1083     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1084   if (CCMask == (CCValid & SystemZ::CCMASK_3))
1085     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1086   if (CCMask == (CCValid & (SystemZ::CCMASK_1
1087                             | SystemZ::CCMASK_2
1088                             | SystemZ::CCMASK_3)))
1089     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1090
1091   // Next try inverting the value and testing a bit.  0/1 could be
1092   // handled this way too, but we dealt with that case above.
1093   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1094     return IPMConversion(-1, 0, SystemZ::IPM_CC);
1095
1096   // Handle cases where adding a value forces a non-sign bit to contain
1097   // the right value.
1098   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1099     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1100   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1101     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1102
1103   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
1104   // can be done by inverting the low CC bit and applying one of the
1105   // sign-based extractions above.
1106   if (CCMask == (CCValid & SystemZ::CCMASK_1))
1107     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1108   if (CCMask == (CCValid & SystemZ::CCMASK_2))
1109     return IPMConversion(1 << SystemZ::IPM_CC,
1110                          TopBit - (3 << SystemZ::IPM_CC), 31);
1111   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1112                             | SystemZ::CCMASK_1
1113                             | SystemZ::CCMASK_3)))
1114     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1115   if (CCMask == (CCValid & (SystemZ::CCMASK_0
1116                             | SystemZ::CCMASK_2
1117                             | SystemZ::CCMASK_3)))
1118     return IPMConversion(1 << SystemZ::IPM_CC,
1119                          TopBit - (1 << SystemZ::IPM_CC), 31);
1120
1121   llvm_unreachable("Unexpected CC combination");
1122 }
1123
1124 // If C can be converted to a comparison against zero, adjust the operands
1125 // as necessary.
1126 static void adjustZeroCmp(SelectionDAG &DAG, Comparison &C) {
1127   if (C.ICmpType == SystemZICMP::UnsignedOnly)
1128     return;
1129
1130   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1131   if (!ConstOp1)
1132     return;
1133
1134   int64_t Value = ConstOp1->getSExtValue();
1135   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1136       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1137       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1138       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1139     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1140     C.Op1 = DAG.getConstant(0, C.Op1.getValueType());
1141   }
1142 }
1143
1144 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1145 // adjust the operands as necessary.
1146 static void adjustSubwordCmp(SelectionDAG &DAG, Comparison &C) {
1147   // For us to make any changes, it must a comparison between a single-use
1148   // load and a constant.
1149   if (!C.Op0.hasOneUse() ||
1150       C.Op0.getOpcode() != ISD::LOAD ||
1151       C.Op1.getOpcode() != ISD::Constant)
1152     return;
1153
1154   // We must have an 8- or 16-bit load.
1155   auto *Load = cast<LoadSDNode>(C.Op0);
1156   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1157   if (NumBits != 8 && NumBits != 16)
1158     return;
1159
1160   // The load must be an extending one and the constant must be within the
1161   // range of the unextended value.
1162   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1163   uint64_t Value = ConstOp1->getZExtValue();
1164   uint64_t Mask = (1 << NumBits) - 1;
1165   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1166     // Make sure that ConstOp1 is in range of C.Op0.
1167     int64_t SignedValue = ConstOp1->getSExtValue();
1168     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1169       return;
1170     if (C.ICmpType != SystemZICMP::SignedOnly) {
1171       // Unsigned comparison between two sign-extended values is equivalent
1172       // to unsigned comparison between two zero-extended values.
1173       Value &= Mask;
1174     } else if (NumBits == 8) {
1175       // Try to treat the comparison as unsigned, so that we can use CLI.
1176       // Adjust CCMask and Value as necessary.
1177       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1178         // Test whether the high bit of the byte is set.
1179         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1180       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1181         // Test whether the high bit of the byte is clear.
1182         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1183       else
1184         // No instruction exists for this combination.
1185         return;
1186       C.ICmpType = SystemZICMP::UnsignedOnly;
1187     }
1188   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1189     if (Value > Mask)
1190       return;
1191     assert(C.ICmpType == SystemZICMP::Any &&
1192            "Signedness shouldn't matter here.");
1193   } else
1194     return;
1195
1196   // Make sure that the first operand is an i32 of the right extension type.
1197   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1198                               ISD::SEXTLOAD :
1199                               ISD::ZEXTLOAD);
1200   if (C.Op0.getValueType() != MVT::i32 ||
1201       Load->getExtensionType() != ExtType)
1202     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1203                            Load->getChain(), Load->getBasePtr(),
1204                            Load->getPointerInfo(), Load->getMemoryVT(),
1205                            Load->isVolatile(), Load->isNonTemporal(),
1206                            Load->isInvariant(), Load->getAlignment());
1207
1208   // Make sure that the second operand is an i32 with the right value.
1209   if (C.Op1.getValueType() != MVT::i32 ||
1210       Value != ConstOp1->getZExtValue())
1211     C.Op1 = DAG.getConstant(Value, MVT::i32);
1212 }
1213
1214 // Return true if Op is either an unextended load, or a load suitable
1215 // for integer register-memory comparisons of type ICmpType.
1216 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1217   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1218   if (Load) {
1219     // There are no instructions to compare a register with a memory byte.
1220     if (Load->getMemoryVT() == MVT::i8)
1221       return false;
1222     // Otherwise decide on extension type.
1223     switch (Load->getExtensionType()) {
1224     case ISD::NON_EXTLOAD:
1225       return true;
1226     case ISD::SEXTLOAD:
1227       return ICmpType != SystemZICMP::UnsignedOnly;
1228     case ISD::ZEXTLOAD:
1229       return ICmpType != SystemZICMP::SignedOnly;
1230     default:
1231       break;
1232     }
1233   }
1234   return false;
1235 }
1236
1237 // Return true if it is better to swap the operands of C.
1238 static bool shouldSwapCmpOperands(const Comparison &C) {
1239   // Leave f128 comparisons alone, since they have no memory forms.
1240   if (C.Op0.getValueType() == MVT::f128)
1241     return false;
1242
1243   // Always keep a floating-point constant second, since comparisons with
1244   // zero can use LOAD TEST and comparisons with other constants make a
1245   // natural memory operand.
1246   if (isa<ConstantFPSDNode>(C.Op1))
1247     return false;
1248
1249   // Never swap comparisons with zero since there are many ways to optimize
1250   // those later.
1251   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1252   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1253     return false;
1254
1255   // Also keep natural memory operands second if the loaded value is
1256   // only used here.  Several comparisons have memory forms.
1257   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1258     return false;
1259
1260   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1261   // In that case we generally prefer the memory to be second.
1262   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1263     // The only exceptions are when the second operand is a constant and
1264     // we can use things like CHHSI.
1265     if (!ConstOp1)
1266       return true;
1267     // The unsigned memory-immediate instructions can handle 16-bit
1268     // unsigned integers.
1269     if (C.ICmpType != SystemZICMP::SignedOnly &&
1270         isUInt<16>(ConstOp1->getZExtValue()))
1271       return false;
1272     // The signed memory-immediate instructions can handle 16-bit
1273     // signed integers.
1274     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1275         isInt<16>(ConstOp1->getSExtValue()))
1276       return false;
1277     return true;
1278   }
1279
1280   // Try to promote the use of CGFR and CLGFR.
1281   unsigned Opcode0 = C.Op0.getOpcode();
1282   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1283     return true;
1284   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1285     return true;
1286   if (C.ICmpType != SystemZICMP::SignedOnly &&
1287       Opcode0 == ISD::AND &&
1288       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1289       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1290     return true;
1291
1292   return false;
1293 }
1294
1295 // Return a version of comparison CC mask CCMask in which the LT and GT
1296 // actions are swapped.
1297 static unsigned reverseCCMask(unsigned CCMask) {
1298   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1299           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1300           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1301           (CCMask & SystemZ::CCMASK_CMP_UO));
1302 }
1303
1304 // Check whether C tests for equality between X and Y and whether X - Y
1305 // or Y - X is also computed.  In that case it's better to compare the
1306 // result of the subtraction against zero.
1307 static void adjustForSubtraction(SelectionDAG &DAG, Comparison &C) {
1308   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1309       C.CCMask == SystemZ::CCMASK_CMP_NE) {
1310     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1311       SDNode *N = *I;
1312       if (N->getOpcode() == ISD::SUB &&
1313           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1314            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1315         C.Op0 = SDValue(N, 0);
1316         C.Op1 = DAG.getConstant(0, N->getValueType(0));
1317         return;
1318       }
1319     }
1320   }
1321 }
1322
1323 // Check whether C compares a floating-point value with zero and if that
1324 // floating-point value is also negated.  In this case we can use the
1325 // negation to set CC, so avoiding separate LOAD AND TEST and
1326 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1327 static void adjustForFNeg(Comparison &C) {
1328   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1329   if (C1 && C1->isZero()) {
1330     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1331       SDNode *N = *I;
1332       if (N->getOpcode() == ISD::FNEG) {
1333         C.Op0 = SDValue(N, 0);
1334         C.CCMask = reverseCCMask(C.CCMask);
1335         return;
1336       }
1337     }
1338   }
1339 }
1340
1341 // Check whether C compares (shl X, 32) with 0 and whether X is
1342 // also sign-extended.  In that case it is better to test the result
1343 // of the sign extension using LTGFR.
1344 //
1345 // This case is important because InstCombine transforms a comparison
1346 // with (sext (trunc X)) into a comparison with (shl X, 32).
1347 static void adjustForLTGFR(Comparison &C) {
1348   // Check for a comparison between (shl X, 32) and 0.
1349   if (C.Op0.getOpcode() == ISD::SHL &&
1350       C.Op0.getValueType() == MVT::i64 &&
1351       C.Op1.getOpcode() == ISD::Constant &&
1352       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1353     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1354     if (C1 && C1->getZExtValue() == 32) {
1355       SDValue ShlOp0 = C.Op0.getOperand(0);
1356       // See whether X has any SIGN_EXTEND_INREG uses.
1357       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1358         SDNode *N = *I;
1359         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1360             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1361           C.Op0 = SDValue(N, 0);
1362           return;
1363         }
1364       }
1365     }
1366   }
1367 }
1368
1369 // If C compares the truncation of an extending load, try to compare
1370 // the untruncated value instead.  This exposes more opportunities to
1371 // reuse CC.
1372 static void adjustICmpTruncate(SelectionDAG &DAG, Comparison &C) {
1373   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1374       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1375       C.Op1.getOpcode() == ISD::Constant &&
1376       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1377     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1378     if (L->getMemoryVT().getStoreSizeInBits()
1379         <= C.Op0.getValueType().getSizeInBits()) {
1380       unsigned Type = L->getExtensionType();
1381       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1382           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1383         C.Op0 = C.Op0.getOperand(0);
1384         C.Op1 = DAG.getConstant(0, C.Op0.getValueType());
1385       }
1386     }
1387   }
1388 }
1389
1390 // Return true if shift operation N has an in-range constant shift value.
1391 // Store it in ShiftVal if so.
1392 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1393   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1394   if (!Shift)
1395     return false;
1396
1397   uint64_t Amount = Shift->getZExtValue();
1398   if (Amount >= N.getValueType().getSizeInBits())
1399     return false;
1400
1401   ShiftVal = Amount;
1402   return true;
1403 }
1404
1405 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1406 // instruction and whether the CC value is descriptive enough to handle
1407 // a comparison of type Opcode between the AND result and CmpVal.
1408 // CCMask says which comparison result is being tested and BitSize is
1409 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1410 // return the corresponding CC mask, otherwise return 0.
1411 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1412                                      uint64_t Mask, uint64_t CmpVal,
1413                                      unsigned ICmpType) {
1414   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1415
1416   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1417   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1418       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1419     return 0;
1420
1421   // Work out the masks for the lowest and highest bits.
1422   unsigned HighShift = 63 - countLeadingZeros(Mask);
1423   uint64_t High = uint64_t(1) << HighShift;
1424   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1425
1426   // Signed ordered comparisons are effectively unsigned if the sign
1427   // bit is dropped.
1428   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1429
1430   // Check for equality comparisons with 0, or the equivalent.
1431   if (CmpVal == 0) {
1432     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1433       return SystemZ::CCMASK_TM_ALL_0;
1434     if (CCMask == SystemZ::CCMASK_CMP_NE)
1435       return SystemZ::CCMASK_TM_SOME_1;
1436   }
1437   if (EffectivelyUnsigned && CmpVal <= Low) {
1438     if (CCMask == SystemZ::CCMASK_CMP_LT)
1439       return SystemZ::CCMASK_TM_ALL_0;
1440     if (CCMask == SystemZ::CCMASK_CMP_GE)
1441       return SystemZ::CCMASK_TM_SOME_1;
1442   }
1443   if (EffectivelyUnsigned && CmpVal < Low) {
1444     if (CCMask == SystemZ::CCMASK_CMP_LE)
1445       return SystemZ::CCMASK_TM_ALL_0;
1446     if (CCMask == SystemZ::CCMASK_CMP_GT)
1447       return SystemZ::CCMASK_TM_SOME_1;
1448   }
1449
1450   // Check for equality comparisons with the mask, or the equivalent.
1451   if (CmpVal == Mask) {
1452     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1453       return SystemZ::CCMASK_TM_ALL_1;
1454     if (CCMask == SystemZ::CCMASK_CMP_NE)
1455       return SystemZ::CCMASK_TM_SOME_0;
1456   }
1457   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1458     if (CCMask == SystemZ::CCMASK_CMP_GT)
1459       return SystemZ::CCMASK_TM_ALL_1;
1460     if (CCMask == SystemZ::CCMASK_CMP_LE)
1461       return SystemZ::CCMASK_TM_SOME_0;
1462   }
1463   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1464     if (CCMask == SystemZ::CCMASK_CMP_GE)
1465       return SystemZ::CCMASK_TM_ALL_1;
1466     if (CCMask == SystemZ::CCMASK_CMP_LT)
1467       return SystemZ::CCMASK_TM_SOME_0;
1468   }
1469
1470   // Check for ordered comparisons with the top bit.
1471   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1472     if (CCMask == SystemZ::CCMASK_CMP_LE)
1473       return SystemZ::CCMASK_TM_MSB_0;
1474     if (CCMask == SystemZ::CCMASK_CMP_GT)
1475       return SystemZ::CCMASK_TM_MSB_1;
1476   }
1477   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1478     if (CCMask == SystemZ::CCMASK_CMP_LT)
1479       return SystemZ::CCMASK_TM_MSB_0;
1480     if (CCMask == SystemZ::CCMASK_CMP_GE)
1481       return SystemZ::CCMASK_TM_MSB_1;
1482   }
1483
1484   // If there are just two bits, we can do equality checks for Low and High
1485   // as well.
1486   if (Mask == Low + High) {
1487     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1488       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1489     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1490       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1491     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1492       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1493     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1494       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1495   }
1496
1497   // Looks like we've exhausted our options.
1498   return 0;
1499 }
1500
1501 // See whether C can be implemented as a TEST UNDER MASK instruction.
1502 // Update the arguments with the TM version if so.
1503 static void adjustForTestUnderMask(SelectionDAG &DAG, Comparison &C) {
1504   // Check that we have a comparison with a constant.
1505   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1506   if (!ConstOp1)
1507     return;
1508   uint64_t CmpVal = ConstOp1->getZExtValue();
1509
1510   // Check whether the nonconstant input is an AND with a constant mask.
1511   Comparison NewC(C);
1512   uint64_t MaskVal;
1513   ConstantSDNode *Mask = nullptr;
1514   if (C.Op0.getOpcode() == ISD::AND) {
1515     NewC.Op0 = C.Op0.getOperand(0);
1516     NewC.Op1 = C.Op0.getOperand(1);
1517     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1518     if (!Mask)
1519       return;
1520     MaskVal = Mask->getZExtValue();
1521   } else {
1522     // There is no instruction to compare with a 64-bit immediate
1523     // so use TMHH instead if possible.  We need an unsigned ordered
1524     // comparison with an i64 immediate.
1525     if (NewC.Op0.getValueType() != MVT::i64 ||
1526         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1527         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1528         NewC.ICmpType == SystemZICMP::SignedOnly)
1529       return;
1530     // Convert LE and GT comparisons into LT and GE.
1531     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1532         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1533       if (CmpVal == uint64_t(-1))
1534         return;
1535       CmpVal += 1;
1536       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1537     }
1538     // If the low N bits of Op1 are zero than the low N bits of Op0 can
1539     // be masked off without changing the result.
1540     MaskVal = -(CmpVal & -CmpVal);
1541     NewC.ICmpType = SystemZICMP::UnsignedOnly;
1542   }
1543   if (!MaskVal)
1544     return;
1545
1546   // Check whether the combination of mask, comparison value and comparison
1547   // type are suitable.
1548   unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
1549   unsigned NewCCMask, ShiftVal;
1550   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1551       NewC.Op0.getOpcode() == ISD::SHL &&
1552       isSimpleShift(NewC.Op0, ShiftVal) &&
1553       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1554                                         MaskVal >> ShiftVal,
1555                                         CmpVal >> ShiftVal,
1556                                         SystemZICMP::Any))) {
1557     NewC.Op0 = NewC.Op0.getOperand(0);
1558     MaskVal >>= ShiftVal;
1559   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1560              NewC.Op0.getOpcode() == ISD::SRL &&
1561              isSimpleShift(NewC.Op0, ShiftVal) &&
1562              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1563                                                MaskVal << ShiftVal,
1564                                                CmpVal << ShiftVal,
1565                                                SystemZICMP::UnsignedOnly))) {
1566     NewC.Op0 = NewC.Op0.getOperand(0);
1567     MaskVal <<= ShiftVal;
1568   } else {
1569     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
1570                                      NewC.ICmpType);
1571     if (!NewCCMask)
1572       return;
1573   }
1574
1575   // Go ahead and make the change.
1576   C.Opcode = SystemZISD::TM;
1577   C.Op0 = NewC.Op0;
1578   if (Mask && Mask->getZExtValue() == MaskVal)
1579     C.Op1 = SDValue(Mask, 0);
1580   else
1581     C.Op1 = DAG.getConstant(MaskVal, C.Op0.getValueType());
1582   C.CCValid = SystemZ::CCMASK_TM;
1583   C.CCMask = NewCCMask;
1584 }
1585
1586 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
1587 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
1588                          ISD::CondCode Cond) {
1589   Comparison C(CmpOp0, CmpOp1);
1590   C.CCMask = CCMaskForCondCode(Cond);
1591   if (C.Op0.getValueType().isFloatingPoint()) {
1592     C.CCValid = SystemZ::CCMASK_FCMP;
1593     C.Opcode = SystemZISD::FCMP;
1594     adjustForFNeg(C);
1595   } else {
1596     C.CCValid = SystemZ::CCMASK_ICMP;
1597     C.Opcode = SystemZISD::ICMP;
1598     // Choose the type of comparison.  Equality and inequality tests can
1599     // use either signed or unsigned comparisons.  The choice also doesn't
1600     // matter if both sign bits are known to be clear.  In those cases we
1601     // want to give the main isel code the freedom to choose whichever
1602     // form fits best.
1603     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1604         C.CCMask == SystemZ::CCMASK_CMP_NE ||
1605         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
1606       C.ICmpType = SystemZICMP::Any;
1607     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
1608       C.ICmpType = SystemZICMP::UnsignedOnly;
1609     else
1610       C.ICmpType = SystemZICMP::SignedOnly;
1611     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
1612     adjustZeroCmp(DAG, C);
1613     adjustSubwordCmp(DAG, C);
1614     adjustForSubtraction(DAG, C);
1615     adjustForLTGFR(C);
1616     adjustICmpTruncate(DAG, C);
1617   }
1618
1619   if (shouldSwapCmpOperands(C)) {
1620     std::swap(C.Op0, C.Op1);
1621     C.CCMask = reverseCCMask(C.CCMask);
1622   }
1623
1624   adjustForTestUnderMask(DAG, C);
1625   return C;
1626 }
1627
1628 // Emit the comparison instruction described by C.
1629 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1630   if (C.Opcode == SystemZISD::ICMP)
1631     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
1632                        DAG.getConstant(C.ICmpType, MVT::i32));
1633   if (C.Opcode == SystemZISD::TM) {
1634     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1635                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1636     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
1637                        DAG.getConstant(RegisterOnly, MVT::i32));
1638   }
1639   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
1640 }
1641
1642 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1643 // 64 bits.  Extend is the extension type to use.  Store the high part
1644 // in Hi and the low part in Lo.
1645 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1646                             unsigned Extend, SDValue Op0, SDValue Op1,
1647                             SDValue &Hi, SDValue &Lo) {
1648   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1649   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1650   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1651   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
1652   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1653   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1654 }
1655
1656 // Lower a binary operation that produces two VT results, one in each
1657 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1658 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1659 // on the extended Op0 and (unextended) Op1.  Store the even register result
1660 // in Even and the odd register result in Odd.
1661 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1662                              unsigned Extend, unsigned Opcode,
1663                              SDValue Op0, SDValue Op1,
1664                              SDValue &Even, SDValue &Odd) {
1665   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1666   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1667                                SDValue(In128, 0), Op1);
1668   bool Is32Bit = is32Bit(VT);
1669   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
1670   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
1671 }
1672
1673 // Return an i32 value that is 1 if the CC value produced by Glue is
1674 // in the mask CCMask and 0 otherwise.  CC is known to have a value
1675 // in CCValid, so other values can be ignored.
1676 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
1677                          unsigned CCValid, unsigned CCMask) {
1678   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
1679   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
1680
1681   if (Conversion.XORValue)
1682     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
1683                          DAG.getConstant(Conversion.XORValue, MVT::i32));
1684
1685   if (Conversion.AddValue)
1686     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
1687                          DAG.getConstant(Conversion.AddValue, MVT::i32));
1688
1689   // The SHR/AND sequence should get optimized to an RISBG.
1690   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
1691                        DAG.getConstant(Conversion.Bit, MVT::i32));
1692   if (Conversion.Bit != 31)
1693     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
1694                          DAG.getConstant(1, MVT::i32));
1695   return Result;
1696 }
1697
1698 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
1699                                           SelectionDAG &DAG) const {
1700   SDValue CmpOp0   = Op.getOperand(0);
1701   SDValue CmpOp1   = Op.getOperand(1);
1702   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1703   SDLoc DL(Op);
1704
1705   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
1706   SDValue Glue = emitCmp(DAG, DL, C);
1707   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
1708 }
1709
1710 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1711   SDValue Chain    = Op.getOperand(0);
1712   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1713   SDValue CmpOp0   = Op.getOperand(2);
1714   SDValue CmpOp1   = Op.getOperand(3);
1715   SDValue Dest     = Op.getOperand(4);
1716   SDLoc DL(Op);
1717
1718   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
1719   SDValue Glue = emitCmp(DAG, DL, C);
1720   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1721                      Chain, DAG.getConstant(C.CCValid, MVT::i32),
1722                      DAG.getConstant(C.CCMask, MVT::i32), Dest, Glue);
1723 }
1724
1725 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
1726 // allowing Pos and Neg to be wider than CmpOp.
1727 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
1728   return (Neg.getOpcode() == ISD::SUB &&
1729           Neg.getOperand(0).getOpcode() == ISD::Constant &&
1730           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
1731           Neg.getOperand(1) == Pos &&
1732           (Pos == CmpOp ||
1733            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
1734             Pos.getOperand(0) == CmpOp)));
1735 }
1736
1737 // Return the absolute or negative absolute of Op; IsNegative decides which.
1738 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
1739                            bool IsNegative) {
1740   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
1741   if (IsNegative)
1742     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
1743                      DAG.getConstant(0, Op.getValueType()), Op);
1744   return Op;
1745 }
1746
1747 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1748                                               SelectionDAG &DAG) const {
1749   SDValue CmpOp0   = Op.getOperand(0);
1750   SDValue CmpOp1   = Op.getOperand(1);
1751   SDValue TrueOp   = Op.getOperand(2);
1752   SDValue FalseOp  = Op.getOperand(3);
1753   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1754   SDLoc DL(Op);
1755
1756   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
1757
1758   // Check for absolute and negative-absolute selections, including those
1759   // where the comparison value is sign-extended (for LPGFR and LNGFR).
1760   // This check supplements the one in DAGCombiner.
1761   if (C.Opcode == SystemZISD::ICMP &&
1762       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
1763       C.CCMask != SystemZ::CCMASK_CMP_NE &&
1764       C.Op1.getOpcode() == ISD::Constant &&
1765       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1766     if (isAbsolute(C.Op0, TrueOp, FalseOp))
1767       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
1768     if (isAbsolute(C.Op0, FalseOp, TrueOp))
1769       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
1770   }
1771
1772   SDValue Glue = emitCmp(DAG, DL, C);
1773
1774   // Special case for handling -1/0 results.  The shifts we use here
1775   // should get optimized with the IPM conversion sequence.
1776   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
1777   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
1778   if (TrueC && FalseC) {
1779     int64_t TrueVal = TrueC->getSExtValue();
1780     int64_t FalseVal = FalseC->getSExtValue();
1781     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
1782       // Invert the condition if we want -1 on false.
1783       if (TrueVal == 0)
1784         C.CCMask ^= C.CCValid;
1785       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
1786       EVT VT = Op.getValueType();
1787       // Extend the result to VT.  Upper bits are ignored.
1788       if (!is32Bit(VT))
1789         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
1790       // Sign-extend from the low bit.
1791       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, MVT::i32);
1792       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
1793       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
1794     }
1795   }
1796
1797   SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, MVT::i32),
1798                    DAG.getConstant(C.CCMask, MVT::i32), Glue};
1799
1800   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1801   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
1802 }
1803
1804 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1805                                                   SelectionDAG &DAG) const {
1806   SDLoc DL(Node);
1807   const GlobalValue *GV = Node->getGlobal();
1808   int64_t Offset = Node->getOffset();
1809   EVT PtrVT = getPointerTy();
1810   Reloc::Model RM = DAG.getTarget().getRelocationModel();
1811   CodeModel::Model CM = DAG.getTarget().getCodeModel();
1812
1813   SDValue Result;
1814   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1815     // Assign anchors at 1<<12 byte boundaries.
1816     uint64_t Anchor = Offset & ~uint64_t(0xfff);
1817     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
1818     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1819
1820     // The offset can be folded into the address if it is aligned to a halfword.
1821     Offset -= Anchor;
1822     if (Offset != 0 && (Offset & 1) == 0) {
1823       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
1824       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
1825       Offset = 0;
1826     }
1827   } else {
1828     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1829     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1830     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1831                          MachinePointerInfo::getGOT(), false, false, false, 0);
1832   }
1833
1834   // If there was a non-zero offset that we didn't fold, create an explicit
1835   // addition for it.
1836   if (Offset != 0)
1837     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1838                          DAG.getConstant(Offset, PtrVT));
1839
1840   return Result;
1841 }
1842
1843 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
1844                                                  SelectionDAG &DAG,
1845                                                  unsigned Opcode,
1846                                                  SDValue GOTOffset) const {
1847   SDLoc DL(Node);
1848   EVT PtrVT = getPointerTy();
1849   SDValue Chain = DAG.getEntryNode();
1850   SDValue Glue;
1851
1852   // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
1853   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1854   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
1855   Glue = Chain.getValue(1);
1856   Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
1857   Glue = Chain.getValue(1);
1858
1859   // The first call operand is the chain and the second is the TLS symbol.
1860   SmallVector<SDValue, 8> Ops;
1861   Ops.push_back(Chain);
1862   Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
1863                                            Node->getValueType(0),
1864                                            0, 0));
1865
1866   // Add argument registers to the end of the list so that they are
1867   // known live into the call.
1868   Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
1869   Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
1870
1871   // Add a register mask operand representing the call-preserved registers.
1872   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1873   const uint32_t *Mask =
1874       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
1875   assert(Mask && "Missing call preserved mask for calling convention");
1876   Ops.push_back(DAG.getRegisterMask(Mask));
1877
1878   // Glue the call to the argument copies.
1879   Ops.push_back(Glue);
1880
1881   // Emit the call.
1882   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1883   Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
1884   Glue = Chain.getValue(1);
1885
1886   // Copy the return value from %r2.
1887   return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
1888 }
1889
1890 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1891                                                      SelectionDAG &DAG) const {
1892   SDLoc DL(Node);
1893   const GlobalValue *GV = Node->getGlobal();
1894   EVT PtrVT = getPointerTy();
1895   TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
1896
1897   // The high part of the thread pointer is in access register 0.
1898   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1899                              DAG.getConstant(0, MVT::i32));
1900   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1901
1902   // The low part of the thread pointer is in access register 1.
1903   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1904                              DAG.getConstant(1, MVT::i32));
1905   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1906
1907   // Merge them into a single 64-bit address.
1908   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1909                                     DAG.getConstant(32, PtrVT));
1910   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1911
1912   // Get the offset of GA from the thread pointer, based on the TLS model.
1913   SDValue Offset;
1914   switch (model) {
1915     case TLSModel::GeneralDynamic: {
1916       // Load the GOT offset of the tls_index (module ID / per-symbol offset).
1917       SystemZConstantPoolValue *CPV =
1918         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
1919
1920       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
1921       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1922                            Offset, MachinePointerInfo::getConstantPool(),
1923                            false, false, false, 0);
1924
1925       // Call __tls_get_offset to retrieve the offset.
1926       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
1927       break;
1928     }
1929
1930     case TLSModel::LocalDynamic: {
1931       // Load the GOT offset of the module ID.
1932       SystemZConstantPoolValue *CPV =
1933         SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
1934
1935       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
1936       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1937                            Offset, MachinePointerInfo::getConstantPool(),
1938                            false, false, false, 0);
1939
1940       // Call __tls_get_offset to retrieve the module base offset.
1941       Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
1942
1943       // Note: The SystemZLDCleanupPass will remove redundant computations
1944       // of the module base offset.  Count total number of local-dynamic
1945       // accesses to trigger execution of that pass.
1946       SystemZMachineFunctionInfo* MFI =
1947         DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
1948       MFI->incNumLocalDynamicTLSAccesses();
1949
1950       // Add the per-symbol offset.
1951       CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
1952
1953       SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
1954       DTPOffset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1955                               DTPOffset, MachinePointerInfo::getConstantPool(),
1956                               false, false, false, 0);
1957
1958       Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
1959       break;
1960     }
1961
1962     case TLSModel::InitialExec: {
1963       // Load the offset from the GOT.
1964       Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1965                                           SystemZII::MO_INDNTPOFF);
1966       Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
1967       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1968                            Offset, MachinePointerInfo::getGOT(),
1969                            false, false, false, 0);
1970       break;
1971     }
1972
1973     case TLSModel::LocalExec: {
1974       // Force the offset into the constant pool and load it from there.
1975       SystemZConstantPoolValue *CPV =
1976         SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1977
1978       Offset = DAG.getConstantPool(CPV, PtrVT, 8);
1979       Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1980                            Offset, MachinePointerInfo::getConstantPool(),
1981                            false, false, false, 0);
1982       break;
1983     }
1984   }
1985
1986   // Add the base and offset together.
1987   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1988 }
1989
1990 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1991                                                  SelectionDAG &DAG) const {
1992   SDLoc DL(Node);
1993   const BlockAddress *BA = Node->getBlockAddress();
1994   int64_t Offset = Node->getOffset();
1995   EVT PtrVT = getPointerTy();
1996
1997   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1998   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1999   return Result;
2000 }
2001
2002 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2003                                               SelectionDAG &DAG) const {
2004   SDLoc DL(JT);
2005   EVT PtrVT = getPointerTy();
2006   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2007
2008   // Use LARL to load the address of the table.
2009   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2010 }
2011
2012 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2013                                                  SelectionDAG &DAG) const {
2014   SDLoc DL(CP);
2015   EVT PtrVT = getPointerTy();
2016
2017   SDValue Result;
2018   if (CP->isMachineConstantPoolEntry())
2019     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2020                                        CP->getAlignment());
2021   else
2022     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2023                                        CP->getAlignment(), CP->getOffset());
2024
2025   // Use LARL to load the address of the constant pool entry.
2026   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2027 }
2028
2029 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2030                                             SelectionDAG &DAG) const {
2031   SDLoc DL(Op);
2032   SDValue In = Op.getOperand(0);
2033   EVT InVT = In.getValueType();
2034   EVT ResVT = Op.getValueType();
2035
2036   if (InVT == MVT::i32 && ResVT == MVT::f32) {
2037     SDValue In64;
2038     if (Subtarget.hasHighWord()) {
2039       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2040                                        MVT::i64);
2041       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2042                                        MVT::i64, SDValue(U64, 0), In);
2043     } else {
2044       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2045       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2046                          DAG.getConstant(32, MVT::i64));
2047     }
2048     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2049     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
2050                                       DL, MVT::f32, Out64);
2051   }
2052   if (InVT == MVT::f32 && ResVT == MVT::i32) {
2053     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2054     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2055                                              MVT::f64, SDValue(U64, 0), In);
2056     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2057     if (Subtarget.hasHighWord())
2058       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2059                                         MVT::i32, Out64);
2060     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2061                                 DAG.getConstant(32, MVT::i64));
2062     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2063   }
2064   llvm_unreachable("Unexpected bitcast combination");
2065 }
2066
2067 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2068                                             SelectionDAG &DAG) const {
2069   MachineFunction &MF = DAG.getMachineFunction();
2070   SystemZMachineFunctionInfo *FuncInfo =
2071     MF.getInfo<SystemZMachineFunctionInfo>();
2072   EVT PtrVT = getPointerTy();
2073
2074   SDValue Chain   = Op.getOperand(0);
2075   SDValue Addr    = Op.getOperand(1);
2076   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2077   SDLoc DL(Op);
2078
2079   // The initial values of each field.
2080   const unsigned NumFields = 4;
2081   SDValue Fields[NumFields] = {
2082     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
2083     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
2084     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2085     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2086   };
2087
2088   // Store each field into its respective slot.
2089   SDValue MemOps[NumFields];
2090   unsigned Offset = 0;
2091   for (unsigned I = 0; I < NumFields; ++I) {
2092     SDValue FieldAddr = Addr;
2093     if (Offset != 0)
2094       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2095                               DAG.getIntPtrConstant(Offset));
2096     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2097                              MachinePointerInfo(SV, Offset),
2098                              false, false, 0);
2099     Offset += 8;
2100   }
2101   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2102 }
2103
2104 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2105                                            SelectionDAG &DAG) const {
2106   SDValue Chain      = Op.getOperand(0);
2107   SDValue DstPtr     = Op.getOperand(1);
2108   SDValue SrcPtr     = Op.getOperand(2);
2109   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2110   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2111   SDLoc DL(Op);
2112
2113   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
2114                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2115                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2116 }
2117
2118 SDValue SystemZTargetLowering::
2119 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2120   SDValue Chain = Op.getOperand(0);
2121   SDValue Size  = Op.getOperand(1);
2122   SDLoc DL(Op);
2123
2124   unsigned SPReg = getStackPointerRegisterToSaveRestore();
2125
2126   // Get a reference to the stack pointer.
2127   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2128
2129   // Get the new stack pointer value.
2130   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
2131
2132   // Copy the new stack pointer back.
2133   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2134
2135   // The allocated data lives above the 160 bytes allocated for the standard
2136   // frame, plus any outgoing stack arguments.  We don't know how much that
2137   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2138   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2139   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2140
2141   SDValue Ops[2] = { Result, Chain };
2142   return DAG.getMergeValues(Ops, DL);
2143 }
2144
2145 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2146                                               SelectionDAG &DAG) const {
2147   EVT VT = Op.getValueType();
2148   SDLoc DL(Op);
2149   SDValue Ops[2];
2150   if (is32Bit(VT))
2151     // Just do a normal 64-bit multiplication and extract the results.
2152     // We define this so that it can be used for constant division.
2153     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2154                     Op.getOperand(1), Ops[1], Ops[0]);
2155   else {
2156     // Do a full 128-bit multiplication based on UMUL_LOHI64:
2157     //
2158     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2159     //
2160     // but using the fact that the upper halves are either all zeros
2161     // or all ones:
2162     //
2163     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2164     //
2165     // and grouping the right terms together since they are quicker than the
2166     // multiplication:
2167     //
2168     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2169     SDValue C63 = DAG.getConstant(63, MVT::i64);
2170     SDValue LL = Op.getOperand(0);
2171     SDValue RL = Op.getOperand(1);
2172     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2173     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2174     // UMUL_LOHI64 returns the low result in the odd register and the high
2175     // result in the even register.  SMUL_LOHI is defined to return the
2176     // low half first, so the results are in reverse order.
2177     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2178                      LL, RL, Ops[1], Ops[0]);
2179     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2180     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2181     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2182     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2183   }
2184   return DAG.getMergeValues(Ops, DL);
2185 }
2186
2187 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2188                                               SelectionDAG &DAG) const {
2189   EVT VT = Op.getValueType();
2190   SDLoc DL(Op);
2191   SDValue Ops[2];
2192   if (is32Bit(VT))
2193     // Just do a normal 64-bit multiplication and extract the results.
2194     // We define this so that it can be used for constant division.
2195     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2196                     Op.getOperand(1), Ops[1], Ops[0]);
2197   else
2198     // UMUL_LOHI64 returns the low result in the odd register and the high
2199     // result in the even register.  UMUL_LOHI is defined to return the
2200     // low half first, so the results are in reverse order.
2201     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2202                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2203   return DAG.getMergeValues(Ops, DL);
2204 }
2205
2206 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2207                                             SelectionDAG &DAG) const {
2208   SDValue Op0 = Op.getOperand(0);
2209   SDValue Op1 = Op.getOperand(1);
2210   EVT VT = Op.getValueType();
2211   SDLoc DL(Op);
2212   unsigned Opcode;
2213
2214   // We use DSGF for 32-bit division.
2215   if (is32Bit(VT)) {
2216     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2217     Opcode = SystemZISD::SDIVREM32;
2218   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2219     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2220     Opcode = SystemZISD::SDIVREM32;
2221   } else    
2222     Opcode = SystemZISD::SDIVREM64;
2223
2224   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2225   // input is "don't care".  The instruction returns the remainder in
2226   // the even register and the quotient in the odd register.
2227   SDValue Ops[2];
2228   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2229                    Op0, Op1, Ops[1], Ops[0]);
2230   return DAG.getMergeValues(Ops, DL);
2231 }
2232
2233 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2234                                             SelectionDAG &DAG) const {
2235   EVT VT = Op.getValueType();
2236   SDLoc DL(Op);
2237
2238   // DL(G) uses a double-width dividend, so we need to clear the even
2239   // register in the GR128 input.  The instruction returns the remainder
2240   // in the even register and the quotient in the odd register.
2241   SDValue Ops[2];
2242   if (is32Bit(VT))
2243     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2244                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2245   else
2246     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2247                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2248   return DAG.getMergeValues(Ops, DL);
2249 }
2250
2251 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2252   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2253
2254   // Get the known-zero masks for each operand.
2255   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2256   APInt KnownZero[2], KnownOne[2];
2257   DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
2258   DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
2259
2260   // See if the upper 32 bits of one operand and the lower 32 bits of the
2261   // other are known zero.  They are the low and high operands respectively.
2262   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2263                        KnownZero[1].getZExtValue() };
2264   unsigned High, Low;
2265   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2266     High = 1, Low = 0;
2267   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2268     High = 0, Low = 1;
2269   else
2270     return Op;
2271
2272   SDValue LowOp = Ops[Low];
2273   SDValue HighOp = Ops[High];
2274
2275   // If the high part is a constant, we're better off using IILH.
2276   if (HighOp.getOpcode() == ISD::Constant)
2277     return Op;
2278
2279   // If the low part is a constant that is outside the range of LHI,
2280   // then we're better off using IILF.
2281   if (LowOp.getOpcode() == ISD::Constant) {
2282     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2283     if (!isInt<16>(Value))
2284       return Op;
2285   }
2286
2287   // Check whether the high part is an AND that doesn't change the
2288   // high 32 bits and just masks out low bits.  We can skip it if so.
2289   if (HighOp.getOpcode() == ISD::AND &&
2290       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2291     SDValue HighOp0 = HighOp.getOperand(0);
2292     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2293     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2294       HighOp = HighOp0;
2295   }
2296
2297   // Take advantage of the fact that all GR32 operations only change the
2298   // low 32 bits by truncating Low to an i32 and inserting it directly
2299   // using a subreg.  The interesting cases are those where the truncation
2300   // can be folded.
2301   SDLoc DL(Op);
2302   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2303   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2304                                    MVT::i64, HighOp, Low32);
2305 }
2306
2307 // Op is an atomic load.  Lower it into a normal volatile load.
2308 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
2309                                                 SelectionDAG &DAG) const {
2310   auto *Node = cast<AtomicSDNode>(Op.getNode());
2311   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
2312                         Node->getChain(), Node->getBasePtr(),
2313                         Node->getMemoryVT(), Node->getMemOperand());
2314 }
2315
2316 // Op is an atomic store.  Lower it into a normal volatile store followed
2317 // by a serialization.
2318 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
2319                                                  SelectionDAG &DAG) const {
2320   auto *Node = cast<AtomicSDNode>(Op.getNode());
2321   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
2322                                     Node->getBasePtr(), Node->getMemoryVT(),
2323                                     Node->getMemOperand());
2324   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
2325                                     Chain), 0);
2326 }
2327
2328 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
2329 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
2330 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
2331                                                    SelectionDAG &DAG,
2332                                                    unsigned Opcode) const {
2333   auto *Node = cast<AtomicSDNode>(Op.getNode());
2334
2335   // 32-bit operations need no code outside the main loop.
2336   EVT NarrowVT = Node->getMemoryVT();
2337   EVT WideVT = MVT::i32;
2338   if (NarrowVT == WideVT)
2339     return Op;
2340
2341   int64_t BitSize = NarrowVT.getSizeInBits();
2342   SDValue ChainIn = Node->getChain();
2343   SDValue Addr = Node->getBasePtr();
2344   SDValue Src2 = Node->getVal();
2345   MachineMemOperand *MMO = Node->getMemOperand();
2346   SDLoc DL(Node);
2347   EVT PtrVT = Addr.getValueType();
2348
2349   // Convert atomic subtracts of constants into additions.
2350   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
2351     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
2352       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
2353       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
2354     }
2355
2356   // Get the address of the containing word.
2357   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2358                                     DAG.getConstant(-4, PtrVT));
2359
2360   // Get the number of bits that the word must be rotated left in order
2361   // to bring the field to the top bits of a GR32.
2362   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2363                                  DAG.getConstant(3, PtrVT));
2364   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2365
2366   // Get the complementing shift amount, for rotating a field in the top
2367   // bits back to its proper position.
2368   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2369                                     DAG.getConstant(0, WideVT), BitShift);
2370
2371   // Extend the source operand to 32 bits and prepare it for the inner loop.
2372   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
2373   // operations require the source to be shifted in advance.  (This shift
2374   // can be folded if the source is constant.)  For AND and NAND, the lower
2375   // bits must be set, while for other opcodes they should be left clear.
2376   if (Opcode != SystemZISD::ATOMIC_SWAPW)
2377     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
2378                        DAG.getConstant(32 - BitSize, WideVT));
2379   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
2380       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
2381     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
2382                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
2383
2384   // Construct the ATOMIC_LOADW_* node.
2385   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2386   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
2387                     DAG.getConstant(BitSize, WideVT) };
2388   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
2389                                              NarrowVT, MMO);
2390
2391   // Rotate the result of the final CS so that the field is in the lower
2392   // bits of a GR32, then truncate it.
2393   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
2394                                     DAG.getConstant(BitSize, WideVT));
2395   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
2396
2397   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
2398   return DAG.getMergeValues(RetOps, DL);
2399 }
2400
2401 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
2402 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
2403 // operations into additions.
2404 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
2405                                                     SelectionDAG &DAG) const {
2406   auto *Node = cast<AtomicSDNode>(Op.getNode());
2407   EVT MemVT = Node->getMemoryVT();
2408   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
2409     // A full-width operation.
2410     assert(Op.getValueType() == MemVT && "Mismatched VTs");
2411     SDValue Src2 = Node->getVal();
2412     SDValue NegSrc2;
2413     SDLoc DL(Src2);
2414
2415     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
2416       // Use an addition if the operand is constant and either LAA(G) is
2417       // available or the negative value is in the range of A(G)FHI.
2418       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
2419       if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
2420         NegSrc2 = DAG.getConstant(Value, MemVT);
2421     } else if (Subtarget.hasInterlockedAccess1())
2422       // Use LAA(G) if available.
2423       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, MemVT),
2424                             Src2);
2425
2426     if (NegSrc2.getNode())
2427       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
2428                            Node->getChain(), Node->getBasePtr(), NegSrc2,
2429                            Node->getMemOperand(), Node->getOrdering(),
2430                            Node->getSynchScope());
2431
2432     // Use the node as-is.
2433     return Op;
2434   }
2435
2436   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2437 }
2438
2439 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
2440 // into a fullword ATOMIC_CMP_SWAPW operation.
2441 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
2442                                                     SelectionDAG &DAG) const {
2443   auto *Node = cast<AtomicSDNode>(Op.getNode());
2444
2445   // We have native support for 32-bit compare and swap.
2446   EVT NarrowVT = Node->getMemoryVT();
2447   EVT WideVT = MVT::i32;
2448   if (NarrowVT == WideVT)
2449     return Op;
2450
2451   int64_t BitSize = NarrowVT.getSizeInBits();
2452   SDValue ChainIn = Node->getOperand(0);
2453   SDValue Addr = Node->getOperand(1);
2454   SDValue CmpVal = Node->getOperand(2);
2455   SDValue SwapVal = Node->getOperand(3);
2456   MachineMemOperand *MMO = Node->getMemOperand();
2457   SDLoc DL(Node);
2458   EVT PtrVT = Addr.getValueType();
2459
2460   // Get the address of the containing word.
2461   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
2462                                     DAG.getConstant(-4, PtrVT));
2463
2464   // Get the number of bits that the word must be rotated left in order
2465   // to bring the field to the top bits of a GR32.
2466   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
2467                                  DAG.getConstant(3, PtrVT));
2468   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
2469
2470   // Get the complementing shift amount, for rotating a field in the top
2471   // bits back to its proper position.
2472   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
2473                                     DAG.getConstant(0, WideVT), BitShift);
2474
2475   // Construct the ATOMIC_CMP_SWAPW node.
2476   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
2477   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
2478                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
2479   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
2480                                              VTList, Ops, NarrowVT, MMO);
2481   return AtomicOp;
2482 }
2483
2484 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
2485                                               SelectionDAG &DAG) const {
2486   MachineFunction &MF = DAG.getMachineFunction();
2487   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2488   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
2489                             SystemZ::R15D, Op.getValueType());
2490 }
2491
2492 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
2493                                                  SelectionDAG &DAG) const {
2494   MachineFunction &MF = DAG.getMachineFunction();
2495   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
2496   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
2497                           SystemZ::R15D, Op.getOperand(1));
2498 }
2499
2500 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
2501                                              SelectionDAG &DAG) const {
2502   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2503   if (!IsData)
2504     // Just preserve the chain.
2505     return Op.getOperand(0);
2506
2507   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2508   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
2509   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
2510   SDValue Ops[] = {
2511     Op.getOperand(0),
2512     DAG.getConstant(Code, MVT::i32),
2513     Op.getOperand(1)
2514   };
2515   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
2516                                  Node->getVTList(), Ops,
2517                                  Node->getMemoryVT(), Node->getMemOperand());
2518 }
2519
2520 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
2521                                               SelectionDAG &DAG) const {
2522   switch (Op.getOpcode()) {
2523   case ISD::BR_CC:
2524     return lowerBR_CC(Op, DAG);
2525   case ISD::SELECT_CC:
2526     return lowerSELECT_CC(Op, DAG);
2527   case ISD::SETCC:
2528     return lowerSETCC(Op, DAG);
2529   case ISD::GlobalAddress:
2530     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
2531   case ISD::GlobalTLSAddress:
2532     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
2533   case ISD::BlockAddress:
2534     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
2535   case ISD::JumpTable:
2536     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
2537   case ISD::ConstantPool:
2538     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
2539   case ISD::BITCAST:
2540     return lowerBITCAST(Op, DAG);
2541   case ISD::VASTART:
2542     return lowerVASTART(Op, DAG);
2543   case ISD::VACOPY:
2544     return lowerVACOPY(Op, DAG);
2545   case ISD::DYNAMIC_STACKALLOC:
2546     return lowerDYNAMIC_STACKALLOC(Op, DAG);
2547   case ISD::SMUL_LOHI:
2548     return lowerSMUL_LOHI(Op, DAG);
2549   case ISD::UMUL_LOHI:
2550     return lowerUMUL_LOHI(Op, DAG);
2551   case ISD::SDIVREM:
2552     return lowerSDIVREM(Op, DAG);
2553   case ISD::UDIVREM:
2554     return lowerUDIVREM(Op, DAG);
2555   case ISD::OR:
2556     return lowerOR(Op, DAG);
2557   case ISD::ATOMIC_SWAP:
2558     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
2559   case ISD::ATOMIC_STORE:
2560     return lowerATOMIC_STORE(Op, DAG);
2561   case ISD::ATOMIC_LOAD:
2562     return lowerATOMIC_LOAD(Op, DAG);
2563   case ISD::ATOMIC_LOAD_ADD:
2564     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
2565   case ISD::ATOMIC_LOAD_SUB:
2566     return lowerATOMIC_LOAD_SUB(Op, DAG);
2567   case ISD::ATOMIC_LOAD_AND:
2568     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
2569   case ISD::ATOMIC_LOAD_OR:
2570     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
2571   case ISD::ATOMIC_LOAD_XOR:
2572     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
2573   case ISD::ATOMIC_LOAD_NAND:
2574     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
2575   case ISD::ATOMIC_LOAD_MIN:
2576     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
2577   case ISD::ATOMIC_LOAD_MAX:
2578     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
2579   case ISD::ATOMIC_LOAD_UMIN:
2580     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
2581   case ISD::ATOMIC_LOAD_UMAX:
2582     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
2583   case ISD::ATOMIC_CMP_SWAP:
2584     return lowerATOMIC_CMP_SWAP(Op, DAG);
2585   case ISD::STACKSAVE:
2586     return lowerSTACKSAVE(Op, DAG);
2587   case ISD::STACKRESTORE:
2588     return lowerSTACKRESTORE(Op, DAG);
2589   case ISD::PREFETCH:
2590     return lowerPREFETCH(Op, DAG);
2591   default:
2592     llvm_unreachable("Unexpected node to lower");
2593   }
2594 }
2595
2596 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
2597 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
2598   switch (Opcode) {
2599     OPCODE(RET_FLAG);
2600     OPCODE(CALL);
2601     OPCODE(SIBCALL);
2602     OPCODE(PCREL_WRAPPER);
2603     OPCODE(PCREL_OFFSET);
2604     OPCODE(IABS);
2605     OPCODE(ICMP);
2606     OPCODE(FCMP);
2607     OPCODE(TM);
2608     OPCODE(BR_CCMASK);
2609     OPCODE(SELECT_CCMASK);
2610     OPCODE(ADJDYNALLOC);
2611     OPCODE(EXTRACT_ACCESS);
2612     OPCODE(UMUL_LOHI64);
2613     OPCODE(SDIVREM64);
2614     OPCODE(UDIVREM32);
2615     OPCODE(UDIVREM64);
2616     OPCODE(MVC);
2617     OPCODE(MVC_LOOP);
2618     OPCODE(NC);
2619     OPCODE(NC_LOOP);
2620     OPCODE(OC);
2621     OPCODE(OC_LOOP);
2622     OPCODE(XC);
2623     OPCODE(XC_LOOP);
2624     OPCODE(CLC);
2625     OPCODE(CLC_LOOP);
2626     OPCODE(STRCMP);
2627     OPCODE(STPCPY);
2628     OPCODE(SEARCH_STRING);
2629     OPCODE(IPM);
2630     OPCODE(SERIALIZE);
2631     OPCODE(ATOMIC_SWAPW);
2632     OPCODE(ATOMIC_LOADW_ADD);
2633     OPCODE(ATOMIC_LOADW_SUB);
2634     OPCODE(ATOMIC_LOADW_AND);
2635     OPCODE(ATOMIC_LOADW_OR);
2636     OPCODE(ATOMIC_LOADW_XOR);
2637     OPCODE(ATOMIC_LOADW_NAND);
2638     OPCODE(ATOMIC_LOADW_MIN);
2639     OPCODE(ATOMIC_LOADW_MAX);
2640     OPCODE(ATOMIC_LOADW_UMIN);
2641     OPCODE(ATOMIC_LOADW_UMAX);
2642     OPCODE(ATOMIC_CMP_SWAPW);
2643     OPCODE(PREFETCH);
2644   }
2645   return nullptr;
2646 #undef OPCODE
2647 }
2648
2649 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
2650                                                  DAGCombinerInfo &DCI) const {
2651   SelectionDAG &DAG = DCI.DAG;
2652   unsigned Opcode = N->getOpcode();
2653   if (Opcode == ISD::SIGN_EXTEND) {
2654     // Convert (sext (ashr (shl X, C1), C2)) to
2655     // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
2656     // cheap as narrower ones.
2657     SDValue N0 = N->getOperand(0);
2658     EVT VT = N->getValueType(0);
2659     if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
2660       auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2661       SDValue Inner = N0.getOperand(0);
2662       if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
2663         if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
2664           unsigned Extra = (VT.getSizeInBits() -
2665                             N0.getValueType().getSizeInBits());
2666           unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
2667           unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
2668           EVT ShiftVT = N0.getOperand(1).getValueType();
2669           SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
2670                                     Inner.getOperand(0));
2671           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
2672                                     DAG.getConstant(NewShlAmt, ShiftVT));
2673           return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
2674                              DAG.getConstant(NewSraAmt, ShiftVT));
2675         }
2676       }
2677     }
2678   }
2679   return SDValue();
2680 }
2681
2682 //===----------------------------------------------------------------------===//
2683 // Custom insertion
2684 //===----------------------------------------------------------------------===//
2685
2686 // Create a new basic block after MBB.
2687 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
2688   MachineFunction &MF = *MBB->getParent();
2689   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
2690   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
2691   return NewMBB;
2692 }
2693
2694 // Split MBB after MI and return the new block (the one that contains
2695 // instructions after MI).
2696 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
2697                                           MachineBasicBlock *MBB) {
2698   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2699   NewMBB->splice(NewMBB->begin(), MBB,
2700                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
2701   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2702   return NewMBB;
2703 }
2704
2705 // Split MBB before MI and return the new block (the one that contains MI).
2706 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
2707                                            MachineBasicBlock *MBB) {
2708   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2709   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
2710   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2711   return NewMBB;
2712 }
2713
2714 // Force base value Base into a register before MI.  Return the register.
2715 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
2716                          const SystemZInstrInfo *TII) {
2717   if (Base.isReg())
2718     return Base.getReg();
2719
2720   MachineBasicBlock *MBB = MI->getParent();
2721   MachineFunction &MF = *MBB->getParent();
2722   MachineRegisterInfo &MRI = MF.getRegInfo();
2723
2724   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2725   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
2726     .addOperand(Base).addImm(0).addReg(0);
2727   return Reg;
2728 }
2729
2730 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
2731 MachineBasicBlock *
2732 SystemZTargetLowering::emitSelect(MachineInstr *MI,
2733                                   MachineBasicBlock *MBB) const {
2734   const SystemZInstrInfo *TII =
2735       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
2736
2737   unsigned DestReg  = MI->getOperand(0).getReg();
2738   unsigned TrueReg  = MI->getOperand(1).getReg();
2739   unsigned FalseReg = MI->getOperand(2).getReg();
2740   unsigned CCValid  = MI->getOperand(3).getImm();
2741   unsigned CCMask   = MI->getOperand(4).getImm();
2742   DebugLoc DL       = MI->getDebugLoc();
2743
2744   MachineBasicBlock *StartMBB = MBB;
2745   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2746   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2747
2748   //  StartMBB:
2749   //   BRC CCMask, JoinMBB
2750   //   # fallthrough to FalseMBB
2751   MBB = StartMBB;
2752   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2753     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2754   MBB->addSuccessor(JoinMBB);
2755   MBB->addSuccessor(FalseMBB);
2756
2757   //  FalseMBB:
2758   //   # fallthrough to JoinMBB
2759   MBB = FalseMBB;
2760   MBB->addSuccessor(JoinMBB);
2761
2762   //  JoinMBB:
2763   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
2764   //  ...
2765   MBB = JoinMBB;
2766   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
2767     .addReg(TrueReg).addMBB(StartMBB)
2768     .addReg(FalseReg).addMBB(FalseMBB);
2769
2770   MI->eraseFromParent();
2771   return JoinMBB;
2772 }
2773
2774 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
2775 // StoreOpcode is the store to use and Invert says whether the store should
2776 // happen when the condition is false rather than true.  If a STORE ON
2777 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
2778 MachineBasicBlock *
2779 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
2780                                      MachineBasicBlock *MBB,
2781                                      unsigned StoreOpcode, unsigned STOCOpcode,
2782                                      bool Invert) const {
2783   const SystemZInstrInfo *TII =
2784       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
2785
2786   unsigned SrcReg     = MI->getOperand(0).getReg();
2787   MachineOperand Base = MI->getOperand(1);
2788   int64_t Disp        = MI->getOperand(2).getImm();
2789   unsigned IndexReg   = MI->getOperand(3).getReg();
2790   unsigned CCValid    = MI->getOperand(4).getImm();
2791   unsigned CCMask     = MI->getOperand(5).getImm();
2792   DebugLoc DL         = MI->getDebugLoc();
2793
2794   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
2795
2796   // Use STOCOpcode if possible.  We could use different store patterns in
2797   // order to avoid matching the index register, but the performance trade-offs
2798   // might be more complicated in that case.
2799   if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
2800     if (Invert)
2801       CCMask ^= CCValid;
2802     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
2803       .addReg(SrcReg).addOperand(Base).addImm(Disp)
2804       .addImm(CCValid).addImm(CCMask);
2805     MI->eraseFromParent();
2806     return MBB;
2807   }
2808
2809   // Get the condition needed to branch around the store.
2810   if (!Invert)
2811     CCMask ^= CCValid;
2812
2813   MachineBasicBlock *StartMBB = MBB;
2814   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2815   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2816
2817   //  StartMBB:
2818   //   BRC CCMask, JoinMBB
2819   //   # fallthrough to FalseMBB
2820   MBB = StartMBB;
2821   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2822     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2823   MBB->addSuccessor(JoinMBB);
2824   MBB->addSuccessor(FalseMBB);
2825
2826   //  FalseMBB:
2827   //   store %SrcReg, %Disp(%Index,%Base)
2828   //   # fallthrough to JoinMBB
2829   MBB = FalseMBB;
2830   BuildMI(MBB, DL, TII->get(StoreOpcode))
2831     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
2832   MBB->addSuccessor(JoinMBB);
2833
2834   MI->eraseFromParent();
2835   return JoinMBB;
2836 }
2837
2838 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
2839 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
2840 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
2841 // BitSize is the width of the field in bits, or 0 if this is a partword
2842 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
2843 // is one of the operands.  Invert says whether the field should be
2844 // inverted after performing BinOpcode (e.g. for NAND).
2845 MachineBasicBlock *
2846 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
2847                                             MachineBasicBlock *MBB,
2848                                             unsigned BinOpcode,
2849                                             unsigned BitSize,
2850                                             bool Invert) const {
2851   MachineFunction &MF = *MBB->getParent();
2852   const SystemZInstrInfo *TII =
2853       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
2854   MachineRegisterInfo &MRI = MF.getRegInfo();
2855   bool IsSubWord = (BitSize < 32);
2856
2857   // Extract the operands.  Base can be a register or a frame index.
2858   // Src2 can be a register or immediate.
2859   unsigned Dest        = MI->getOperand(0).getReg();
2860   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2861   int64_t Disp         = MI->getOperand(2).getImm();
2862   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
2863   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2864   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2865   DebugLoc DL          = MI->getDebugLoc();
2866   if (IsSubWord)
2867     BitSize = MI->getOperand(6).getImm();
2868
2869   // Subword operations use 32-bit registers.
2870   const TargetRegisterClass *RC = (BitSize <= 32 ?
2871                                    &SystemZ::GR32BitRegClass :
2872                                    &SystemZ::GR64BitRegClass);
2873   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2874   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2875
2876   // Get the right opcodes for the displacement.
2877   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2878   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2879   assert(LOpcode && CSOpcode && "Displacement out of range");
2880
2881   // Create virtual registers for temporary results.
2882   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2883   unsigned OldVal        = MRI.createVirtualRegister(RC);
2884   unsigned NewVal        = (BinOpcode || IsSubWord ?
2885                             MRI.createVirtualRegister(RC) : Src2.getReg());
2886   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2887   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2888
2889   // Insert a basic block for the main loop.
2890   MachineBasicBlock *StartMBB = MBB;
2891   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2892   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2893
2894   //  StartMBB:
2895   //   ...
2896   //   %OrigVal = L Disp(%Base)
2897   //   # fall through to LoopMMB
2898   MBB = StartMBB;
2899   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2900     .addOperand(Base).addImm(Disp).addReg(0);
2901   MBB->addSuccessor(LoopMBB);
2902
2903   //  LoopMBB:
2904   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
2905   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2906   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
2907   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2908   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2909   //   JNE LoopMBB
2910   //   # fall through to DoneMMB
2911   MBB = LoopMBB;
2912   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2913     .addReg(OrigVal).addMBB(StartMBB)
2914     .addReg(Dest).addMBB(LoopMBB);
2915   if (IsSubWord)
2916     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2917       .addReg(OldVal).addReg(BitShift).addImm(0);
2918   if (Invert) {
2919     // Perform the operation normally and then invert every bit of the field.
2920     unsigned Tmp = MRI.createVirtualRegister(RC);
2921     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
2922       .addReg(RotatedOldVal).addOperand(Src2);
2923     if (BitSize <= 32)
2924       // XILF with the upper BitSize bits set.
2925       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
2926         .addReg(Tmp).addImm(-1U << (32 - BitSize));
2927     else {
2928       // Use LCGR and add -1 to the result, which is more compact than
2929       // an XILF, XILH pair.
2930       unsigned Tmp2 = MRI.createVirtualRegister(RC);
2931       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
2932       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
2933         .addReg(Tmp2).addImm(-1);
2934     }
2935   } else if (BinOpcode)
2936     // A simply binary operation.
2937     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
2938       .addReg(RotatedOldVal).addOperand(Src2);
2939   else if (IsSubWord)
2940     // Use RISBG to rotate Src2 into position and use it to replace the
2941     // field in RotatedOldVal.
2942     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
2943       .addReg(RotatedOldVal).addReg(Src2.getReg())
2944       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
2945   if (IsSubWord)
2946     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2947       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2948   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2949     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2950   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2951     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2952   MBB->addSuccessor(LoopMBB);
2953   MBB->addSuccessor(DoneMBB);
2954
2955   MI->eraseFromParent();
2956   return DoneMBB;
2957 }
2958
2959 // Implement EmitInstrWithCustomInserter for pseudo
2960 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
2961 // instruction that should be used to compare the current field with the
2962 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
2963 // for when the current field should be kept.  BitSize is the width of
2964 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
2965 MachineBasicBlock *
2966 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
2967                                             MachineBasicBlock *MBB,
2968                                             unsigned CompareOpcode,
2969                                             unsigned KeepOldMask,
2970                                             unsigned BitSize) const {
2971   MachineFunction &MF = *MBB->getParent();
2972   const SystemZInstrInfo *TII =
2973       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
2974   MachineRegisterInfo &MRI = MF.getRegInfo();
2975   bool IsSubWord = (BitSize < 32);
2976
2977   // Extract the operands.  Base can be a register or a frame index.
2978   unsigned Dest        = MI->getOperand(0).getReg();
2979   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2980   int64_t  Disp        = MI->getOperand(2).getImm();
2981   unsigned Src2        = MI->getOperand(3).getReg();
2982   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2983   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2984   DebugLoc DL          = MI->getDebugLoc();
2985   if (IsSubWord)
2986     BitSize = MI->getOperand(6).getImm();
2987
2988   // Subword operations use 32-bit registers.
2989   const TargetRegisterClass *RC = (BitSize <= 32 ?
2990                                    &SystemZ::GR32BitRegClass :
2991                                    &SystemZ::GR64BitRegClass);
2992   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2993   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2994
2995   // Get the right opcodes for the displacement.
2996   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2997   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2998   assert(LOpcode && CSOpcode && "Displacement out of range");
2999
3000   // Create virtual registers for temporary results.
3001   unsigned OrigVal       = MRI.createVirtualRegister(RC);
3002   unsigned OldVal        = MRI.createVirtualRegister(RC);
3003   unsigned NewVal        = MRI.createVirtualRegister(RC);
3004   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
3005   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
3006   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
3007
3008   // Insert 3 basic blocks for the loop.
3009   MachineBasicBlock *StartMBB  = MBB;
3010   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
3011   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
3012   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
3013   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
3014
3015   //  StartMBB:
3016   //   ...
3017   //   %OrigVal     = L Disp(%Base)
3018   //   # fall through to LoopMMB
3019   MBB = StartMBB;
3020   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
3021     .addOperand(Base).addImm(Disp).addReg(0);
3022   MBB->addSuccessor(LoopMBB);
3023
3024   //  LoopMBB:
3025   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
3026   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
3027   //   CompareOpcode %RotatedOldVal, %Src2
3028   //   BRC KeepOldMask, UpdateMBB
3029   MBB = LoopMBB;
3030   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
3031     .addReg(OrigVal).addMBB(StartMBB)
3032     .addReg(Dest).addMBB(UpdateMBB);
3033   if (IsSubWord)
3034     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
3035       .addReg(OldVal).addReg(BitShift).addImm(0);
3036   BuildMI(MBB, DL, TII->get(CompareOpcode))
3037     .addReg(RotatedOldVal).addReg(Src2);
3038   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3039     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
3040   MBB->addSuccessor(UpdateMBB);
3041   MBB->addSuccessor(UseAltMBB);
3042
3043   //  UseAltMBB:
3044   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
3045   //   # fall through to UpdateMMB
3046   MBB = UseAltMBB;
3047   if (IsSubWord)
3048     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
3049       .addReg(RotatedOldVal).addReg(Src2)
3050       .addImm(32).addImm(31 + BitSize).addImm(0);
3051   MBB->addSuccessor(UpdateMBB);
3052
3053   //  UpdateMBB:
3054   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
3055   //                        [ %RotatedAltVal, UseAltMBB ]
3056   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
3057   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
3058   //   JNE LoopMBB
3059   //   # fall through to DoneMMB
3060   MBB = UpdateMBB;
3061   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
3062     .addReg(RotatedOldVal).addMBB(LoopMBB)
3063     .addReg(RotatedAltVal).addMBB(UseAltMBB);
3064   if (IsSubWord)
3065     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
3066       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
3067   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
3068     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
3069   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3070     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
3071   MBB->addSuccessor(LoopMBB);
3072   MBB->addSuccessor(DoneMBB);
3073
3074   MI->eraseFromParent();
3075   return DoneMBB;
3076 }
3077
3078 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
3079 // instruction MI.
3080 MachineBasicBlock *
3081 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
3082                                           MachineBasicBlock *MBB) const {
3083   MachineFunction &MF = *MBB->getParent();
3084   const SystemZInstrInfo *TII =
3085       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3086   MachineRegisterInfo &MRI = MF.getRegInfo();
3087
3088   // Extract the operands.  Base can be a register or a frame index.
3089   unsigned Dest        = MI->getOperand(0).getReg();
3090   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
3091   int64_t  Disp        = MI->getOperand(2).getImm();
3092   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
3093   unsigned OrigSwapVal = MI->getOperand(4).getReg();
3094   unsigned BitShift    = MI->getOperand(5).getReg();
3095   unsigned NegBitShift = MI->getOperand(6).getReg();
3096   int64_t  BitSize     = MI->getOperand(7).getImm();
3097   DebugLoc DL          = MI->getDebugLoc();
3098
3099   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
3100
3101   // Get the right opcodes for the displacement.
3102   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
3103   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
3104   assert(LOpcode && CSOpcode && "Displacement out of range");
3105
3106   // Create virtual registers for temporary results.
3107   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
3108   unsigned OldVal       = MRI.createVirtualRegister(RC);
3109   unsigned CmpVal       = MRI.createVirtualRegister(RC);
3110   unsigned SwapVal      = MRI.createVirtualRegister(RC);
3111   unsigned StoreVal     = MRI.createVirtualRegister(RC);
3112   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
3113   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
3114   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
3115
3116   // Insert 2 basic blocks for the loop.
3117   MachineBasicBlock *StartMBB = MBB;
3118   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
3119   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
3120   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
3121
3122   //  StartMBB:
3123   //   ...
3124   //   %OrigOldVal     = L Disp(%Base)
3125   //   # fall through to LoopMMB
3126   MBB = StartMBB;
3127   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
3128     .addOperand(Base).addImm(Disp).addReg(0);
3129   MBB->addSuccessor(LoopMBB);
3130
3131   //  LoopMBB:
3132   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
3133   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
3134   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
3135   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
3136   //                      ^^ The low BitSize bits contain the field
3137   //                         of interest.
3138   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
3139   //                      ^^ Replace the upper 32-BitSize bits of the
3140   //                         comparison value with those that we loaded,
3141   //                         so that we can use a full word comparison.
3142   //   CR %Dest, %RetryCmpVal
3143   //   JNE DoneMBB
3144   //   # Fall through to SetMBB
3145   MBB = LoopMBB;
3146   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
3147     .addReg(OrigOldVal).addMBB(StartMBB)
3148     .addReg(RetryOldVal).addMBB(SetMBB);
3149   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
3150     .addReg(OrigCmpVal).addMBB(StartMBB)
3151     .addReg(RetryCmpVal).addMBB(SetMBB);
3152   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
3153     .addReg(OrigSwapVal).addMBB(StartMBB)
3154     .addReg(RetrySwapVal).addMBB(SetMBB);
3155   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
3156     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
3157   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
3158     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
3159   BuildMI(MBB, DL, TII->get(SystemZ::CR))
3160     .addReg(Dest).addReg(RetryCmpVal);
3161   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3162     .addImm(SystemZ::CCMASK_ICMP)
3163     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
3164   MBB->addSuccessor(DoneMBB);
3165   MBB->addSuccessor(SetMBB);
3166
3167   //  SetMBB:
3168   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
3169   //                      ^^ Replace the upper 32-BitSize bits of the new
3170   //                         value with those that we loaded.
3171   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
3172   //                      ^^ Rotate the new field to its proper position.
3173   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
3174   //   JNE LoopMBB
3175   //   # fall through to ExitMMB
3176   MBB = SetMBB;
3177   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
3178     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
3179   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
3180     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
3181   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
3182     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
3183   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3184     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
3185   MBB->addSuccessor(LoopMBB);
3186   MBB->addSuccessor(DoneMBB);
3187
3188   MI->eraseFromParent();
3189   return DoneMBB;
3190 }
3191
3192 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
3193 // if the high register of the GR128 value must be cleared or false if
3194 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
3195 // and subreg_l64 when extending a GR64.
3196 MachineBasicBlock *
3197 SystemZTargetLowering::emitExt128(MachineInstr *MI,
3198                                   MachineBasicBlock *MBB,
3199                                   bool ClearEven, unsigned SubReg) const {
3200   MachineFunction &MF = *MBB->getParent();
3201   const SystemZInstrInfo *TII =
3202       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3203   MachineRegisterInfo &MRI = MF.getRegInfo();
3204   DebugLoc DL = MI->getDebugLoc();
3205
3206   unsigned Dest  = MI->getOperand(0).getReg();
3207   unsigned Src   = MI->getOperand(1).getReg();
3208   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
3209
3210   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
3211   if (ClearEven) {
3212     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
3213     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
3214
3215     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
3216       .addImm(0);
3217     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
3218       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
3219     In128 = NewIn128;
3220   }
3221   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
3222     .addReg(In128).addReg(Src).addImm(SubReg);
3223
3224   MI->eraseFromParent();
3225   return MBB;
3226 }
3227
3228 MachineBasicBlock *
3229 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
3230                                          MachineBasicBlock *MBB,
3231                                          unsigned Opcode) const {
3232   MachineFunction &MF = *MBB->getParent();
3233   const SystemZInstrInfo *TII =
3234       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3235   MachineRegisterInfo &MRI = MF.getRegInfo();
3236   DebugLoc DL = MI->getDebugLoc();
3237
3238   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
3239   uint64_t       DestDisp = MI->getOperand(1).getImm();
3240   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
3241   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
3242   uint64_t       Length   = MI->getOperand(4).getImm();
3243
3244   // When generating more than one CLC, all but the last will need to
3245   // branch to the end when a difference is found.
3246   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
3247                                splitBlockAfter(MI, MBB) : nullptr);
3248
3249   // Check for the loop form, in which operand 5 is the trip count.
3250   if (MI->getNumExplicitOperands() > 5) {
3251     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
3252
3253     uint64_t StartCountReg = MI->getOperand(5).getReg();
3254     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
3255     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
3256                               forceReg(MI, DestBase, TII));
3257
3258     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
3259     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
3260     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
3261                             MRI.createVirtualRegister(RC));
3262     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
3263     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
3264                             MRI.createVirtualRegister(RC));
3265
3266     RC = &SystemZ::GR64BitRegClass;
3267     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
3268     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
3269
3270     MachineBasicBlock *StartMBB = MBB;
3271     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
3272     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
3273     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
3274
3275     //  StartMBB:
3276     //   # fall through to LoopMMB
3277     MBB->addSuccessor(LoopMBB);
3278
3279     //  LoopMBB:
3280     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
3281     //                      [ %NextDestReg, NextMBB ]
3282     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
3283     //                     [ %NextSrcReg, NextMBB ]
3284     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
3285     //                       [ %NextCountReg, NextMBB ]
3286     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
3287     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
3288     //   ( JLH EndMBB )
3289     //
3290     // The prefetch is used only for MVC.  The JLH is used only for CLC.
3291     MBB = LoopMBB;
3292
3293     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
3294       .addReg(StartDestReg).addMBB(StartMBB)
3295       .addReg(NextDestReg).addMBB(NextMBB);
3296     if (!HaveSingleBase)
3297       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
3298         .addReg(StartSrcReg).addMBB(StartMBB)
3299         .addReg(NextSrcReg).addMBB(NextMBB);
3300     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
3301       .addReg(StartCountReg).addMBB(StartMBB)
3302       .addReg(NextCountReg).addMBB(NextMBB);
3303     if (Opcode == SystemZ::MVC)
3304       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
3305         .addImm(SystemZ::PFD_WRITE)
3306         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
3307     BuildMI(MBB, DL, TII->get(Opcode))
3308       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
3309       .addReg(ThisSrcReg).addImm(SrcDisp);
3310     if (EndMBB) {
3311       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3312         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
3313         .addMBB(EndMBB);
3314       MBB->addSuccessor(EndMBB);
3315       MBB->addSuccessor(NextMBB);
3316     }
3317
3318     // NextMBB:
3319     //   %NextDestReg = LA 256(%ThisDestReg)
3320     //   %NextSrcReg = LA 256(%ThisSrcReg)
3321     //   %NextCountReg = AGHI %ThisCountReg, -1
3322     //   CGHI %NextCountReg, 0
3323     //   JLH LoopMBB
3324     //   # fall through to DoneMMB
3325     //
3326     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
3327     MBB = NextMBB;
3328
3329     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
3330       .addReg(ThisDestReg).addImm(256).addReg(0);
3331     if (!HaveSingleBase)
3332       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
3333         .addReg(ThisSrcReg).addImm(256).addReg(0);
3334     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
3335       .addReg(ThisCountReg).addImm(-1);
3336     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
3337       .addReg(NextCountReg).addImm(0);
3338     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3339       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
3340       .addMBB(LoopMBB);
3341     MBB->addSuccessor(LoopMBB);
3342     MBB->addSuccessor(DoneMBB);
3343
3344     DestBase = MachineOperand::CreateReg(NextDestReg, false);
3345     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
3346     Length &= 255;
3347     MBB = DoneMBB;
3348   }
3349   // Handle any remaining bytes with straight-line code.
3350   while (Length > 0) {
3351     uint64_t ThisLength = std::min(Length, uint64_t(256));
3352     // The previous iteration might have created out-of-range displacements.
3353     // Apply them using LAY if so.
3354     if (!isUInt<12>(DestDisp)) {
3355       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
3356       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
3357         .addOperand(DestBase).addImm(DestDisp).addReg(0);
3358       DestBase = MachineOperand::CreateReg(Reg, false);
3359       DestDisp = 0;
3360     }
3361     if (!isUInt<12>(SrcDisp)) {
3362       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
3363       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
3364         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
3365       SrcBase = MachineOperand::CreateReg(Reg, false);
3366       SrcDisp = 0;
3367     }
3368     BuildMI(*MBB, MI, DL, TII->get(Opcode))
3369       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
3370       .addOperand(SrcBase).addImm(SrcDisp);
3371     DestDisp += ThisLength;
3372     SrcDisp += ThisLength;
3373     Length -= ThisLength;
3374     // If there's another CLC to go, branch to the end if a difference
3375     // was found.
3376     if (EndMBB && Length > 0) {
3377       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
3378       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3379         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
3380         .addMBB(EndMBB);
3381       MBB->addSuccessor(EndMBB);
3382       MBB->addSuccessor(NextMBB);
3383       MBB = NextMBB;
3384     }
3385   }
3386   if (EndMBB) {
3387     MBB->addSuccessor(EndMBB);
3388     MBB = EndMBB;
3389     MBB->addLiveIn(SystemZ::CC);
3390   }
3391
3392   MI->eraseFromParent();
3393   return MBB;
3394 }
3395
3396 // Decompose string pseudo-instruction MI into a loop that continually performs
3397 // Opcode until CC != 3.
3398 MachineBasicBlock *
3399 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
3400                                          MachineBasicBlock *MBB,
3401                                          unsigned Opcode) const {
3402   MachineFunction &MF = *MBB->getParent();
3403   const SystemZInstrInfo *TII =
3404       static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
3405   MachineRegisterInfo &MRI = MF.getRegInfo();
3406   DebugLoc DL = MI->getDebugLoc();
3407
3408   uint64_t End1Reg   = MI->getOperand(0).getReg();
3409   uint64_t Start1Reg = MI->getOperand(1).getReg();
3410   uint64_t Start2Reg = MI->getOperand(2).getReg();
3411   uint64_t CharReg   = MI->getOperand(3).getReg();
3412
3413   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
3414   uint64_t This1Reg = MRI.createVirtualRegister(RC);
3415   uint64_t This2Reg = MRI.createVirtualRegister(RC);
3416   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
3417
3418   MachineBasicBlock *StartMBB = MBB;
3419   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
3420   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
3421
3422   //  StartMBB:
3423   //   # fall through to LoopMMB
3424   MBB->addSuccessor(LoopMBB);
3425
3426   //  LoopMBB:
3427   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
3428   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
3429   //   R0L = %CharReg
3430   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
3431   //   JO LoopMBB
3432   //   # fall through to DoneMMB
3433   //
3434   // The load of R0L can be hoisted by post-RA LICM.
3435   MBB = LoopMBB;
3436
3437   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
3438     .addReg(Start1Reg).addMBB(StartMBB)
3439     .addReg(End1Reg).addMBB(LoopMBB);
3440   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
3441     .addReg(Start2Reg).addMBB(StartMBB)
3442     .addReg(End2Reg).addMBB(LoopMBB);
3443   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
3444   BuildMI(MBB, DL, TII->get(Opcode))
3445     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
3446     .addReg(This1Reg).addReg(This2Reg);
3447   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
3448     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
3449   MBB->addSuccessor(LoopMBB);
3450   MBB->addSuccessor(DoneMBB);
3451
3452   DoneMBB->addLiveIn(SystemZ::CC);
3453
3454   MI->eraseFromParent();
3455   return DoneMBB;
3456 }
3457
3458 MachineBasicBlock *SystemZTargetLowering::
3459 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
3460   switch (MI->getOpcode()) {
3461   case SystemZ::Select32Mux:
3462   case SystemZ::Select32:
3463   case SystemZ::SelectF32:
3464   case SystemZ::Select64:
3465   case SystemZ::SelectF64:
3466   case SystemZ::SelectF128:
3467     return emitSelect(MI, MBB);
3468
3469   case SystemZ::CondStore8Mux:
3470     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
3471   case SystemZ::CondStore8MuxInv:
3472     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
3473   case SystemZ::CondStore16Mux:
3474     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
3475   case SystemZ::CondStore16MuxInv:
3476     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
3477   case SystemZ::CondStore8:
3478     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
3479   case SystemZ::CondStore8Inv:
3480     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
3481   case SystemZ::CondStore16:
3482     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
3483   case SystemZ::CondStore16Inv:
3484     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
3485   case SystemZ::CondStore32:
3486     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
3487   case SystemZ::CondStore32Inv:
3488     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
3489   case SystemZ::CondStore64:
3490     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
3491   case SystemZ::CondStore64Inv:
3492     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
3493   case SystemZ::CondStoreF32:
3494     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
3495   case SystemZ::CondStoreF32Inv:
3496     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
3497   case SystemZ::CondStoreF64:
3498     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
3499   case SystemZ::CondStoreF64Inv:
3500     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
3501
3502   case SystemZ::AEXT128_64:
3503     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
3504   case SystemZ::ZEXT128_32:
3505     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
3506   case SystemZ::ZEXT128_64:
3507     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
3508
3509   case SystemZ::ATOMIC_SWAPW:
3510     return emitAtomicLoadBinary(MI, MBB, 0, 0);
3511   case SystemZ::ATOMIC_SWAP_32:
3512     return emitAtomicLoadBinary(MI, MBB, 0, 32);
3513   case SystemZ::ATOMIC_SWAP_64:
3514     return emitAtomicLoadBinary(MI, MBB, 0, 64);
3515
3516   case SystemZ::ATOMIC_LOADW_AR:
3517     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
3518   case SystemZ::ATOMIC_LOADW_AFI:
3519     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
3520   case SystemZ::ATOMIC_LOAD_AR:
3521     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
3522   case SystemZ::ATOMIC_LOAD_AHI:
3523     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
3524   case SystemZ::ATOMIC_LOAD_AFI:
3525     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
3526   case SystemZ::ATOMIC_LOAD_AGR:
3527     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
3528   case SystemZ::ATOMIC_LOAD_AGHI:
3529     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
3530   case SystemZ::ATOMIC_LOAD_AGFI:
3531     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
3532
3533   case SystemZ::ATOMIC_LOADW_SR:
3534     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
3535   case SystemZ::ATOMIC_LOAD_SR:
3536     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
3537   case SystemZ::ATOMIC_LOAD_SGR:
3538     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
3539
3540   case SystemZ::ATOMIC_LOADW_NR:
3541     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
3542   case SystemZ::ATOMIC_LOADW_NILH:
3543     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
3544   case SystemZ::ATOMIC_LOAD_NR:
3545     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
3546   case SystemZ::ATOMIC_LOAD_NILL:
3547     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
3548   case SystemZ::ATOMIC_LOAD_NILH:
3549     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
3550   case SystemZ::ATOMIC_LOAD_NILF:
3551     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
3552   case SystemZ::ATOMIC_LOAD_NGR:
3553     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
3554   case SystemZ::ATOMIC_LOAD_NILL64:
3555     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
3556   case SystemZ::ATOMIC_LOAD_NILH64:
3557     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
3558   case SystemZ::ATOMIC_LOAD_NIHL64:
3559     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
3560   case SystemZ::ATOMIC_LOAD_NIHH64:
3561     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
3562   case SystemZ::ATOMIC_LOAD_NILF64:
3563     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
3564   case SystemZ::ATOMIC_LOAD_NIHF64:
3565     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
3566
3567   case SystemZ::ATOMIC_LOADW_OR:
3568     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
3569   case SystemZ::ATOMIC_LOADW_OILH:
3570     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
3571   case SystemZ::ATOMIC_LOAD_OR:
3572     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
3573   case SystemZ::ATOMIC_LOAD_OILL:
3574     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
3575   case SystemZ::ATOMIC_LOAD_OILH:
3576     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
3577   case SystemZ::ATOMIC_LOAD_OILF:
3578     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
3579   case SystemZ::ATOMIC_LOAD_OGR:
3580     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
3581   case SystemZ::ATOMIC_LOAD_OILL64:
3582     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
3583   case SystemZ::ATOMIC_LOAD_OILH64:
3584     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
3585   case SystemZ::ATOMIC_LOAD_OIHL64:
3586     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
3587   case SystemZ::ATOMIC_LOAD_OIHH64:
3588     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
3589   case SystemZ::ATOMIC_LOAD_OILF64:
3590     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
3591   case SystemZ::ATOMIC_LOAD_OIHF64:
3592     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
3593
3594   case SystemZ::ATOMIC_LOADW_XR:
3595     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
3596   case SystemZ::ATOMIC_LOADW_XILF:
3597     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
3598   case SystemZ::ATOMIC_LOAD_XR:
3599     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
3600   case SystemZ::ATOMIC_LOAD_XILF:
3601     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
3602   case SystemZ::ATOMIC_LOAD_XGR:
3603     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
3604   case SystemZ::ATOMIC_LOAD_XILF64:
3605     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
3606   case SystemZ::ATOMIC_LOAD_XIHF64:
3607     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
3608
3609   case SystemZ::ATOMIC_LOADW_NRi:
3610     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
3611   case SystemZ::ATOMIC_LOADW_NILHi:
3612     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
3613   case SystemZ::ATOMIC_LOAD_NRi:
3614     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
3615   case SystemZ::ATOMIC_LOAD_NILLi:
3616     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
3617   case SystemZ::ATOMIC_LOAD_NILHi:
3618     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
3619   case SystemZ::ATOMIC_LOAD_NILFi:
3620     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
3621   case SystemZ::ATOMIC_LOAD_NGRi:
3622     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
3623   case SystemZ::ATOMIC_LOAD_NILL64i:
3624     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
3625   case SystemZ::ATOMIC_LOAD_NILH64i:
3626     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
3627   case SystemZ::ATOMIC_LOAD_NIHL64i:
3628     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
3629   case SystemZ::ATOMIC_LOAD_NIHH64i:
3630     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
3631   case SystemZ::ATOMIC_LOAD_NILF64i:
3632     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
3633   case SystemZ::ATOMIC_LOAD_NIHF64i:
3634     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
3635
3636   case SystemZ::ATOMIC_LOADW_MIN:
3637     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3638                                 SystemZ::CCMASK_CMP_LE, 0);
3639   case SystemZ::ATOMIC_LOAD_MIN_32:
3640     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3641                                 SystemZ::CCMASK_CMP_LE, 32);
3642   case SystemZ::ATOMIC_LOAD_MIN_64:
3643     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3644                                 SystemZ::CCMASK_CMP_LE, 64);
3645
3646   case SystemZ::ATOMIC_LOADW_MAX:
3647     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3648                                 SystemZ::CCMASK_CMP_GE, 0);
3649   case SystemZ::ATOMIC_LOAD_MAX_32:
3650     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3651                                 SystemZ::CCMASK_CMP_GE, 32);
3652   case SystemZ::ATOMIC_LOAD_MAX_64:
3653     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3654                                 SystemZ::CCMASK_CMP_GE, 64);
3655
3656   case SystemZ::ATOMIC_LOADW_UMIN:
3657     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3658                                 SystemZ::CCMASK_CMP_LE, 0);
3659   case SystemZ::ATOMIC_LOAD_UMIN_32:
3660     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3661                                 SystemZ::CCMASK_CMP_LE, 32);
3662   case SystemZ::ATOMIC_LOAD_UMIN_64:
3663     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3664                                 SystemZ::CCMASK_CMP_LE, 64);
3665
3666   case SystemZ::ATOMIC_LOADW_UMAX:
3667     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3668                                 SystemZ::CCMASK_CMP_GE, 0);
3669   case SystemZ::ATOMIC_LOAD_UMAX_32:
3670     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3671                                 SystemZ::CCMASK_CMP_GE, 32);
3672   case SystemZ::ATOMIC_LOAD_UMAX_64:
3673     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3674                                 SystemZ::CCMASK_CMP_GE, 64);
3675
3676   case SystemZ::ATOMIC_CMP_SWAPW:
3677     return emitAtomicCmpSwapW(MI, MBB);
3678   case SystemZ::MVCSequence:
3679   case SystemZ::MVCLoop:
3680     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
3681   case SystemZ::NCSequence:
3682   case SystemZ::NCLoop:
3683     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
3684   case SystemZ::OCSequence:
3685   case SystemZ::OCLoop:
3686     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
3687   case SystemZ::XCSequence:
3688   case SystemZ::XCLoop:
3689     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
3690   case SystemZ::CLCSequence:
3691   case SystemZ::CLCLoop:
3692     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
3693   case SystemZ::CLSTLoop:
3694     return emitStringWrapper(MI, MBB, SystemZ::CLST);
3695   case SystemZ::MVSTLoop:
3696     return emitStringWrapper(MI, MBB, SystemZ::MVST);
3697   case SystemZ::SRSTLoop:
3698     return emitStringWrapper(MI, MBB, SystemZ::SRST);
3699   default:
3700     llvm_unreachable("Unexpected instr type to insert");
3701   }
3702 }