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