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