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