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