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