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