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