[SystemZ] Use FI[EDX]BRA for codegen
[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 #define DEBUG_TYPE "systemz-lower"
15
16 #include "SystemZISelLowering.h"
17 #include "SystemZCallingConv.h"
18 #include "SystemZConstantPoolValue.h"
19 #include "SystemZMachineFunctionInfo.h"
20 #include "SystemZTargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25
26 using namespace llvm;
27
28 // Classify VT as either 32 or 64 bit.
29 static bool is32Bit(EVT VT) {
30   switch (VT.getSimpleVT().SimpleTy) {
31   case MVT::i32:
32     return true;
33   case MVT::i64:
34     return false;
35   default:
36     llvm_unreachable("Unsupported type");
37   }
38 }
39
40 // Return a version of MachineOperand that can be safely used before the
41 // final use.
42 static MachineOperand earlyUseOperand(MachineOperand Op) {
43   if (Op.isReg())
44     Op.setIsKill(false);
45   return Op;
46 }
47
48 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm)
49   : TargetLowering(tm, new TargetLoweringObjectFileELF()),
50     Subtarget(*tm.getSubtargetImpl()), TM(tm) {
51   MVT PtrVT = getPointerTy();
52
53   // Set up the register classes.
54   addRegisterClass(MVT::i32,  &SystemZ::GR32BitRegClass);
55   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
56   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
57   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
58   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
59
60   // Compute derived properties from the register classes
61   computeRegisterProperties();
62
63   // Set up special registers.
64   setExceptionPointerRegister(SystemZ::R6D);
65   setExceptionSelectorRegister(SystemZ::R7D);
66   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
67
68   // TODO: It may be better to default to latency-oriented scheduling, however
69   // LLVM's current latency-oriented scheduler can't handle physreg definitions
70   // such as SystemZ has with CC, so set this to the register-pressure
71   // scheduler, because it can.
72   setSchedulingPreference(Sched::RegPressure);
73
74   setBooleanContents(ZeroOrOneBooleanContent);
75   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
76
77   // Instructions are strings of 2-byte aligned 2-byte values.
78   setMinFunctionAlignment(2);
79
80   // Handle operations that are handled in a similar way for all types.
81   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
82        I <= MVT::LAST_FP_VALUETYPE;
83        ++I) {
84     MVT VT = MVT::SimpleValueType(I);
85     if (isTypeLegal(VT)) {
86       // Expand SETCC(X, Y, COND) into SELECT_CC(X, Y, 1, 0, COND).
87       setOperationAction(ISD::SETCC, VT, Expand);
88
89       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
90       setOperationAction(ISD::SELECT, VT, Expand);
91
92       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
93       setOperationAction(ISD::SELECT_CC, VT, Custom);
94       setOperationAction(ISD::BR_CC,     VT, Custom);
95     }
96   }
97
98   // Expand jump table branches as address arithmetic followed by an
99   // indirect jump.
100   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
101
102   // Expand BRCOND into a BR_CC (see above).
103   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
104
105   // Handle integer types.
106   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
107        I <= MVT::LAST_INTEGER_VALUETYPE;
108        ++I) {
109     MVT VT = MVT::SimpleValueType(I);
110     if (isTypeLegal(VT)) {
111       // Expand individual DIV and REMs into DIVREMs.
112       setOperationAction(ISD::SDIV, VT, Expand);
113       setOperationAction(ISD::UDIV, VT, Expand);
114       setOperationAction(ISD::SREM, VT, Expand);
115       setOperationAction(ISD::UREM, VT, Expand);
116       setOperationAction(ISD::SDIVREM, VT, Custom);
117       setOperationAction(ISD::UDIVREM, VT, Custom);
118
119       // Expand ATOMIC_LOAD and ATOMIC_STORE using ATOMIC_CMP_SWAP.
120       // FIXME: probably much too conservative.
121       setOperationAction(ISD::ATOMIC_LOAD,  VT, Expand);
122       setOperationAction(ISD::ATOMIC_STORE, VT, Expand);
123
124       // No special instructions for these.
125       setOperationAction(ISD::CTPOP,           VT, Expand);
126       setOperationAction(ISD::CTTZ,            VT, Expand);
127       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
128       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
129       setOperationAction(ISD::ROTR,            VT, Expand);
130
131       // Use *MUL_LOHI where possible and a wider multiplication otherwise.
132       setOperationAction(ISD::MULHS, VT, Expand);
133       setOperationAction(ISD::MULHU, VT, Expand);
134
135       // We have instructions for signed but not unsigned FP conversion.
136       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
137     }
138   }
139
140   // Type legalization will convert 8- and 16-bit atomic operations into
141   // forms that operate on i32s (but still keeping the original memory VT).
142   // Lower them into full i32 operations.
143   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
144   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
145   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
146   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
147   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
148   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
149   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
150   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
151   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
152   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
153   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
154   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
155
156   // We have instructions for signed but not unsigned FP conversion.
157   // Handle unsigned 32-bit types as signed 64-bit types.
158   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
159   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
160
161   // We have native support for a 64-bit CTLZ, via FLOGR.
162   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
163   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
164
165   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
166   setOperationAction(ISD::OR, MVT::i64, Custom);
167
168   // The architecture has 32-bit SMUL_LOHI and UMUL_LOHI (MR and MLR),
169   // but they aren't really worth using.  There is no 64-bit SMUL_LOHI,
170   // but there is a 64-bit UMUL_LOHI: MLGR.
171   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
172   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
173   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
174   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Custom);
175
176   // FIXME: Can we support these natively?
177   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
178   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
179   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
180
181   // We have native instructions for i8, i16 and i32 extensions, but not i1.
182   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
183   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
184   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
185   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
186
187   // Handle the various types of symbolic address.
188   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
189   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
190   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
191   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
192   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
193
194   // We need to handle dynamic allocations specially because of the
195   // 160-byte area at the bottom of the stack.
196   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
197
198   // Use custom expanders so that we can force the function to use
199   // a frame pointer.
200   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
201   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
202
203   // Handle floating-point types.
204   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
205        I <= MVT::LAST_FP_VALUETYPE;
206        ++I) {
207     MVT VT = MVT::SimpleValueType(I);
208     if (isTypeLegal(VT)) {
209       // We can use FI for FRINT.
210       setOperationAction(ISD::FRINT, VT, Legal);
211
212       // We can use the extended form of FI for other rounding operations.
213       if (Subtarget.hasFPExtension()) {
214         setOperationAction(ISD::FNEARBYINT, VT, Legal);
215         setOperationAction(ISD::FFLOOR, VT, Legal);
216         setOperationAction(ISD::FCEIL, VT, Legal);
217         setOperationAction(ISD::FTRUNC, VT, Legal);
218         setOperationAction(ISD::FROUND, VT, Legal);
219       }
220
221       // No special instructions for these.
222       setOperationAction(ISD::FSIN, VT, Expand);
223       setOperationAction(ISD::FCOS, VT, Expand);
224       setOperationAction(ISD::FREM, VT, Expand);
225     }
226   }
227
228   // We have fused multiply-addition for f32 and f64 but not f128.
229   setOperationAction(ISD::FMA, MVT::f32,  Legal);
230   setOperationAction(ISD::FMA, MVT::f64,  Legal);
231   setOperationAction(ISD::FMA, MVT::f128, Expand);
232
233   // Needed so that we don't try to implement f128 constant loads using
234   // a load-and-extend of a f80 constant (in cases where the constant
235   // would fit in an f80).
236   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
237
238   // Floating-point truncation and stores need to be done separately.
239   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
240   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
241   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
242
243   // We have 64-bit FPR<->GPR moves, but need special handling for
244   // 32-bit forms.
245   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
246   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
247
248   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
249   // structure, but VAEND is a no-op.
250   setOperationAction(ISD::VASTART, MVT::Other, Custom);
251   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
252   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
253
254   // We want to use MVC in preference to even a single load/store pair.
255   MaxStoresPerMemcpy = 0;
256   MaxStoresPerMemcpyOptSize = 0;
257
258   // The main memset sequence is a byte store followed by an MVC.
259   // Two STC or MV..I stores win over that, but the kind of fused stores
260   // generated by target-independent code don't when the byte value is
261   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
262   // than "STC;MVC".  Handle the choice in target-specific code instead.
263   MaxStoresPerMemset = 0;
264   MaxStoresPerMemsetOptSize = 0;
265 }
266
267 bool
268 SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
269   VT = VT.getScalarType();
270
271   if (!VT.isSimple())
272     return false;
273
274   switch (VT.getSimpleVT().SimpleTy) {
275   case MVT::f32:
276   case MVT::f64:
277     return true;
278   case MVT::f128:
279     return false;
280   default:
281     break;
282   }
283
284   return false;
285 }
286
287 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
288   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
289   return Imm.isZero() || Imm.isNegZero();
290 }
291
292 bool SystemZTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
293                                                           bool *Fast) const {
294   // Unaligned accesses should never be slower than the expanded version.
295   // We check specifically for aligned accesses in the few cases where
296   // they are required.
297   if (Fast)
298     *Fast = true;
299   return true;
300 }
301   
302 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
303                                                   Type *Ty) const {
304   // Punt on globals for now, although they can be used in limited
305   // RELATIVE LONG cases.
306   if (AM.BaseGV)
307     return false;
308
309   // Require a 20-bit signed offset.
310   if (!isInt<20>(AM.BaseOffs))
311     return false;
312
313   // Indexing is OK but no scale factor can be applied.
314   return AM.Scale == 0 || AM.Scale == 1;
315 }
316
317 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
318   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
319     return false;
320   unsigned FromBits = FromType->getPrimitiveSizeInBits();
321   unsigned ToBits = ToType->getPrimitiveSizeInBits();
322   return FromBits > ToBits;
323 }
324
325 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
326   if (!FromVT.isInteger() || !ToVT.isInteger())
327     return false;
328   unsigned FromBits = FromVT.getSizeInBits();
329   unsigned ToBits = ToVT.getSizeInBits();
330   return FromBits > ToBits;
331 }
332
333 //===----------------------------------------------------------------------===//
334 // Inline asm support
335 //===----------------------------------------------------------------------===//
336
337 TargetLowering::ConstraintType
338 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
339   if (Constraint.size() == 1) {
340     switch (Constraint[0]) {
341     case 'a': // Address register
342     case 'd': // Data register (equivalent to 'r')
343     case 'f': // Floating-point register
344     case 'r': // General-purpose register
345       return C_RegisterClass;
346
347     case 'Q': // Memory with base and unsigned 12-bit displacement
348     case 'R': // Likewise, plus an index
349     case 'S': // Memory with base and signed 20-bit displacement
350     case 'T': // Likewise, plus an index
351     case 'm': // Equivalent to 'T'.
352       return C_Memory;
353
354     case 'I': // Unsigned 8-bit constant
355     case 'J': // Unsigned 12-bit constant
356     case 'K': // Signed 16-bit constant
357     case 'L': // Signed 20-bit displacement (on all targets we support)
358     case 'M': // 0x7fffffff
359       return C_Other;
360
361     default:
362       break;
363     }
364   }
365   return TargetLowering::getConstraintType(Constraint);
366 }
367
368 TargetLowering::ConstraintWeight SystemZTargetLowering::
369 getSingleConstraintMatchWeight(AsmOperandInfo &info,
370                                const char *constraint) const {
371   ConstraintWeight weight = CW_Invalid;
372   Value *CallOperandVal = info.CallOperandVal;
373   // If we don't have a value, we can't do a match,
374   // but allow it at the lowest weight.
375   if (CallOperandVal == NULL)
376     return CW_Default;
377   Type *type = CallOperandVal->getType();
378   // Look at the constraint type.
379   switch (*constraint) {
380   default:
381     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
382     break;
383
384   case 'a': // Address register
385   case 'd': // Data register (equivalent to 'r')
386   case 'r': // General-purpose register
387     if (CallOperandVal->getType()->isIntegerTy())
388       weight = CW_Register;
389     break;
390
391   case 'f': // Floating-point register
392     if (type->isFloatingPointTy())
393       weight = CW_Register;
394     break;
395
396   case 'I': // Unsigned 8-bit constant
397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
398       if (isUInt<8>(C->getZExtValue()))
399         weight = CW_Constant;
400     break;
401
402   case 'J': // Unsigned 12-bit constant
403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
404       if (isUInt<12>(C->getZExtValue()))
405         weight = CW_Constant;
406     break;
407
408   case 'K': // Signed 16-bit constant
409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
410       if (isInt<16>(C->getSExtValue()))
411         weight = CW_Constant;
412     break;
413
414   case 'L': // Signed 20-bit displacement (on all targets we support)
415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
416       if (isInt<20>(C->getSExtValue()))
417         weight = CW_Constant;
418     break;
419
420   case 'M': // 0x7fffffff
421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
422       if (C->getZExtValue() == 0x7fffffff)
423         weight = CW_Constant;
424     break;
425   }
426   return weight;
427 }
428
429 // Parse a "{tNNN}" register constraint for which the register type "t"
430 // has already been verified.  MC is the class associated with "t" and
431 // Map maps 0-based register numbers to LLVM register numbers.
432 static std::pair<unsigned, const TargetRegisterClass *>
433 parseRegisterNumber(const std::string &Constraint,
434                     const TargetRegisterClass *RC, const unsigned *Map) {
435   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
436   if (isdigit(Constraint[2])) {
437     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
438     unsigned Index = atoi(Suffix.c_str());
439     if (Index < 16 && Map[Index])
440       return std::make_pair(Map[Index], RC);
441   }
442   return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
443 }
444
445 std::pair<unsigned, const TargetRegisterClass *> SystemZTargetLowering::
446 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const {
447   if (Constraint.size() == 1) {
448     // GCC Constraint Letters
449     switch (Constraint[0]) {
450     default: break;
451     case 'd': // Data register (equivalent to 'r')
452     case 'r': // General-purpose register
453       if (VT == MVT::i64)
454         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
455       else if (VT == MVT::i128)
456         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
457       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
458
459     case 'a': // Address register
460       if (VT == MVT::i64)
461         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
462       else if (VT == MVT::i128)
463         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
464       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
465
466     case 'f': // Floating-point register
467       if (VT == MVT::f64)
468         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
469       else if (VT == MVT::f128)
470         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
471       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
472     }
473   }
474   if (Constraint[0] == '{') {
475     // We need to override the default register parsing for GPRs and FPRs
476     // because the interpretation depends on VT.  The internal names of
477     // the registers are also different from the external names
478     // (F0D and F0S instead of F0, etc.).
479     if (Constraint[1] == 'r') {
480       if (VT == MVT::i32)
481         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
482                                    SystemZMC::GR32Regs);
483       if (VT == MVT::i128)
484         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
485                                    SystemZMC::GR128Regs);
486       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
487                                  SystemZMC::GR64Regs);
488     }
489     if (Constraint[1] == 'f') {
490       if (VT == MVT::f32)
491         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
492                                    SystemZMC::FP32Regs);
493       if (VT == MVT::f128)
494         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
495                                    SystemZMC::FP128Regs);
496       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
497                                  SystemZMC::FP64Regs);
498     }
499   }
500   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
501 }
502
503 void SystemZTargetLowering::
504 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
505                              std::vector<SDValue> &Ops,
506                              SelectionDAG &DAG) const {
507   // Only support length 1 constraints for now.
508   if (Constraint.length() == 1) {
509     switch (Constraint[0]) {
510     case 'I': // Unsigned 8-bit constant
511       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
512         if (isUInt<8>(C->getZExtValue()))
513           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
514                                               Op.getValueType()));
515       return;
516
517     case 'J': // Unsigned 12-bit constant
518       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
519         if (isUInt<12>(C->getZExtValue()))
520           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
521                                               Op.getValueType()));
522       return;
523
524     case 'K': // Signed 16-bit constant
525       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
526         if (isInt<16>(C->getSExtValue()))
527           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
528                                               Op.getValueType()));
529       return;
530
531     case 'L': // Signed 20-bit displacement (on all targets we support)
532       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
533         if (isInt<20>(C->getSExtValue()))
534           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
535                                               Op.getValueType()));
536       return;
537
538     case 'M': // 0x7fffffff
539       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
540         if (C->getZExtValue() == 0x7fffffff)
541           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
542                                               Op.getValueType()));
543       return;
544     }
545   }
546   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
547 }
548
549 //===----------------------------------------------------------------------===//
550 // Calling conventions
551 //===----------------------------------------------------------------------===//
552
553 #include "SystemZGenCallingConv.inc"
554
555 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
556                                                      Type *ToType) const {
557   return isTruncateFree(FromType, ToType);
558 }
559
560 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
561   if (!CI->isTailCall())
562     return false;
563   return true;
564 }
565
566 // Value is a value that has been passed to us in the location described by VA
567 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
568 // any loads onto Chain.
569 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
570                                    CCValAssign &VA, SDValue Chain,
571                                    SDValue Value) {
572   // If the argument has been promoted from a smaller type, insert an
573   // assertion to capture this.
574   if (VA.getLocInfo() == CCValAssign::SExt)
575     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
576                         DAG.getValueType(VA.getValVT()));
577   else if (VA.getLocInfo() == CCValAssign::ZExt)
578     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
579                         DAG.getValueType(VA.getValVT()));
580
581   if (VA.isExtInLoc())
582     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
583   else if (VA.getLocInfo() == CCValAssign::Indirect)
584     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
585                         MachinePointerInfo(), false, false, false, 0);
586   else
587     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
588   return Value;
589 }
590
591 // Value is a value of type VA.getValVT() that we need to copy into
592 // the location described by VA.  Return a copy of Value converted to
593 // VA.getValVT().  The caller is responsible for handling indirect values.
594 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
595                                    CCValAssign &VA, SDValue Value) {
596   switch (VA.getLocInfo()) {
597   case CCValAssign::SExt:
598     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
599   case CCValAssign::ZExt:
600     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
601   case CCValAssign::AExt:
602     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
603   case CCValAssign::Full:
604     return Value;
605   default:
606     llvm_unreachable("Unhandled getLocInfo()");
607   }
608 }
609
610 SDValue SystemZTargetLowering::
611 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
612                      const SmallVectorImpl<ISD::InputArg> &Ins,
613                      SDLoc DL, SelectionDAG &DAG,
614                      SmallVectorImpl<SDValue> &InVals) const {
615   MachineFunction &MF = DAG.getMachineFunction();
616   MachineFrameInfo *MFI = MF.getFrameInfo();
617   MachineRegisterInfo &MRI = MF.getRegInfo();
618   SystemZMachineFunctionInfo *FuncInfo =
619     MF.getInfo<SystemZMachineFunctionInfo>();
620   const SystemZFrameLowering *TFL =
621     static_cast<const SystemZFrameLowering *>(TM.getFrameLowering());
622
623   // Assign locations to all of the incoming arguments.
624   SmallVector<CCValAssign, 16> ArgLocs;
625   CCState CCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
626   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
627
628   unsigned NumFixedGPRs = 0;
629   unsigned NumFixedFPRs = 0;
630   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
631     SDValue ArgValue;
632     CCValAssign &VA = ArgLocs[I];
633     EVT LocVT = VA.getLocVT();
634     if (VA.isRegLoc()) {
635       // Arguments passed in registers
636       const TargetRegisterClass *RC;
637       switch (LocVT.getSimpleVT().SimpleTy) {
638       default:
639         // Integers smaller than i64 should be promoted to i64.
640         llvm_unreachable("Unexpected argument type");
641       case MVT::i32:
642         NumFixedGPRs += 1;
643         RC = &SystemZ::GR32BitRegClass;
644         break;
645       case MVT::i64:
646         NumFixedGPRs += 1;
647         RC = &SystemZ::GR64BitRegClass;
648         break;
649       case MVT::f32:
650         NumFixedFPRs += 1;
651         RC = &SystemZ::FP32BitRegClass;
652         break;
653       case MVT::f64:
654         NumFixedFPRs += 1;
655         RC = &SystemZ::FP64BitRegClass;
656         break;
657       }
658
659       unsigned VReg = MRI.createVirtualRegister(RC);
660       MRI.addLiveIn(VA.getLocReg(), VReg);
661       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
662     } else {
663       assert(VA.isMemLoc() && "Argument not register or memory");
664
665       // Create the frame index object for this incoming parameter.
666       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
667                                       VA.getLocMemOffset(), true);
668
669       // Create the SelectionDAG nodes corresponding to a load
670       // from this parameter.  Unpromoted ints and floats are
671       // passed as right-justified 8-byte values.
672       EVT PtrVT = getPointerTy();
673       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
674       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
675         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
676       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
677                              MachinePointerInfo::getFixedStack(FI),
678                              false, false, false, 0);
679     }
680
681     // Convert the value of the argument register into the value that's
682     // being passed.
683     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
684   }
685
686   if (IsVarArg) {
687     // Save the number of non-varargs registers for later use by va_start, etc.
688     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
689     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
690
691     // Likewise the address (in the form of a frame index) of where the
692     // first stack vararg would be.  The 1-byte size here is arbitrary.
693     int64_t StackSize = CCInfo.getNextStackOffset();
694     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
695
696     // ...and a similar frame index for the caller-allocated save area
697     // that will be used to store the incoming registers.
698     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
699     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
700     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
701
702     // Store the FPR varargs in the reserved frame slots.  (We store the
703     // GPRs as part of the prologue.)
704     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
705       SDValue MemOps[SystemZ::NumArgFPRs];
706       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
707         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
708         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
709         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
710         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
711                                      &SystemZ::FP64BitRegClass);
712         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
713         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
714                                  MachinePointerInfo::getFixedStack(FI),
715                                  false, false, 0);
716
717       }
718       // Join the stores, which are independent of one another.
719       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
720                           &MemOps[NumFixedFPRs],
721                           SystemZ::NumArgFPRs - NumFixedFPRs);
722     }
723   }
724
725   return Chain;
726 }
727
728 static bool canUseSiblingCall(CCState ArgCCInfo,
729                               SmallVectorImpl<CCValAssign> &ArgLocs) {
730   // Punt if there are any indirect or stack arguments, or if the call
731   // needs the call-saved argument register R6.
732   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
733     CCValAssign &VA = ArgLocs[I];
734     if (VA.getLocInfo() == CCValAssign::Indirect)
735       return false;
736     if (!VA.isRegLoc())
737       return false;
738     unsigned Reg = VA.getLocReg();
739     if (Reg == SystemZ::R6W || Reg == SystemZ::R6D)
740       return false;
741   }
742   return true;
743 }
744
745 SDValue
746 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
747                                  SmallVectorImpl<SDValue> &InVals) const {
748   SelectionDAG &DAG = CLI.DAG;
749   SDLoc &DL = CLI.DL;
750   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
751   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
752   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
753   SDValue Chain = CLI.Chain;
754   SDValue Callee = CLI.Callee;
755   bool &IsTailCall = CLI.IsTailCall;
756   CallingConv::ID CallConv = CLI.CallConv;
757   bool IsVarArg = CLI.IsVarArg;
758   MachineFunction &MF = DAG.getMachineFunction();
759   EVT PtrVT = getPointerTy();
760
761   // Analyze the operands of the call, assigning locations to each operand.
762   SmallVector<CCValAssign, 16> ArgLocs;
763   CCState ArgCCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
764   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
765
766   // We don't support GuaranteedTailCallOpt, only automatically-detected
767   // sibling calls.
768   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
769     IsTailCall = false;
770
771   // Get a count of how many bytes are to be pushed on the stack.
772   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
773
774   // Mark the start of the call.
775   if (!IsTailCall)
776     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
777                                  DL);
778
779   // Copy argument values to their designated locations.
780   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
781   SmallVector<SDValue, 8> MemOpChains;
782   SDValue StackPtr;
783   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
784     CCValAssign &VA = ArgLocs[I];
785     SDValue ArgValue = OutVals[I];
786
787     if (VA.getLocInfo() == CCValAssign::Indirect) {
788       // Store the argument in a stack slot and pass its address.
789       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
790       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
791       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
792                                          MachinePointerInfo::getFixedStack(FI),
793                                          false, false, 0));
794       ArgValue = SpillSlot;
795     } else
796       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
797
798     if (VA.isRegLoc())
799       // Queue up the argument copies and emit them at the end.
800       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
801     else {
802       assert(VA.isMemLoc() && "Argument not register or memory");
803
804       // Work out the address of the stack slot.  Unpromoted ints and
805       // floats are passed as right-justified 8-byte values.
806       if (!StackPtr.getNode())
807         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
808       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
809       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
810         Offset += 4;
811       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
812                                     DAG.getIntPtrConstant(Offset));
813
814       // Emit the store.
815       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
816                                          MachinePointerInfo(),
817                                          false, false, 0));
818     }
819   }
820
821   // Join the stores, which are independent of one another.
822   if (!MemOpChains.empty())
823     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
824                         &MemOpChains[0], MemOpChains.size());
825
826   // Accept direct calls by converting symbolic call addresses to the
827   // associated Target* opcodes.  Force %r1 to be used for indirect
828   // tail calls.
829   SDValue Glue;
830   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
831     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
832     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
833   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
834     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
835     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
836   } else if (IsTailCall) {
837     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
838     Glue = Chain.getValue(1);
839     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
840   }
841
842   // Build a sequence of copy-to-reg nodes, chained and glued together.
843   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
844     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
845                              RegsToPass[I].second, Glue);
846     Glue = Chain.getValue(1);
847   }
848
849   // The first call operand is the chain and the second is the target address.
850   SmallVector<SDValue, 8> Ops;
851   Ops.push_back(Chain);
852   Ops.push_back(Callee);
853
854   // Add argument registers to the end of the list so that they are
855   // known live into the call.
856   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
857     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
858                                   RegsToPass[I].second.getValueType()));
859
860   // Glue the call to the argument copies, if any.
861   if (Glue.getNode())
862     Ops.push_back(Glue);
863
864   // Emit the call.
865   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
866   if (IsTailCall)
867     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, &Ops[0], Ops.size());
868   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
869   Glue = Chain.getValue(1);
870
871   // Mark the end of the call, which is glued to the call itself.
872   Chain = DAG.getCALLSEQ_END(Chain,
873                              DAG.getConstant(NumBytes, PtrVT, true),
874                              DAG.getConstant(0, PtrVT, true),
875                              Glue, DL);
876   Glue = Chain.getValue(1);
877
878   // Assign locations to each value returned by this call.
879   SmallVector<CCValAssign, 16> RetLocs;
880   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
881   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
882
883   // Copy all of the result registers out of their specified physreg.
884   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
885     CCValAssign &VA = RetLocs[I];
886
887     // Copy the value out, gluing the copy to the end of the call sequence.
888     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
889                                           VA.getLocVT(), Glue);
890     Chain = RetValue.getValue(1);
891     Glue = RetValue.getValue(2);
892
893     // Convert the value of the return register into the value that's
894     // being returned.
895     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
896   }
897
898   return Chain;
899 }
900
901 SDValue
902 SystemZTargetLowering::LowerReturn(SDValue Chain,
903                                    CallingConv::ID CallConv, bool IsVarArg,
904                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
905                                    const SmallVectorImpl<SDValue> &OutVals,
906                                    SDLoc DL, SelectionDAG &DAG) const {
907   MachineFunction &MF = DAG.getMachineFunction();
908
909   // Assign locations to each returned value.
910   SmallVector<CCValAssign, 16> RetLocs;
911   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
912   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
913
914   // Quick exit for void returns
915   if (RetLocs.empty())
916     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
917
918   // Copy the result values into the output registers.
919   SDValue Glue;
920   SmallVector<SDValue, 4> RetOps;
921   RetOps.push_back(Chain);
922   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
923     CCValAssign &VA = RetLocs[I];
924     SDValue RetValue = OutVals[I];
925
926     // Make the return register live on exit.
927     assert(VA.isRegLoc() && "Can only return in registers!");
928
929     // Promote the value as required.
930     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
931
932     // Chain and glue the copies together.
933     unsigned Reg = VA.getLocReg();
934     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
935     Glue = Chain.getValue(1);
936     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
937   }
938
939   // Update chain and glue.
940   RetOps[0] = Chain;
941   if (Glue.getNode())
942     RetOps.push_back(Glue);
943
944   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other,
945                      RetOps.data(), RetOps.size());
946 }
947
948 // CC is a comparison that will be implemented using an integer or
949 // floating-point comparison.  Return the condition code mask for
950 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
951 // unsigned comparisons and clear for signed ones.  In the floating-point
952 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
953 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
954 #define CONV(X) \
955   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
956   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
957   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
958
959   switch (CC) {
960   default:
961     llvm_unreachable("Invalid integer condition!");
962
963   CONV(EQ);
964   CONV(NE);
965   CONV(GT);
966   CONV(GE);
967   CONV(LT);
968   CONV(LE);
969
970   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
971   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
972   }
973 #undef CONV
974 }
975
976 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
977 // can be converted to a comparison against zero, adjust the operands
978 // as necessary.
979 static void adjustZeroCmp(SelectionDAG &DAG, bool &IsUnsigned,
980                           SDValue &CmpOp0, SDValue &CmpOp1,
981                           unsigned &CCMask) {
982   if (IsUnsigned)
983     return;
984
985   ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(CmpOp1.getNode());
986   if (!ConstOp1)
987     return;
988
989   int64_t Value = ConstOp1->getSExtValue();
990   if ((Value == -1 && CCMask == SystemZ::CCMASK_CMP_GT) ||
991       (Value == -1 && CCMask == SystemZ::CCMASK_CMP_LE) ||
992       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_LT) ||
993       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_GE)) {
994     CCMask ^= SystemZ::CCMASK_CMP_EQ;
995     CmpOp1 = DAG.getConstant(0, CmpOp1.getValueType());
996   }
997 }
998
999 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
1000 // is suitable for CLI(Y), CHHSI or CLHHSI, adjust the operands as necessary.
1001 static void adjustSubwordCmp(SelectionDAG &DAG, bool &IsUnsigned,
1002                              SDValue &CmpOp0, SDValue &CmpOp1,
1003                              unsigned &CCMask) {
1004   // For us to make any changes, it must a comparison between a single-use
1005   // load and a constant.
1006   if (!CmpOp0.hasOneUse() ||
1007       CmpOp0.getOpcode() != ISD::LOAD ||
1008       CmpOp1.getOpcode() != ISD::Constant)
1009     return;
1010
1011   // We must have an 8- or 16-bit load.
1012   LoadSDNode *Load = cast<LoadSDNode>(CmpOp0);
1013   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1014   if (NumBits != 8 && NumBits != 16)
1015     return;
1016
1017   // The load must be an extending one and the constant must be within the
1018   // range of the unextended value.
1019   ConstantSDNode *Constant = cast<ConstantSDNode>(CmpOp1);
1020   uint64_t Value = Constant->getZExtValue();
1021   uint64_t Mask = (1 << NumBits) - 1;
1022   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1023     int64_t SignedValue = Constant->getSExtValue();
1024     if (uint64_t(SignedValue) + (1ULL << (NumBits - 1)) > Mask)
1025       return;
1026     // Unsigned comparison between two sign-extended values is equivalent
1027     // to unsigned comparison between two zero-extended values.
1028     if (IsUnsigned)
1029       Value &= Mask;
1030     else if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1031              CCMask == SystemZ::CCMASK_CMP_NE)
1032       // Any choice of IsUnsigned is OK for equality comparisons.
1033       // We could use either CHHSI or CLHHSI for 16-bit comparisons,
1034       // but since we use CLHHSI for zero extensions, it seems better
1035       // to be consistent and do the same here.
1036       Value &= Mask, IsUnsigned = true;
1037     else if (NumBits == 8) {
1038       // Try to treat the comparison as unsigned, so that we can use CLI.
1039       // Adjust CCMask and Value as necessary.
1040       if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_LT)
1041         // Test whether the high bit of the byte is set.
1042         Value = 127, CCMask = SystemZ::CCMASK_CMP_GT, IsUnsigned = true;
1043       else if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_GE)
1044         // Test whether the high bit of the byte is clear.
1045         Value = 128, CCMask = SystemZ::CCMASK_CMP_LT, IsUnsigned = true;
1046       else
1047         // No instruction exists for this combination.
1048         return;
1049     }
1050   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1051     if (Value > Mask)
1052       return;
1053     // Signed comparison between two zero-extended values is equivalent
1054     // to unsigned comparison.
1055     IsUnsigned = true;
1056   } else
1057     return;
1058
1059   // Make sure that the first operand is an i32 of the right extension type.
1060   ISD::LoadExtType ExtType = IsUnsigned ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
1061   if (CmpOp0.getValueType() != MVT::i32 ||
1062       Load->getExtensionType() != ExtType)
1063     CmpOp0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1064                             Load->getChain(), Load->getBasePtr(),
1065                             Load->getPointerInfo(), Load->getMemoryVT(),
1066                             Load->isVolatile(), Load->isNonTemporal(),
1067                             Load->getAlignment());
1068
1069   // Make sure that the second operand is an i32 with the right value.
1070   if (CmpOp1.getValueType() != MVT::i32 ||
1071       Value != Constant->getZExtValue())
1072     CmpOp1 = DAG.getConstant(Value, MVT::i32);
1073 }
1074
1075 // Return true if a comparison described by CCMask, CmpOp0 and CmpOp1
1076 // is an equality comparison that is better implemented using unsigned
1077 // rather than signed comparison instructions.
1078 static bool preferUnsignedComparison(SelectionDAG &DAG, SDValue CmpOp0,
1079                                      SDValue CmpOp1, unsigned CCMask) {
1080   // The test must be for equality or inequality.
1081   if (CCMask != SystemZ::CCMASK_CMP_EQ && CCMask != SystemZ::CCMASK_CMP_NE)
1082     return false;
1083
1084   if (CmpOp1.getOpcode() == ISD::Constant) {
1085     uint64_t Value = cast<ConstantSDNode>(CmpOp1)->getSExtValue();
1086
1087     // If we're comparing with memory, prefer unsigned comparisons for
1088     // values that are in the unsigned 16-bit range but not the signed
1089     // 16-bit range.  We want to use CLFHSI and CLGHSI.
1090     if (CmpOp0.hasOneUse() &&
1091         ISD::isNormalLoad(CmpOp0.getNode()) &&
1092         (Value >= 32768 && Value < 65536))
1093       return true;
1094
1095     // Use unsigned comparisons for values that are in the CLGFI range
1096     // but not in the CGFI range.
1097     if (CmpOp0.getValueType() == MVT::i64 && (Value >> 31) == 1)
1098       return true;
1099
1100     return false;
1101   }
1102
1103   // Prefer CL for zero-extended loads.
1104   if (CmpOp1.getOpcode() == ISD::ZERO_EXTEND ||
1105       ISD::isZEXTLoad(CmpOp1.getNode()))
1106     return true;
1107
1108   // ...and for "in-register" zero extensions.
1109   if (CmpOp1.getOpcode() == ISD::AND && CmpOp1.getValueType() == MVT::i64) {
1110     SDValue Mask = CmpOp1.getOperand(1);
1111     if (Mask.getOpcode() == ISD::Constant &&
1112         cast<ConstantSDNode>(Mask)->getZExtValue() == 0xffffffff)
1113       return true;
1114   }
1115
1116   return false;
1117 }
1118
1119 // Return a target node that compares CmpOp0 with CmpOp1 and stores a
1120 // 2-bit result in CC.  Set CCValid to the CCMASK_* of all possible
1121 // 2-bit results and CCMask to the subset of those results that are
1122 // associated with Cond.
1123 static SDValue emitCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
1124                        ISD::CondCode Cond, unsigned &CCValid,
1125                        unsigned &CCMask) {
1126   bool IsUnsigned = false;
1127   CCMask = CCMaskForCondCode(Cond);
1128   if (CmpOp0.getValueType().isFloatingPoint())
1129     CCValid = SystemZ::CCMASK_FCMP;
1130   else {
1131     IsUnsigned = CCMask & SystemZ::CCMASK_CMP_UO;
1132     CCValid = SystemZ::CCMASK_ICMP;
1133     CCMask &= CCValid;
1134     adjustZeroCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1135     adjustSubwordCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1136     if (preferUnsignedComparison(DAG, CmpOp0, CmpOp1, CCMask))
1137       IsUnsigned = true;
1138   }
1139
1140   SDLoc DL(CmpOp0);
1141   return DAG.getNode((IsUnsigned ? SystemZISD::UCMP : SystemZISD::CMP),
1142                      DL, MVT::Glue, CmpOp0, CmpOp1);
1143 }
1144
1145 // Lower a binary operation that produces two VT results, one in each
1146 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1147 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1148 // on the extended Op0 and (unextended) Op1.  Store the even register result
1149 // in Even and the odd register result in Odd.
1150 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1151                              unsigned Extend, unsigned Opcode,
1152                              SDValue Op0, SDValue Op1,
1153                              SDValue &Even, SDValue &Odd) {
1154   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1155   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1156                                SDValue(In128, 0), Op1);
1157   bool Is32Bit = is32Bit(VT);
1158   SDValue SubReg0 = DAG.getTargetConstant(SystemZ::even128(Is32Bit), VT);
1159   SDValue SubReg1 = DAG.getTargetConstant(SystemZ::odd128(Is32Bit), VT);
1160   SDNode *Reg0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1161                                     VT, Result, SubReg0);
1162   SDNode *Reg1 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1163                                     VT, Result, SubReg1);
1164   Even = SDValue(Reg0, 0);
1165   Odd = SDValue(Reg1, 0);
1166 }
1167
1168 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1169   SDValue Chain    = Op.getOperand(0);
1170   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1171   SDValue CmpOp0   = Op.getOperand(2);
1172   SDValue CmpOp1   = Op.getOperand(3);
1173   SDValue Dest     = Op.getOperand(4);
1174   SDLoc DL(Op);
1175
1176   unsigned CCValid, CCMask;
1177   SDValue Flags = emitCmp(DAG, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1178   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1179                      Chain, DAG.getConstant(CCValid, MVT::i32),
1180                      DAG.getConstant(CCMask, MVT::i32), Dest, Flags);
1181 }
1182
1183 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1184                                               SelectionDAG &DAG) const {
1185   SDValue CmpOp0   = Op.getOperand(0);
1186   SDValue CmpOp1   = Op.getOperand(1);
1187   SDValue TrueOp   = Op.getOperand(2);
1188   SDValue FalseOp  = Op.getOperand(3);
1189   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1190   SDLoc DL(Op);
1191
1192   unsigned CCValid, CCMask;
1193   SDValue Flags = emitCmp(DAG, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1194
1195   SmallVector<SDValue, 5> Ops;
1196   Ops.push_back(TrueOp);
1197   Ops.push_back(FalseOp);
1198   Ops.push_back(DAG.getConstant(CCValid, MVT::i32));
1199   Ops.push_back(DAG.getConstant(CCMask, MVT::i32));
1200   Ops.push_back(Flags);
1201
1202   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1203   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
1204 }
1205
1206 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1207                                                   SelectionDAG &DAG) const {
1208   SDLoc DL(Node);
1209   const GlobalValue *GV = Node->getGlobal();
1210   int64_t Offset = Node->getOffset();
1211   EVT PtrVT = getPointerTy();
1212   Reloc::Model RM = TM.getRelocationModel();
1213   CodeModel::Model CM = TM.getCodeModel();
1214
1215   SDValue Result;
1216   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1217     // Make sure that the offset is aligned to a halfword.  If it isn't,
1218     // create an "anchor" at the previous 12-bit boundary.
1219     // FIXME check whether there is a better way of handling this.
1220     if (Offset & 1) {
1221       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1222                                           Offset & ~uint64_t(0xfff));
1223       Offset &= 0xfff;
1224     } else {
1225       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Offset);
1226       Offset = 0;
1227     }
1228     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1229   } else {
1230     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1231     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1232     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1233                          MachinePointerInfo::getGOT(), false, false, false, 0);
1234   }
1235
1236   // If there was a non-zero offset that we didn't fold, create an explicit
1237   // addition for it.
1238   if (Offset != 0)
1239     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1240                          DAG.getConstant(Offset, PtrVT));
1241
1242   return Result;
1243 }
1244
1245 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1246                                                      SelectionDAG &DAG) const {
1247   SDLoc DL(Node);
1248   const GlobalValue *GV = Node->getGlobal();
1249   EVT PtrVT = getPointerTy();
1250   TLSModel::Model model = TM.getTLSModel(GV);
1251
1252   if (model != TLSModel::LocalExec)
1253     llvm_unreachable("only local-exec TLS mode supported");
1254
1255   // The high part of the thread pointer is in access register 0.
1256   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1257                              DAG.getConstant(0, MVT::i32));
1258   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1259
1260   // The low part of the thread pointer is in access register 1.
1261   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1262                              DAG.getConstant(1, MVT::i32));
1263   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1264
1265   // Merge them into a single 64-bit address.
1266   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1267                                     DAG.getConstant(32, PtrVT));
1268   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1269
1270   // Get the offset of GA from the thread pointer.
1271   SystemZConstantPoolValue *CPV =
1272     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1273
1274   // Force the offset into the constant pool and load it from there.
1275   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
1276   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1277                                CPAddr, MachinePointerInfo::getConstantPool(),
1278                                false, false, false, 0);
1279
1280   // Add the base and offset together.
1281   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1282 }
1283
1284 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1285                                                  SelectionDAG &DAG) const {
1286   SDLoc DL(Node);
1287   const BlockAddress *BA = Node->getBlockAddress();
1288   int64_t Offset = Node->getOffset();
1289   EVT PtrVT = getPointerTy();
1290
1291   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1292   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1293   return Result;
1294 }
1295
1296 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
1297                                               SelectionDAG &DAG) const {
1298   SDLoc DL(JT);
1299   EVT PtrVT = getPointerTy();
1300   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1301
1302   // Use LARL to load the address of the table.
1303   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1304 }
1305
1306 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
1307                                                  SelectionDAG &DAG) const {
1308   SDLoc DL(CP);
1309   EVT PtrVT = getPointerTy();
1310
1311   SDValue Result;
1312   if (CP->isMachineConstantPoolEntry())
1313     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1314                                        CP->getAlignment());
1315   else
1316     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1317                                        CP->getAlignment(), CP->getOffset());
1318
1319   // Use LARL to load the address of the constant pool entry.
1320   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1321 }
1322
1323 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
1324                                             SelectionDAG &DAG) const {
1325   SDLoc DL(Op);
1326   SDValue In = Op.getOperand(0);
1327   EVT InVT = In.getValueType();
1328   EVT ResVT = Op.getValueType();
1329
1330   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1331   SDValue Shift32 = DAG.getConstant(32, MVT::i64);
1332   if (InVT == MVT::i32 && ResVT == MVT::f32) {
1333     SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
1334     SDValue Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, In64, Shift32);
1335     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shift);
1336     SDNode *Out = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1337                                      MVT::f32, Out64, SubReg32);
1338     return SDValue(Out, 0);
1339   }
1340   if (InVT == MVT::f32 && ResVT == MVT::i32) {
1341     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
1342     SDNode *In64 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1343                                       MVT::f64, SDValue(U64, 0), In, SubReg32);
1344     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, SDValue(In64, 0));
1345     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64, Shift32);
1346     SDValue Out = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
1347     return Out;
1348   }
1349   llvm_unreachable("Unexpected bitcast combination");
1350 }
1351
1352 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
1353                                             SelectionDAG &DAG) const {
1354   MachineFunction &MF = DAG.getMachineFunction();
1355   SystemZMachineFunctionInfo *FuncInfo =
1356     MF.getInfo<SystemZMachineFunctionInfo>();
1357   EVT PtrVT = getPointerTy();
1358
1359   SDValue Chain   = Op.getOperand(0);
1360   SDValue Addr    = Op.getOperand(1);
1361   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1362   SDLoc DL(Op);
1363
1364   // The initial values of each field.
1365   const unsigned NumFields = 4;
1366   SDValue Fields[NumFields] = {
1367     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
1368     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
1369     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
1370     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
1371   };
1372
1373   // Store each field into its respective slot.
1374   SDValue MemOps[NumFields];
1375   unsigned Offset = 0;
1376   for (unsigned I = 0; I < NumFields; ++I) {
1377     SDValue FieldAddr = Addr;
1378     if (Offset != 0)
1379       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
1380                               DAG.getIntPtrConstant(Offset));
1381     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
1382                              MachinePointerInfo(SV, Offset),
1383                              false, false, 0);
1384     Offset += 8;
1385   }
1386   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
1387 }
1388
1389 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
1390                                            SelectionDAG &DAG) const {
1391   SDValue Chain      = Op.getOperand(0);
1392   SDValue DstPtr     = Op.getOperand(1);
1393   SDValue SrcPtr     = Op.getOperand(2);
1394   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1395   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1396   SDLoc DL(Op);
1397
1398   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
1399                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
1400                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
1401 }
1402
1403 SDValue SystemZTargetLowering::
1404 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
1405   SDValue Chain = Op.getOperand(0);
1406   SDValue Size  = Op.getOperand(1);
1407   SDLoc DL(Op);
1408
1409   unsigned SPReg = getStackPointerRegisterToSaveRestore();
1410
1411   // Get a reference to the stack pointer.
1412   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
1413
1414   // Get the new stack pointer value.
1415   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
1416
1417   // Copy the new stack pointer back.
1418   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
1419
1420   // The allocated data lives above the 160 bytes allocated for the standard
1421   // frame, plus any outgoing stack arguments.  We don't know how much that
1422   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
1423   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
1424   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
1425
1426   SDValue Ops[2] = { Result, Chain };
1427   return DAG.getMergeValues(Ops, 2, DL);
1428 }
1429
1430 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
1431                                               SelectionDAG &DAG) const {
1432   EVT VT = Op.getValueType();
1433   SDLoc DL(Op);
1434   assert(!is32Bit(VT) && "Only support 64-bit UMUL_LOHI");
1435
1436   // UMUL_LOHI64 returns the low result in the odd register and the high
1437   // result in the even register.  UMUL_LOHI is defined to return the
1438   // low half first, so the results are in reverse order.
1439   SDValue Ops[2];
1440   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1441                    Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1442   return DAG.getMergeValues(Ops, 2, DL);
1443 }
1444
1445 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
1446                                             SelectionDAG &DAG) const {
1447   SDValue Op0 = Op.getOperand(0);
1448   SDValue Op1 = Op.getOperand(1);
1449   EVT VT = Op.getValueType();
1450   SDLoc DL(Op);
1451   unsigned Opcode;
1452
1453   // We use DSGF for 32-bit division.
1454   if (is32Bit(VT)) {
1455     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
1456     Opcode = SystemZISD::SDIVREM32;
1457   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
1458     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
1459     Opcode = SystemZISD::SDIVREM32;
1460   } else    
1461     Opcode = SystemZISD::SDIVREM64;
1462
1463   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
1464   // input is "don't care".  The instruction returns the remainder in
1465   // the even register and the quotient in the odd register.
1466   SDValue Ops[2];
1467   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
1468                    Op0, Op1, Ops[1], Ops[0]);
1469   return DAG.getMergeValues(Ops, 2, DL);
1470 }
1471
1472 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
1473                                             SelectionDAG &DAG) const {
1474   EVT VT = Op.getValueType();
1475   SDLoc DL(Op);
1476
1477   // DL(G) uses a double-width dividend, so we need to clear the even
1478   // register in the GR128 input.  The instruction returns the remainder
1479   // in the even register and the quotient in the odd register.
1480   SDValue Ops[2];
1481   if (is32Bit(VT))
1482     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
1483                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1484   else
1485     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
1486                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1487   return DAG.getMergeValues(Ops, 2, DL);
1488 }
1489
1490 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
1491   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
1492
1493   // Get the known-zero masks for each operand.
1494   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
1495   APInt KnownZero[2], KnownOne[2];
1496   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
1497   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
1498
1499   // See if the upper 32 bits of one operand and the lower 32 bits of the
1500   // other are known zero.  They are the low and high operands respectively.
1501   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
1502                        KnownZero[1].getZExtValue() };
1503   unsigned High, Low;
1504   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
1505     High = 1, Low = 0;
1506   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
1507     High = 0, Low = 1;
1508   else
1509     return Op;
1510
1511   SDValue LowOp = Ops[Low];
1512   SDValue HighOp = Ops[High];
1513
1514   // If the high part is a constant, we're better off using IILH.
1515   if (HighOp.getOpcode() == ISD::Constant)
1516     return Op;
1517
1518   // If the low part is a constant that is outside the range of LHI,
1519   // then we're better off using IILF.
1520   if (LowOp.getOpcode() == ISD::Constant) {
1521     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
1522     if (!isInt<16>(Value))
1523       return Op;
1524   }
1525
1526   // Check whether the high part is an AND that doesn't change the
1527   // high 32 bits and just masks out low bits.  We can skip it if so.
1528   if (HighOp.getOpcode() == ISD::AND &&
1529       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
1530     ConstantSDNode *MaskNode = cast<ConstantSDNode>(HighOp.getOperand(1));
1531     uint64_t Mask = MaskNode->getZExtValue() | Masks[High];
1532     if ((Mask >> 32) == 0xffffffff)
1533       HighOp = HighOp.getOperand(0);
1534   }
1535
1536   // Take advantage of the fact that all GR32 operations only change the
1537   // low 32 bits by truncating Low to an i32 and inserting it directly
1538   // using a subreg.  The interesting cases are those where the truncation
1539   // can be folded.
1540   SDLoc DL(Op);
1541   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
1542   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1543   SDNode *Result = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1544                                       MVT::i64, HighOp, Low32, SubReg32);
1545   return SDValue(Result, 0);
1546 }
1547
1548 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
1549 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
1550 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
1551                                                 SelectionDAG &DAG,
1552                                                 unsigned Opcode) const {
1553   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1554
1555   // 32-bit operations need no code outside the main loop.
1556   EVT NarrowVT = Node->getMemoryVT();
1557   EVT WideVT = MVT::i32;
1558   if (NarrowVT == WideVT)
1559     return Op;
1560
1561   int64_t BitSize = NarrowVT.getSizeInBits();
1562   SDValue ChainIn = Node->getChain();
1563   SDValue Addr = Node->getBasePtr();
1564   SDValue Src2 = Node->getVal();
1565   MachineMemOperand *MMO = Node->getMemOperand();
1566   SDLoc DL(Node);
1567   EVT PtrVT = Addr.getValueType();
1568
1569   // Convert atomic subtracts of constants into additions.
1570   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
1571     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Src2)) {
1572       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
1573       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
1574     }
1575
1576   // Get the address of the containing word.
1577   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1578                                     DAG.getConstant(-4, PtrVT));
1579
1580   // Get the number of bits that the word must be rotated left in order
1581   // to bring the field to the top bits of a GR32.
1582   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1583                                  DAG.getConstant(3, PtrVT));
1584   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1585
1586   // Get the complementing shift amount, for rotating a field in the top
1587   // bits back to its proper position.
1588   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1589                                     DAG.getConstant(0, WideVT), BitShift);
1590
1591   // Extend the source operand to 32 bits and prepare it for the inner loop.
1592   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
1593   // operations require the source to be shifted in advance.  (This shift
1594   // can be folded if the source is constant.)  For AND and NAND, the lower
1595   // bits must be set, while for other opcodes they should be left clear.
1596   if (Opcode != SystemZISD::ATOMIC_SWAPW)
1597     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
1598                        DAG.getConstant(32 - BitSize, WideVT));
1599   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
1600       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
1601     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
1602                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
1603
1604   // Construct the ATOMIC_LOADW_* node.
1605   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1606   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
1607                     DAG.getConstant(BitSize, WideVT) };
1608   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
1609                                              array_lengthof(Ops),
1610                                              NarrowVT, MMO);
1611
1612   // Rotate the result of the final CS so that the field is in the lower
1613   // bits of a GR32, then truncate it.
1614   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
1615                                     DAG.getConstant(BitSize, WideVT));
1616   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
1617
1618   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
1619   return DAG.getMergeValues(RetOps, 2, DL);
1620 }
1621
1622 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
1623 // into a fullword ATOMIC_CMP_SWAPW operation.
1624 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
1625                                                     SelectionDAG &DAG) const {
1626   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1627
1628   // We have native support for 32-bit compare and swap.
1629   EVT NarrowVT = Node->getMemoryVT();
1630   EVT WideVT = MVT::i32;
1631   if (NarrowVT == WideVT)
1632     return Op;
1633
1634   int64_t BitSize = NarrowVT.getSizeInBits();
1635   SDValue ChainIn = Node->getOperand(0);
1636   SDValue Addr = Node->getOperand(1);
1637   SDValue CmpVal = Node->getOperand(2);
1638   SDValue SwapVal = Node->getOperand(3);
1639   MachineMemOperand *MMO = Node->getMemOperand();
1640   SDLoc DL(Node);
1641   EVT PtrVT = Addr.getValueType();
1642
1643   // Get the address of the containing word.
1644   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1645                                     DAG.getConstant(-4, PtrVT));
1646
1647   // Get the number of bits that the word must be rotated left in order
1648   // to bring the field to the top bits of a GR32.
1649   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1650                                  DAG.getConstant(3, PtrVT));
1651   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1652
1653   // Get the complementing shift amount, for rotating a field in the top
1654   // bits back to its proper position.
1655   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1656                                     DAG.getConstant(0, WideVT), BitShift);
1657
1658   // Construct the ATOMIC_CMP_SWAPW node.
1659   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1660   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
1661                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
1662   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
1663                                              VTList, Ops, array_lengthof(Ops),
1664                                              NarrowVT, MMO);
1665   return AtomicOp;
1666 }
1667
1668 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
1669                                               SelectionDAG &DAG) const {
1670   MachineFunction &MF = DAG.getMachineFunction();
1671   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1672   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
1673                             SystemZ::R15D, Op.getValueType());
1674 }
1675
1676 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
1677                                                  SelectionDAG &DAG) const {
1678   MachineFunction &MF = DAG.getMachineFunction();
1679   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1680   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
1681                           SystemZ::R15D, Op.getOperand(1));
1682 }
1683
1684 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
1685                                               SelectionDAG &DAG) const {
1686   switch (Op.getOpcode()) {
1687   case ISD::BR_CC:
1688     return lowerBR_CC(Op, DAG);
1689   case ISD::SELECT_CC:
1690     return lowerSELECT_CC(Op, DAG);
1691   case ISD::GlobalAddress:
1692     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
1693   case ISD::GlobalTLSAddress:
1694     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
1695   case ISD::BlockAddress:
1696     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
1697   case ISD::JumpTable:
1698     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
1699   case ISD::ConstantPool:
1700     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
1701   case ISD::BITCAST:
1702     return lowerBITCAST(Op, DAG);
1703   case ISD::VASTART:
1704     return lowerVASTART(Op, DAG);
1705   case ISD::VACOPY:
1706     return lowerVACOPY(Op, DAG);
1707   case ISD::DYNAMIC_STACKALLOC:
1708     return lowerDYNAMIC_STACKALLOC(Op, DAG);
1709   case ISD::UMUL_LOHI:
1710     return lowerUMUL_LOHI(Op, DAG);
1711   case ISD::SDIVREM:
1712     return lowerSDIVREM(Op, DAG);
1713   case ISD::UDIVREM:
1714     return lowerUDIVREM(Op, DAG);
1715   case ISD::OR:
1716     return lowerOR(Op, DAG);
1717   case ISD::ATOMIC_SWAP:
1718     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_SWAPW);
1719   case ISD::ATOMIC_LOAD_ADD:
1720     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
1721   case ISD::ATOMIC_LOAD_SUB:
1722     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
1723   case ISD::ATOMIC_LOAD_AND:
1724     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
1725   case ISD::ATOMIC_LOAD_OR:
1726     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
1727   case ISD::ATOMIC_LOAD_XOR:
1728     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
1729   case ISD::ATOMIC_LOAD_NAND:
1730     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
1731   case ISD::ATOMIC_LOAD_MIN:
1732     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
1733   case ISD::ATOMIC_LOAD_MAX:
1734     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
1735   case ISD::ATOMIC_LOAD_UMIN:
1736     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
1737   case ISD::ATOMIC_LOAD_UMAX:
1738     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
1739   case ISD::ATOMIC_CMP_SWAP:
1740     return lowerATOMIC_CMP_SWAP(Op, DAG);
1741   case ISD::STACKSAVE:
1742     return lowerSTACKSAVE(Op, DAG);
1743   case ISD::STACKRESTORE:
1744     return lowerSTACKRESTORE(Op, DAG);
1745   default:
1746     llvm_unreachable("Unexpected node to lower");
1747   }
1748 }
1749
1750 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
1751 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
1752   switch (Opcode) {
1753     OPCODE(RET_FLAG);
1754     OPCODE(CALL);
1755     OPCODE(SIBCALL);
1756     OPCODE(PCREL_WRAPPER);
1757     OPCODE(CMP);
1758     OPCODE(UCMP);
1759     OPCODE(BR_CCMASK);
1760     OPCODE(SELECT_CCMASK);
1761     OPCODE(ADJDYNALLOC);
1762     OPCODE(EXTRACT_ACCESS);
1763     OPCODE(UMUL_LOHI64);
1764     OPCODE(SDIVREM64);
1765     OPCODE(UDIVREM32);
1766     OPCODE(UDIVREM64);
1767     OPCODE(MVC);
1768     OPCODE(CLC);
1769     OPCODE(STRCMP);
1770     OPCODE(STPCPY);
1771     OPCODE(SEARCH_STRING);
1772     OPCODE(IPM);
1773     OPCODE(ATOMIC_SWAPW);
1774     OPCODE(ATOMIC_LOADW_ADD);
1775     OPCODE(ATOMIC_LOADW_SUB);
1776     OPCODE(ATOMIC_LOADW_AND);
1777     OPCODE(ATOMIC_LOADW_OR);
1778     OPCODE(ATOMIC_LOADW_XOR);
1779     OPCODE(ATOMIC_LOADW_NAND);
1780     OPCODE(ATOMIC_LOADW_MIN);
1781     OPCODE(ATOMIC_LOADW_MAX);
1782     OPCODE(ATOMIC_LOADW_UMIN);
1783     OPCODE(ATOMIC_LOADW_UMAX);
1784     OPCODE(ATOMIC_CMP_SWAPW);
1785   }
1786   return NULL;
1787 #undef OPCODE
1788 }
1789
1790 //===----------------------------------------------------------------------===//
1791 // Custom insertion
1792 //===----------------------------------------------------------------------===//
1793
1794 // Create a new basic block after MBB.
1795 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
1796   MachineFunction &MF = *MBB->getParent();
1797   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
1798   MF.insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
1799   return NewMBB;
1800 }
1801
1802 // Split MBB after MI and return the new block (the one that contains
1803 // instructions after MI).
1804 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
1805                                           MachineBasicBlock *MBB) {
1806   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
1807   NewMBB->splice(NewMBB->begin(), MBB,
1808                  llvm::next(MachineBasicBlock::iterator(MI)),
1809                  MBB->end());
1810   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
1811   return NewMBB;
1812 }
1813
1814 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
1815 MachineBasicBlock *
1816 SystemZTargetLowering::emitSelect(MachineInstr *MI,
1817                                   MachineBasicBlock *MBB) const {
1818   const SystemZInstrInfo *TII = TM.getInstrInfo();
1819
1820   unsigned DestReg  = MI->getOperand(0).getReg();
1821   unsigned TrueReg  = MI->getOperand(1).getReg();
1822   unsigned FalseReg = MI->getOperand(2).getReg();
1823   unsigned CCValid  = MI->getOperand(3).getImm();
1824   unsigned CCMask   = MI->getOperand(4).getImm();
1825   DebugLoc DL       = MI->getDebugLoc();
1826
1827   MachineBasicBlock *StartMBB = MBB;
1828   MachineBasicBlock *JoinMBB  = splitBlockAfter(MI, MBB);
1829   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
1830
1831   //  StartMBB:
1832   //   BRC CCMask, JoinMBB
1833   //   # fallthrough to FalseMBB
1834   MBB = StartMBB;
1835   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
1836     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
1837   MBB->addSuccessor(JoinMBB);
1838   MBB->addSuccessor(FalseMBB);
1839
1840   //  FalseMBB:
1841   //   # fallthrough to JoinMBB
1842   MBB = FalseMBB;
1843   MBB->addSuccessor(JoinMBB);
1844
1845   //  JoinMBB:
1846   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
1847   //  ...
1848   MBB = JoinMBB;
1849   BuildMI(*MBB, MBB->begin(), DL, TII->get(SystemZ::PHI), DestReg)
1850     .addReg(TrueReg).addMBB(StartMBB)
1851     .addReg(FalseReg).addMBB(FalseMBB);
1852
1853   MI->eraseFromParent();
1854   return JoinMBB;
1855 }
1856
1857 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
1858 // StoreOpcode is the store to use and Invert says whether the store should
1859 // happen when the condition is false rather than true.  If a STORE ON
1860 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
1861 MachineBasicBlock *
1862 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
1863                                      MachineBasicBlock *MBB,
1864                                      unsigned StoreOpcode, unsigned STOCOpcode,
1865                                      bool Invert) const {
1866   const SystemZInstrInfo *TII = TM.getInstrInfo();
1867
1868   unsigned SrcReg     = MI->getOperand(0).getReg();
1869   MachineOperand Base = MI->getOperand(1);
1870   int64_t Disp        = MI->getOperand(2).getImm();
1871   unsigned IndexReg   = MI->getOperand(3).getReg();
1872   unsigned CCValid    = MI->getOperand(4).getImm();
1873   unsigned CCMask     = MI->getOperand(5).getImm();
1874   DebugLoc DL         = MI->getDebugLoc();
1875
1876   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
1877
1878   // Use STOCOpcode if possible.  We could use different store patterns in
1879   // order to avoid matching the index register, but the performance trade-offs
1880   // might be more complicated in that case.
1881   if (STOCOpcode && !IndexReg && TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
1882     if (Invert)
1883       CCMask ^= CCValid;
1884     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
1885       .addReg(SrcReg).addOperand(Base).addImm(Disp)
1886       .addImm(CCValid).addImm(CCMask);
1887     MI->eraseFromParent();
1888     return MBB;
1889   }
1890
1891   // Get the condition needed to branch around the store.
1892   if (!Invert)
1893     CCMask ^= CCValid;
1894
1895   MachineBasicBlock *StartMBB = MBB;
1896   MachineBasicBlock *JoinMBB  = splitBlockAfter(MI, MBB);
1897   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
1898
1899   //  StartMBB:
1900   //   BRC CCMask, JoinMBB
1901   //   # fallthrough to FalseMBB
1902   MBB = StartMBB;
1903   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
1904     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
1905   MBB->addSuccessor(JoinMBB);
1906   MBB->addSuccessor(FalseMBB);
1907
1908   //  FalseMBB:
1909   //   store %SrcReg, %Disp(%Index,%Base)
1910   //   # fallthrough to JoinMBB
1911   MBB = FalseMBB;
1912   BuildMI(MBB, DL, TII->get(StoreOpcode))
1913     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
1914   MBB->addSuccessor(JoinMBB);
1915
1916   MI->eraseFromParent();
1917   return JoinMBB;
1918 }
1919
1920 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
1921 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
1922 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
1923 // BitSize is the width of the field in bits, or 0 if this is a partword
1924 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
1925 // is one of the operands.  Invert says whether the field should be
1926 // inverted after performing BinOpcode (e.g. for NAND).
1927 MachineBasicBlock *
1928 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
1929                                             MachineBasicBlock *MBB,
1930                                             unsigned BinOpcode,
1931                                             unsigned BitSize,
1932                                             bool Invert) const {
1933   const SystemZInstrInfo *TII = TM.getInstrInfo();
1934   MachineFunction &MF = *MBB->getParent();
1935   MachineRegisterInfo &MRI = MF.getRegInfo();
1936   bool IsSubWord = (BitSize < 32);
1937
1938   // Extract the operands.  Base can be a register or a frame index.
1939   // Src2 can be a register or immediate.
1940   unsigned Dest        = MI->getOperand(0).getReg();
1941   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
1942   int64_t Disp         = MI->getOperand(2).getImm();
1943   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
1944   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
1945   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
1946   DebugLoc DL          = MI->getDebugLoc();
1947   if (IsSubWord)
1948     BitSize = MI->getOperand(6).getImm();
1949
1950   // Subword operations use 32-bit registers.
1951   const TargetRegisterClass *RC = (BitSize <= 32 ?
1952                                    &SystemZ::GR32BitRegClass :
1953                                    &SystemZ::GR64BitRegClass);
1954   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
1955   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
1956
1957   // Get the right opcodes for the displacement.
1958   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
1959   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
1960   assert(LOpcode && CSOpcode && "Displacement out of range");
1961
1962   // Create virtual registers for temporary results.
1963   unsigned OrigVal       = MRI.createVirtualRegister(RC);
1964   unsigned OldVal        = MRI.createVirtualRegister(RC);
1965   unsigned NewVal        = (BinOpcode || IsSubWord ?
1966                             MRI.createVirtualRegister(RC) : Src2.getReg());
1967   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
1968   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
1969
1970   // Insert a basic block for the main loop.
1971   MachineBasicBlock *StartMBB = MBB;
1972   MachineBasicBlock *DoneMBB  = splitBlockAfter(MI, MBB);
1973   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
1974
1975   //  StartMBB:
1976   //   ...
1977   //   %OrigVal = L Disp(%Base)
1978   //   # fall through to LoopMMB
1979   MBB = StartMBB;
1980   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
1981     .addOperand(Base).addImm(Disp).addReg(0);
1982   MBB->addSuccessor(LoopMBB);
1983
1984   //  LoopMBB:
1985   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
1986   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
1987   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
1988   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
1989   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
1990   //   JNE LoopMBB
1991   //   # fall through to DoneMMB
1992   MBB = LoopMBB;
1993   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
1994     .addReg(OrigVal).addMBB(StartMBB)
1995     .addReg(Dest).addMBB(LoopMBB);
1996   if (IsSubWord)
1997     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
1998       .addReg(OldVal).addReg(BitShift).addImm(0);
1999   if (Invert) {
2000     // Perform the operation normally and then invert every bit of the field.
2001     unsigned Tmp = MRI.createVirtualRegister(RC);
2002     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
2003       .addReg(RotatedOldVal).addOperand(Src2);
2004     if (BitSize < 32)
2005       // XILF with the upper BitSize bits set.
2006       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
2007         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
2008     else if (BitSize == 32)
2009       // XILF with every bit set.
2010       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
2011         .addReg(Tmp).addImm(~uint32_t(0));
2012     else {
2013       // Use LCGR and add -1 to the result, which is more compact than
2014       // an XILF, XILH pair.
2015       unsigned Tmp2 = MRI.createVirtualRegister(RC);
2016       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
2017       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
2018         .addReg(Tmp2).addImm(-1);
2019     }
2020   } else if (BinOpcode)
2021     // A simply binary operation.
2022     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
2023       .addReg(RotatedOldVal).addOperand(Src2);
2024   else if (IsSubWord)
2025     // Use RISBG to rotate Src2 into position and use it to replace the
2026     // field in RotatedOldVal.
2027     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
2028       .addReg(RotatedOldVal).addReg(Src2.getReg())
2029       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
2030   if (IsSubWord)
2031     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2032       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2033   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2034     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2035   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2036     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2037   MBB->addSuccessor(LoopMBB);
2038   MBB->addSuccessor(DoneMBB);
2039
2040   MI->eraseFromParent();
2041   return DoneMBB;
2042 }
2043
2044 // Implement EmitInstrWithCustomInserter for pseudo
2045 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
2046 // instruction that should be used to compare the current field with the
2047 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
2048 // for when the current field should be kept.  BitSize is the width of
2049 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
2050 MachineBasicBlock *
2051 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
2052                                             MachineBasicBlock *MBB,
2053                                             unsigned CompareOpcode,
2054                                             unsigned KeepOldMask,
2055                                             unsigned BitSize) const {
2056   const SystemZInstrInfo *TII = TM.getInstrInfo();
2057   MachineFunction &MF = *MBB->getParent();
2058   MachineRegisterInfo &MRI = MF.getRegInfo();
2059   bool IsSubWord = (BitSize < 32);
2060
2061   // Extract the operands.  Base can be a register or a frame index.
2062   unsigned Dest        = MI->getOperand(0).getReg();
2063   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2064   int64_t  Disp        = MI->getOperand(2).getImm();
2065   unsigned Src2        = MI->getOperand(3).getReg();
2066   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2067   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2068   DebugLoc DL          = MI->getDebugLoc();
2069   if (IsSubWord)
2070     BitSize = MI->getOperand(6).getImm();
2071
2072   // Subword operations use 32-bit registers.
2073   const TargetRegisterClass *RC = (BitSize <= 32 ?
2074                                    &SystemZ::GR32BitRegClass :
2075                                    &SystemZ::GR64BitRegClass);
2076   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2077   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2078
2079   // Get the right opcodes for the displacement.
2080   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2081   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2082   assert(LOpcode && CSOpcode && "Displacement out of range");
2083
2084   // Create virtual registers for temporary results.
2085   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2086   unsigned OldVal        = MRI.createVirtualRegister(RC);
2087   unsigned NewVal        = MRI.createVirtualRegister(RC);
2088   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2089   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
2090   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2091
2092   // Insert 3 basic blocks for the loop.
2093   MachineBasicBlock *StartMBB  = MBB;
2094   MachineBasicBlock *DoneMBB   = splitBlockAfter(MI, MBB);
2095   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
2096   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
2097   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
2098
2099   //  StartMBB:
2100   //   ...
2101   //   %OrigVal     = L Disp(%Base)
2102   //   # fall through to LoopMMB
2103   MBB = StartMBB;
2104   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2105     .addOperand(Base).addImm(Disp).addReg(0);
2106   MBB->addSuccessor(LoopMBB);
2107
2108   //  LoopMBB:
2109   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
2110   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2111   //   CompareOpcode %RotatedOldVal, %Src2
2112   //   BRC KeepOldMask, UpdateMBB
2113   MBB = LoopMBB;
2114   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2115     .addReg(OrigVal).addMBB(StartMBB)
2116     .addReg(Dest).addMBB(UpdateMBB);
2117   if (IsSubWord)
2118     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2119       .addReg(OldVal).addReg(BitShift).addImm(0);
2120   BuildMI(MBB, DL, TII->get(CompareOpcode))
2121     .addReg(RotatedOldVal).addReg(Src2);
2122   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2123     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
2124   MBB->addSuccessor(UpdateMBB);
2125   MBB->addSuccessor(UseAltMBB);
2126
2127   //  UseAltMBB:
2128   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
2129   //   # fall through to UpdateMMB
2130   MBB = UseAltMBB;
2131   if (IsSubWord)
2132     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
2133       .addReg(RotatedOldVal).addReg(Src2)
2134       .addImm(32).addImm(31 + BitSize).addImm(0);
2135   MBB->addSuccessor(UpdateMBB);
2136
2137   //  UpdateMBB:
2138   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
2139   //                        [ %RotatedAltVal, UseAltMBB ]
2140   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2141   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2142   //   JNE LoopMBB
2143   //   # fall through to DoneMMB
2144   MBB = UpdateMBB;
2145   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
2146     .addReg(RotatedOldVal).addMBB(LoopMBB)
2147     .addReg(RotatedAltVal).addMBB(UseAltMBB);
2148   if (IsSubWord)
2149     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2150       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2151   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2152     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2153   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2154     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2155   MBB->addSuccessor(LoopMBB);
2156   MBB->addSuccessor(DoneMBB);
2157
2158   MI->eraseFromParent();
2159   return DoneMBB;
2160 }
2161
2162 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
2163 // instruction MI.
2164 MachineBasicBlock *
2165 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
2166                                           MachineBasicBlock *MBB) const {
2167   const SystemZInstrInfo *TII = TM.getInstrInfo();
2168   MachineFunction &MF = *MBB->getParent();
2169   MachineRegisterInfo &MRI = MF.getRegInfo();
2170
2171   // Extract the operands.  Base can be a register or a frame index.
2172   unsigned Dest        = MI->getOperand(0).getReg();
2173   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2174   int64_t  Disp        = MI->getOperand(2).getImm();
2175   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
2176   unsigned OrigSwapVal = MI->getOperand(4).getReg();
2177   unsigned BitShift    = MI->getOperand(5).getReg();
2178   unsigned NegBitShift = MI->getOperand(6).getReg();
2179   int64_t  BitSize     = MI->getOperand(7).getImm();
2180   DebugLoc DL          = MI->getDebugLoc();
2181
2182   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
2183
2184   // Get the right opcodes for the displacement.
2185   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
2186   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
2187   assert(LOpcode && CSOpcode && "Displacement out of range");
2188
2189   // Create virtual registers for temporary results.
2190   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
2191   unsigned OldVal       = MRI.createVirtualRegister(RC);
2192   unsigned CmpVal       = MRI.createVirtualRegister(RC);
2193   unsigned SwapVal      = MRI.createVirtualRegister(RC);
2194   unsigned StoreVal     = MRI.createVirtualRegister(RC);
2195   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
2196   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
2197   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
2198
2199   // Insert 2 basic blocks for the loop.
2200   MachineBasicBlock *StartMBB = MBB;
2201   MachineBasicBlock *DoneMBB  = splitBlockAfter(MI, MBB);
2202   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2203   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
2204
2205   //  StartMBB:
2206   //   ...
2207   //   %OrigOldVal     = L Disp(%Base)
2208   //   # fall through to LoopMMB
2209   MBB = StartMBB;
2210   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
2211     .addOperand(Base).addImm(Disp).addReg(0);
2212   MBB->addSuccessor(LoopMBB);
2213
2214   //  LoopMBB:
2215   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
2216   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
2217   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
2218   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
2219   //                      ^^ The low BitSize bits contain the field
2220   //                         of interest.
2221   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
2222   //                      ^^ Replace the upper 32-BitSize bits of the
2223   //                         comparison value with those that we loaded,
2224   //                         so that we can use a full word comparison.
2225   //   CR %Dest, %RetryCmpVal
2226   //   JNE DoneMBB
2227   //   # Fall through to SetMBB
2228   MBB = LoopMBB;
2229   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2230     .addReg(OrigOldVal).addMBB(StartMBB)
2231     .addReg(RetryOldVal).addMBB(SetMBB);
2232   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
2233     .addReg(OrigCmpVal).addMBB(StartMBB)
2234     .addReg(RetryCmpVal).addMBB(SetMBB);
2235   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
2236     .addReg(OrigSwapVal).addMBB(StartMBB)
2237     .addReg(RetrySwapVal).addMBB(SetMBB);
2238   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
2239     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
2240   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
2241     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2242   BuildMI(MBB, DL, TII->get(SystemZ::CR))
2243     .addReg(Dest).addReg(RetryCmpVal);
2244   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2245     .addImm(SystemZ::CCMASK_ICMP)
2246     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
2247   MBB->addSuccessor(DoneMBB);
2248   MBB->addSuccessor(SetMBB);
2249
2250   //  SetMBB:
2251   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
2252   //                      ^^ Replace the upper 32-BitSize bits of the new
2253   //                         value with those that we loaded.
2254   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
2255   //                      ^^ Rotate the new field to its proper position.
2256   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
2257   //   JNE LoopMBB
2258   //   # fall through to ExitMMB
2259   MBB = SetMBB;
2260   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
2261     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2262   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
2263     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
2264   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
2265     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
2266   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2267     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2268   MBB->addSuccessor(LoopMBB);
2269   MBB->addSuccessor(DoneMBB);
2270
2271   MI->eraseFromParent();
2272   return DoneMBB;
2273 }
2274
2275 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
2276 // if the high register of the GR128 value must be cleared or false if
2277 // it's "don't care".  SubReg is subreg_odd32 when extending a GR32
2278 // and subreg_odd when extending a GR64.
2279 MachineBasicBlock *
2280 SystemZTargetLowering::emitExt128(MachineInstr *MI,
2281                                   MachineBasicBlock *MBB,
2282                                   bool ClearEven, unsigned SubReg) const {
2283   const SystemZInstrInfo *TII = TM.getInstrInfo();
2284   MachineFunction &MF = *MBB->getParent();
2285   MachineRegisterInfo &MRI = MF.getRegInfo();
2286   DebugLoc DL = MI->getDebugLoc();
2287
2288   unsigned Dest  = MI->getOperand(0).getReg();
2289   unsigned Src   = MI->getOperand(1).getReg();
2290   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2291
2292   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
2293   if (ClearEven) {
2294     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2295     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
2296
2297     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
2298       .addImm(0);
2299     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
2300       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_high);
2301     In128 = NewIn128;
2302   }
2303   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
2304     .addReg(In128).addReg(Src).addImm(SubReg);
2305
2306   MI->eraseFromParent();
2307   return MBB;
2308 }
2309
2310 MachineBasicBlock *
2311 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
2312                                          MachineBasicBlock *MBB,
2313                                          unsigned Opcode) const {
2314   const SystemZInstrInfo *TII = TM.getInstrInfo();
2315   DebugLoc DL = MI->getDebugLoc();
2316
2317   MachineOperand DestBase = MI->getOperand(0);
2318   uint64_t       DestDisp = MI->getOperand(1).getImm();
2319   MachineOperand SrcBase  = MI->getOperand(2);
2320   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
2321   uint64_t       Length   = MI->getOperand(4).getImm();
2322
2323   BuildMI(*MBB, MI, DL, TII->get(Opcode))
2324     .addOperand(DestBase).addImm(DestDisp).addImm(Length)
2325     .addOperand(SrcBase).addImm(SrcDisp);
2326
2327   MI->eraseFromParent();
2328   return MBB;
2329 }
2330
2331 // Decompose string pseudo-instruction MI into a loop that continually performs
2332 // Opcode until CC != 3.
2333 MachineBasicBlock *
2334 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
2335                                          MachineBasicBlock *MBB,
2336                                          unsigned Opcode) const {
2337   const SystemZInstrInfo *TII = TM.getInstrInfo();
2338   MachineFunction &MF = *MBB->getParent();
2339   MachineRegisterInfo &MRI = MF.getRegInfo();
2340   DebugLoc DL = MI->getDebugLoc();
2341
2342   uint64_t End1Reg   = MI->getOperand(0).getReg();
2343   uint64_t Start1Reg = MI->getOperand(1).getReg();
2344   uint64_t Start2Reg = MI->getOperand(2).getReg();
2345   uint64_t CharReg   = MI->getOperand(3).getReg();
2346
2347   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
2348   uint64_t This1Reg = MRI.createVirtualRegister(RC);
2349   uint64_t This2Reg = MRI.createVirtualRegister(RC);
2350   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
2351
2352   MachineBasicBlock *StartMBB = MBB;
2353   MachineBasicBlock *DoneMBB = splitBlockAfter(MI, MBB);
2354   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
2355
2356   //  StartMBB:
2357   //   # fall through to LoopMMB
2358   MBB->addSuccessor(LoopMBB);
2359
2360   //  LoopMBB:
2361   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
2362   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
2363   //   R0W = %CharReg
2364   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0W
2365   //   JO LoopMBB
2366   //   # fall through to DoneMMB
2367   //
2368   // The load of R0W can be hoisted by post-RA LICM.
2369   MBB = LoopMBB;
2370
2371   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
2372     .addReg(Start1Reg).addMBB(StartMBB)
2373     .addReg(End1Reg).addMBB(LoopMBB);
2374   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
2375     .addReg(Start2Reg).addMBB(StartMBB)
2376     .addReg(End2Reg).addMBB(LoopMBB);
2377   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0W).addReg(CharReg);
2378   BuildMI(MBB, DL, TII->get(Opcode))
2379     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
2380     .addReg(This1Reg).addReg(This2Reg);
2381   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2382     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
2383   MBB->addSuccessor(LoopMBB);
2384   MBB->addSuccessor(DoneMBB);
2385
2386   DoneMBB->addLiveIn(SystemZ::CC);
2387
2388   MI->eraseFromParent();
2389   return DoneMBB;
2390 }
2391
2392 MachineBasicBlock *SystemZTargetLowering::
2393 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
2394   switch (MI->getOpcode()) {
2395   case SystemZ::Select32:
2396   case SystemZ::SelectF32:
2397   case SystemZ::Select64:
2398   case SystemZ::SelectF64:
2399   case SystemZ::SelectF128:
2400     return emitSelect(MI, MBB);
2401
2402   case SystemZ::CondStore8_32:
2403     return emitCondStore(MI, MBB, SystemZ::STC32, 0, false);
2404   case SystemZ::CondStore8_32Inv:
2405     return emitCondStore(MI, MBB, SystemZ::STC32, 0, true);
2406   case SystemZ::CondStore16_32:
2407     return emitCondStore(MI, MBB, SystemZ::STH32, 0, false);
2408   case SystemZ::CondStore16_32Inv:
2409     return emitCondStore(MI, MBB, SystemZ::STH32, 0, true);
2410   case SystemZ::CondStore32_32:
2411     return emitCondStore(MI, MBB, SystemZ::ST32, SystemZ::STOC32, false);
2412   case SystemZ::CondStore32_32Inv:
2413     return emitCondStore(MI, MBB, SystemZ::ST32, SystemZ::STOC32, true);
2414   case SystemZ::CondStore8:
2415     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
2416   case SystemZ::CondStore8Inv:
2417     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
2418   case SystemZ::CondStore16:
2419     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
2420   case SystemZ::CondStore16Inv:
2421     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
2422   case SystemZ::CondStore32:
2423     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
2424   case SystemZ::CondStore32Inv:
2425     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
2426   case SystemZ::CondStore64:
2427     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
2428   case SystemZ::CondStore64Inv:
2429     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
2430   case SystemZ::CondStoreF32:
2431     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
2432   case SystemZ::CondStoreF32Inv:
2433     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
2434   case SystemZ::CondStoreF64:
2435     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
2436   case SystemZ::CondStoreF64Inv:
2437     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
2438
2439   case SystemZ::AEXT128_64:
2440     return emitExt128(MI, MBB, false, SystemZ::subreg_low);
2441   case SystemZ::ZEXT128_32:
2442     return emitExt128(MI, MBB, true, SystemZ::subreg_low32);
2443   case SystemZ::ZEXT128_64:
2444     return emitExt128(MI, MBB, true, SystemZ::subreg_low);
2445
2446   case SystemZ::ATOMIC_SWAPW:
2447     return emitAtomicLoadBinary(MI, MBB, 0, 0);
2448   case SystemZ::ATOMIC_SWAP_32:
2449     return emitAtomicLoadBinary(MI, MBB, 0, 32);
2450   case SystemZ::ATOMIC_SWAP_64:
2451     return emitAtomicLoadBinary(MI, MBB, 0, 64);
2452
2453   case SystemZ::ATOMIC_LOADW_AR:
2454     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
2455   case SystemZ::ATOMIC_LOADW_AFI:
2456     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
2457   case SystemZ::ATOMIC_LOAD_AR:
2458     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
2459   case SystemZ::ATOMIC_LOAD_AHI:
2460     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
2461   case SystemZ::ATOMIC_LOAD_AFI:
2462     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
2463   case SystemZ::ATOMIC_LOAD_AGR:
2464     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
2465   case SystemZ::ATOMIC_LOAD_AGHI:
2466     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
2467   case SystemZ::ATOMIC_LOAD_AGFI:
2468     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
2469
2470   case SystemZ::ATOMIC_LOADW_SR:
2471     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
2472   case SystemZ::ATOMIC_LOAD_SR:
2473     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
2474   case SystemZ::ATOMIC_LOAD_SGR:
2475     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
2476
2477   case SystemZ::ATOMIC_LOADW_NR:
2478     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
2479   case SystemZ::ATOMIC_LOADW_NILH:
2480     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0);
2481   case SystemZ::ATOMIC_LOAD_NR:
2482     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
2483   case SystemZ::ATOMIC_LOAD_NILL32:
2484     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32);
2485   case SystemZ::ATOMIC_LOAD_NILH32:
2486     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32);
2487   case SystemZ::ATOMIC_LOAD_NILF32:
2488     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32);
2489   case SystemZ::ATOMIC_LOAD_NGR:
2490     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
2491   case SystemZ::ATOMIC_LOAD_NILL:
2492     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64);
2493   case SystemZ::ATOMIC_LOAD_NILH:
2494     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64);
2495   case SystemZ::ATOMIC_LOAD_NIHL:
2496     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64);
2497   case SystemZ::ATOMIC_LOAD_NIHH:
2498     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64);
2499   case SystemZ::ATOMIC_LOAD_NILF:
2500     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64);
2501   case SystemZ::ATOMIC_LOAD_NIHF:
2502     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64);
2503
2504   case SystemZ::ATOMIC_LOADW_OR:
2505     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
2506   case SystemZ::ATOMIC_LOADW_OILH:
2507     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 0);
2508   case SystemZ::ATOMIC_LOAD_OR:
2509     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
2510   case SystemZ::ATOMIC_LOAD_OILL32:
2511     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL32, 32);
2512   case SystemZ::ATOMIC_LOAD_OILH32:
2513     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 32);
2514   case SystemZ::ATOMIC_LOAD_OILF32:
2515     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF32, 32);
2516   case SystemZ::ATOMIC_LOAD_OGR:
2517     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
2518   case SystemZ::ATOMIC_LOAD_OILL:
2519     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 64);
2520   case SystemZ::ATOMIC_LOAD_OILH:
2521     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 64);
2522   case SystemZ::ATOMIC_LOAD_OIHL:
2523     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL, 64);
2524   case SystemZ::ATOMIC_LOAD_OIHH:
2525     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH, 64);
2526   case SystemZ::ATOMIC_LOAD_OILF:
2527     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 64);
2528   case SystemZ::ATOMIC_LOAD_OIHF:
2529     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF, 64);
2530
2531   case SystemZ::ATOMIC_LOADW_XR:
2532     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
2533   case SystemZ::ATOMIC_LOADW_XILF:
2534     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 0);
2535   case SystemZ::ATOMIC_LOAD_XR:
2536     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
2537   case SystemZ::ATOMIC_LOAD_XILF32:
2538     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 32);
2539   case SystemZ::ATOMIC_LOAD_XGR:
2540     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
2541   case SystemZ::ATOMIC_LOAD_XILF:
2542     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 64);
2543   case SystemZ::ATOMIC_LOAD_XIHF:
2544     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF, 64);
2545
2546   case SystemZ::ATOMIC_LOADW_NRi:
2547     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
2548   case SystemZ::ATOMIC_LOADW_NILHi:
2549     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0, true);
2550   case SystemZ::ATOMIC_LOAD_NRi:
2551     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
2552   case SystemZ::ATOMIC_LOAD_NILL32i:
2553     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32, true);
2554   case SystemZ::ATOMIC_LOAD_NILH32i:
2555     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32, true);
2556   case SystemZ::ATOMIC_LOAD_NILF32i:
2557     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32, true);
2558   case SystemZ::ATOMIC_LOAD_NGRi:
2559     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
2560   case SystemZ::ATOMIC_LOAD_NILLi:
2561     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64, true);
2562   case SystemZ::ATOMIC_LOAD_NILHi:
2563     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64, true);
2564   case SystemZ::ATOMIC_LOAD_NIHLi:
2565     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64, true);
2566   case SystemZ::ATOMIC_LOAD_NIHHi:
2567     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64, true);
2568   case SystemZ::ATOMIC_LOAD_NILFi:
2569     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64, true);
2570   case SystemZ::ATOMIC_LOAD_NIHFi:
2571     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64, true);
2572
2573   case SystemZ::ATOMIC_LOADW_MIN:
2574     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2575                                 SystemZ::CCMASK_CMP_LE, 0);
2576   case SystemZ::ATOMIC_LOAD_MIN_32:
2577     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2578                                 SystemZ::CCMASK_CMP_LE, 32);
2579   case SystemZ::ATOMIC_LOAD_MIN_64:
2580     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
2581                                 SystemZ::CCMASK_CMP_LE, 64);
2582
2583   case SystemZ::ATOMIC_LOADW_MAX:
2584     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2585                                 SystemZ::CCMASK_CMP_GE, 0);
2586   case SystemZ::ATOMIC_LOAD_MAX_32:
2587     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
2588                                 SystemZ::CCMASK_CMP_GE, 32);
2589   case SystemZ::ATOMIC_LOAD_MAX_64:
2590     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
2591                                 SystemZ::CCMASK_CMP_GE, 64);
2592
2593   case SystemZ::ATOMIC_LOADW_UMIN:
2594     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2595                                 SystemZ::CCMASK_CMP_LE, 0);
2596   case SystemZ::ATOMIC_LOAD_UMIN_32:
2597     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2598                                 SystemZ::CCMASK_CMP_LE, 32);
2599   case SystemZ::ATOMIC_LOAD_UMIN_64:
2600     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
2601                                 SystemZ::CCMASK_CMP_LE, 64);
2602
2603   case SystemZ::ATOMIC_LOADW_UMAX:
2604     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2605                                 SystemZ::CCMASK_CMP_GE, 0);
2606   case SystemZ::ATOMIC_LOAD_UMAX_32:
2607     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
2608                                 SystemZ::CCMASK_CMP_GE, 32);
2609   case SystemZ::ATOMIC_LOAD_UMAX_64:
2610     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
2611                                 SystemZ::CCMASK_CMP_GE, 64);
2612
2613   case SystemZ::ATOMIC_CMP_SWAPW:
2614     return emitAtomicCmpSwapW(MI, MBB);
2615   case SystemZ::MVCWrapper:
2616     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
2617   case SystemZ::CLCWrapper:
2618     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
2619   case SystemZ::CLSTLoop:
2620     return emitStringWrapper(MI, MBB, SystemZ::CLST);
2621   case SystemZ::MVSTLoop:
2622     return emitStringWrapper(MI, MBB, SystemZ::MVST);
2623   case SystemZ::SRSTLoop:
2624     return emitStringWrapper(MI, MBB, SystemZ::SRST);
2625   default:
2626     llvm_unreachable("Unexpected instr type to insert");
2627   }
2628 }