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