Expand few nodes until someone will be crazy enough to implement them natively :)
[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 "SystemZ.h"
18 #include "SystemZTargetMachine.h"
19 #include "SystemZSubtarget.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/ADT/VectorExtras.h"
38 using namespace llvm;
39
40 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm) :
41   TargetLowering(tm, new TargetLoweringObjectFileELF()),
42   Subtarget(*tm.getSubtargetImpl()), TM(tm) {
43
44   RegInfo = TM.getRegisterInfo();
45
46   // Set up the register classes.
47   addRegisterClass(MVT::i32,  SystemZ::GR32RegisterClass);
48   addRegisterClass(MVT::i64,  SystemZ::GR64RegisterClass);
49   addRegisterClass(MVT::v2i32,SystemZ::GR64PRegisterClass);
50   addRegisterClass(MVT::v2i64,SystemZ::GR128RegisterClass);
51
52   if (!UseSoftFloat) {
53     addRegisterClass(MVT::f32, SystemZ::FP32RegisterClass);
54     addRegisterClass(MVT::f64, SystemZ::FP64RegisterClass);
55
56     addLegalFPImmediate(APFloat(+0.0));  // lzer
57     addLegalFPImmediate(APFloat(+0.0f)); // lzdr
58     addLegalFPImmediate(APFloat(-0.0));  // lzer + lner
59     addLegalFPImmediate(APFloat(-0.0f)); // lzdr + lndr
60   }
61
62   // Compute derived properties from the register classes
63   computeRegisterProperties();
64
65   // Set shifts properties
66   setShiftAmountType(MVT::i64);
67
68   // Provide all sorts of operation actions
69   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
70   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
71   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
72
73   setLoadExtAction(ISD::SEXTLOAD, MVT::f32, Expand);
74   setLoadExtAction(ISD::ZEXTLOAD, MVT::f32, Expand);
75   setLoadExtAction(ISD::EXTLOAD,  MVT::f32, Expand);
76
77   setLoadExtAction(ISD::SEXTLOAD, MVT::f64, Expand);
78   setLoadExtAction(ISD::ZEXTLOAD, MVT::f64, Expand);
79   setLoadExtAction(ISD::EXTLOAD,  MVT::f64, Expand);
80
81   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
82   setSchedulingPreference(SchedulingForLatency);
83   setBooleanContents(ZeroOrOneBooleanContent);
84
85   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
86   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
87   setOperationAction(ISD::BR_CC,            MVT::i32, Custom);
88   setOperationAction(ISD::BR_CC,            MVT::i64, Custom);
89   setOperationAction(ISD::BR_CC,            MVT::f32, Custom);
90   setOperationAction(ISD::BR_CC,            MVT::f64, Custom);
91   setOperationAction(ISD::ConstantPool,     MVT::i32, Custom);
92   setOperationAction(ISD::ConstantPool,     MVT::i64, Custom);
93   setOperationAction(ISD::GlobalAddress,    MVT::i64, Custom);
94   setOperationAction(ISD::JumpTable,        MVT::i64, Custom);
95   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
96
97   setOperationAction(ISD::SDIV,             MVT::i32, Expand);
98   setOperationAction(ISD::UDIV,             MVT::i32, Expand);
99   setOperationAction(ISD::SDIV,             MVT::i64, Expand);
100   setOperationAction(ISD::UDIV,             MVT::i64, Expand);
101   setOperationAction(ISD::SREM,             MVT::i32, Expand);
102   setOperationAction(ISD::UREM,             MVT::i32, Expand);
103   setOperationAction(ISD::SREM,             MVT::i64, Expand);
104   setOperationAction(ISD::UREM,             MVT::i64, Expand);
105
106   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
107
108   setOperationAction(ISD::CTPOP,            MVT::i32, Expand);
109   setOperationAction(ISD::CTPOP,            MVT::i64, Expand);
110   setOperationAction(ISD::CTTZ,             MVT::i32, Expand);
111   setOperationAction(ISD::CTTZ,             MVT::i64, Expand);
112   setOperationAction(ISD::CTLZ,             MVT::i32, Promote);
113   setOperationAction(ISD::CTLZ,             MVT::i64, Legal);
114
115   // FIXME: Can we lower these 2 efficiently?
116   setOperationAction(ISD::SETCC,            MVT::i32, Expand);
117   setOperationAction(ISD::SETCC,            MVT::i64, Expand);
118   setOperationAction(ISD::SETCC,            MVT::f32, Expand);
119   setOperationAction(ISD::SETCC,            MVT::f64, Expand);
120   setOperationAction(ISD::SELECT,           MVT::i32, Expand);
121   setOperationAction(ISD::SELECT,           MVT::i64, Expand);
122   setOperationAction(ISD::SELECT,           MVT::f32, Expand);
123   setOperationAction(ISD::SELECT,           MVT::f64, Expand);
124   setOperationAction(ISD::SELECT_CC,        MVT::i32, Custom);
125   setOperationAction(ISD::SELECT_CC,        MVT::i64, Custom);
126   setOperationAction(ISD::SELECT_CC,        MVT::f32, Custom);
127   setOperationAction(ISD::SELECT_CC,        MVT::f64, Custom);
128
129   setOperationAction(ISD::MULHS,            MVT::i64, Expand);
130   setOperationAction(ISD::SMUL_LOHI,        MVT::i64, Expand);
131
132   // FIXME: Can we support these natively?
133   setOperationAction(ISD::UMUL_LOHI,        MVT::i64, Expand);
134   setOperationAction(ISD::SRL_PARTS,        MVT::i64, Expand);
135   setOperationAction(ISD::SHL_PARTS,        MVT::i64, Expand);
136   setOperationAction(ISD::SRA_PARTS,        MVT::i64, Expand);
137
138   // Lower some FP stuff
139   setOperationAction(ISD::FSIN,             MVT::f32, Expand);
140   setOperationAction(ISD::FSIN,             MVT::f64, Expand);
141   setOperationAction(ISD::FCOS,             MVT::f32, Expand);
142   setOperationAction(ISD::FCOS,             MVT::f64, Expand);
143   setOperationAction(ISD::FREM,             MVT::f32, Expand);
144   setOperationAction(ISD::FREM,             MVT::f64, Expand);
145
146   // We have only 64-bit bitconverts
147   setOperationAction(ISD::BIT_CONVERT,      MVT::f32, Expand);
148   setOperationAction(ISD::BIT_CONVERT,      MVT::i32, Expand);
149
150   setOperationAction(ISD::UINT_TO_FP,       MVT::i32, Expand);
151   setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Expand);
152   setOperationAction(ISD::FP_TO_UINT,       MVT::i32, Expand);
153   setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Expand);
154
155   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
156 }
157
158 SDValue SystemZTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
159   switch (Op.getOpcode()) {
160   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
161   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
162   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
163   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
164   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
165   default:
166     llvm_unreachable("Should not custom lower this!");
167     return SDValue();
168   }
169 }
170
171 //===----------------------------------------------------------------------===//
172 //                       SystemZ Inline Assembly Support
173 //===----------------------------------------------------------------------===//
174
175 /// getConstraintType - Given a constraint letter, return the type of
176 /// constraint it is for this target.
177 TargetLowering::ConstraintType
178 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
179   if (Constraint.size() == 1) {
180     switch (Constraint[0]) {
181     case 'r':
182       return C_RegisterClass;
183     default:
184       break;
185     }
186   }
187   return TargetLowering::getConstraintType(Constraint);
188 }
189
190 std::pair<unsigned, const TargetRegisterClass*>
191 SystemZTargetLowering::
192 getRegForInlineAsmConstraint(const std::string &Constraint,
193                              EVT VT) const {
194   if (Constraint.size() == 1) {
195     // GCC Constraint Letters
196     switch (Constraint[0]) {
197     default: break;
198     case 'r':   // GENERAL_REGS
199       if (VT == MVT::i32)
200         return std::make_pair(0U, SystemZ::GR32RegisterClass);
201       else if (VT == MVT::i128)
202         return std::make_pair(0U, SystemZ::GR128RegisterClass);
203
204       return std::make_pair(0U, SystemZ::GR64RegisterClass);
205     }
206   }
207
208   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
209 }
210
211 //===----------------------------------------------------------------------===//
212 //                      Calling Convention Implementation
213 //===----------------------------------------------------------------------===//
214
215 #include "SystemZGenCallingConv.inc"
216
217 SDValue
218 SystemZTargetLowering::LowerFormalArguments(SDValue Chain,
219                                             unsigned CallConv,
220                                             bool isVarArg,
221                                             const SmallVectorImpl<ISD::InputArg>
222                                               &Ins,
223                                             DebugLoc dl,
224                                             SelectionDAG &DAG,
225                                             SmallVectorImpl<SDValue> &InVals) {
226
227   switch (CallConv) {
228   default:
229     llvm_unreachable("Unsupported calling convention");
230   case CallingConv::C:
231   case CallingConv::Fast:
232     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
233   }
234 }
235
236 SDValue
237 SystemZTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
238                                  unsigned CallConv, bool isVarArg,
239                                  bool isTailCall,
240                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
241                                  const SmallVectorImpl<ISD::InputArg> &Ins,
242                                  DebugLoc dl, SelectionDAG &DAG,
243                                  SmallVectorImpl<SDValue> &InVals) {
244
245   switch (CallConv) {
246   default:
247     llvm_unreachable("Unsupported calling convention");
248   case CallingConv::Fast:
249   case CallingConv::C:
250     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
251                           Outs, Ins, dl, DAG, InVals);
252   }
253 }
254
255 /// LowerCCCArguments - transform physical registers into virtual registers and
256 /// generate load operations for arguments places on the stack.
257 // FIXME: struct return stuff
258 // FIXME: varargs
259 SDValue
260 SystemZTargetLowering::LowerCCCArguments(SDValue Chain,
261                                          unsigned CallConv,
262                                          bool isVarArg,
263                                          const SmallVectorImpl<ISD::InputArg>
264                                            &Ins,
265                                          DebugLoc dl,
266                                          SelectionDAG &DAG,
267                                          SmallVectorImpl<SDValue> &InVals) {
268
269   MachineFunction &MF = DAG.getMachineFunction();
270   MachineFrameInfo *MFI = MF.getFrameInfo();
271   MachineRegisterInfo &RegInfo = MF.getRegInfo();
272
273   // Assign locations to all of the incoming arguments.
274   SmallVector<CCValAssign, 16> ArgLocs;
275   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
276                  ArgLocs, *DAG.getContext());
277   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
278
279   if (isVarArg)
280     llvm_report_error("Varargs not supported yet");
281
282   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
283     SDValue ArgValue;
284     CCValAssign &VA = ArgLocs[i];
285     EVT LocVT = VA.getLocVT();
286     if (VA.isRegLoc()) {
287       // Arguments passed in registers
288       TargetRegisterClass *RC;
289       switch (LocVT.getSimpleVT().SimpleTy) {
290       default:
291 #ifndef NDEBUG
292         cerr << "LowerFormalArguments Unhandled argument type: "
293              << LocVT.getSimpleVT().SimpleTy
294              << "\n";
295 #endif
296         llvm_unreachable(0);
297       case MVT::i64:
298         RC = SystemZ::GR64RegisterClass;
299         break;
300       case MVT::f32:
301         RC = SystemZ::FP32RegisterClass;
302         break;
303       case MVT::f64:
304         RC = SystemZ::FP64RegisterClass;
305         break;
306       }
307
308       unsigned VReg = RegInfo.createVirtualRegister(RC);
309       RegInfo.addLiveIn(VA.getLocReg(), VReg);
310       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
311     } else {
312       // Sanity check
313       assert(VA.isMemLoc());
314
315       // Create the nodes corresponding to a load from this parameter slot.
316       // Create the frame index object for this incoming parameter...
317       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits()/8,
318                                       VA.getLocMemOffset());
319
320       // Create the SelectionDAG nodes corresponding to a load
321       // from this parameter
322       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
323       ArgValue = DAG.getLoad(LocVT, dl, Chain, FIN,
324                              PseudoSourceValue::getFixedStack(FI), 0);
325     }
326
327     // If this is an 8/16/32-bit value, it is really passed promoted to 64
328     // bits. Insert an assert[sz]ext to capture this, then truncate to the
329     // right size.
330     if (VA.getLocInfo() == CCValAssign::SExt)
331       ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
332                              DAG.getValueType(VA.getValVT()));
333     else if (VA.getLocInfo() == CCValAssign::ZExt)
334       ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
335                              DAG.getValueType(VA.getValVT()));
336
337     if (VA.getLocInfo() != CCValAssign::Full)
338       ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
339
340     InVals.push_back(ArgValue);
341   }
342
343   return Chain;
344 }
345
346 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
347 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
348 /// TODO: sret.
349 SDValue
350 SystemZTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
351                                       unsigned CallConv, bool isVarArg,
352                                       bool isTailCall,
353                                       const SmallVectorImpl<ISD::OutputArg>
354                                         &Outs,
355                                       const SmallVectorImpl<ISD::InputArg> &Ins,
356                                       DebugLoc dl, SelectionDAG &DAG,
357                                       SmallVectorImpl<SDValue> &InVals) {
358
359   MachineFunction &MF = DAG.getMachineFunction();
360
361   // Offset to first argument stack slot.
362   const unsigned FirstArgOffset = 160;
363
364   // Analyze operands of the call, assigning locations to each operand.
365   SmallVector<CCValAssign, 16> ArgLocs;
366   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
367                  ArgLocs, *DAG.getContext());
368
369   CCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
370
371   // Get a count of how many bytes are to be pushed on the stack.
372   unsigned NumBytes = CCInfo.getNextStackOffset();
373
374   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
375                                                       getPointerTy(), true));
376
377   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
378   SmallVector<SDValue, 12> MemOpChains;
379   SDValue StackPtr;
380
381   // Walk the register/memloc assignments, inserting copies/loads.
382   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
383     CCValAssign &VA = ArgLocs[i];
384
385     SDValue Arg = Outs[i].Val;
386
387     // Promote the value if needed.
388     switch (VA.getLocInfo()) {
389       default: assert(0 && "Unknown loc info!");
390       case CCValAssign::Full: break;
391       case CCValAssign::SExt:
392         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
393         break;
394       case CCValAssign::ZExt:
395         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
396         break;
397       case CCValAssign::AExt:
398         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
399         break;
400     }
401
402     // Arguments that can be passed on register must be kept at RegsToPass
403     // vector
404     if (VA.isRegLoc()) {
405       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
406     } else {
407       assert(VA.isMemLoc());
408
409       if (StackPtr.getNode() == 0)
410         StackPtr =
411           DAG.getCopyFromReg(Chain, dl,
412                              (RegInfo->hasFP(MF) ?
413                               SystemZ::R11D : SystemZ::R15D),
414                              getPointerTy());
415
416       unsigned Offset = FirstArgOffset + VA.getLocMemOffset();
417       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
418                                    StackPtr,
419                                    DAG.getIntPtrConstant(Offset));
420
421       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
422                                          PseudoSourceValue::getStack(), Offset));
423     }
424   }
425
426   // Transform all store nodes into one single node because all store nodes are
427   // independent of each other.
428   if (!MemOpChains.empty())
429     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
430                         &MemOpChains[0], MemOpChains.size());
431
432   // Build a sequence of copy-to-reg nodes chained together with token chain and
433   // flag operands which copy the outgoing args into registers.  The InFlag in
434   // necessary since all emited instructions must be stuck together.
435   SDValue InFlag;
436   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
437     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
438                              RegsToPass[i].second, InFlag);
439     InFlag = Chain.getValue(1);
440   }
441
442   // If the callee is a GlobalAddress node (quite common, every direct call is)
443   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
444   // Likewise ExternalSymbol -> TargetExternalSymbol.
445   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
446     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
447   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
448     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
449
450   // Returns a chain & a flag for retval copy to use.
451   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
452   SmallVector<SDValue, 8> Ops;
453   Ops.push_back(Chain);
454   Ops.push_back(Callee);
455
456   // Add argument registers to the end of the list so that they are
457   // known live into the call.
458   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
459     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
460                                   RegsToPass[i].second.getValueType()));
461
462   if (InFlag.getNode())
463     Ops.push_back(InFlag);
464
465   Chain = DAG.getNode(SystemZISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
466   InFlag = Chain.getValue(1);
467
468   // Create the CALLSEQ_END node.
469   Chain = DAG.getCALLSEQ_END(Chain,
470                              DAG.getConstant(NumBytes, getPointerTy(), true),
471                              DAG.getConstant(0, getPointerTy(), true),
472                              InFlag);
473   InFlag = Chain.getValue(1);
474
475   // Handle result values, copying them out of physregs into vregs that we
476   // return.
477   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
478                          DAG, InVals);
479 }
480
481 /// LowerCallResult - Lower the result values of a call into the
482 /// appropriate copies out of appropriate physical registers.
483 ///
484 SDValue
485 SystemZTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
486                                        unsigned CallConv, bool isVarArg,
487                                        const SmallVectorImpl<ISD::InputArg>
488                                          &Ins,
489                                        DebugLoc dl, SelectionDAG &DAG,
490                                        SmallVectorImpl<SDValue> &InVals) {
491
492   // Assign locations to each value returned by this call.
493   SmallVector<CCValAssign, 16> RVLocs;
494   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
495                  *DAG.getContext());
496
497   CCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
498
499   // Copy all of the result registers out of their specified physreg.
500   for (unsigned i = 0; i != RVLocs.size(); ++i) {
501     CCValAssign &VA = RVLocs[i];
502
503     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
504                                VA.getLocVT(), InFlag).getValue(1);
505     SDValue RetValue = Chain.getValue(0);
506     InFlag = Chain.getValue(2);
507
508     // If this is an 8/16/32-bit value, it is really passed promoted to 64
509     // bits. Insert an assert[sz]ext to capture this, then truncate to the
510     // right size.
511     if (VA.getLocInfo() == CCValAssign::SExt)
512       RetValue = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), RetValue,
513                              DAG.getValueType(VA.getValVT()));
514     else if (VA.getLocInfo() == CCValAssign::ZExt)
515       RetValue = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), RetValue,
516                              DAG.getValueType(VA.getValVT()));
517
518     if (VA.getLocInfo() != CCValAssign::Full)
519       RetValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), RetValue);
520
521     InVals.push_back(RetValue);
522   }
523
524   return Chain;
525 }
526
527
528 SDValue
529 SystemZTargetLowering::LowerReturn(SDValue Chain,
530                                    unsigned CallConv, bool isVarArg,
531                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
532                                    DebugLoc dl, SelectionDAG &DAG) {
533
534   // CCValAssign - represent the assignment of the return value to a location
535   SmallVector<CCValAssign, 16> RVLocs;
536
537   // CCState - Info about the registers and stack slot.
538   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
539                  RVLocs, *DAG.getContext());
540
541   // Analize return values.
542   CCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
543
544   // If this is the first return lowered for this function, add the regs to the
545   // liveout set for the function.
546   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
547     for (unsigned i = 0; i != RVLocs.size(); ++i)
548       if (RVLocs[i].isRegLoc())
549         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
550   }
551
552   SDValue Flag;
553
554   // Copy the result values into the output registers.
555   for (unsigned i = 0; i != RVLocs.size(); ++i) {
556     CCValAssign &VA = RVLocs[i];
557     SDValue ResValue = Outs[i].Val;
558     assert(VA.isRegLoc() && "Can only return in registers!");
559
560     // If this is an 8/16/32-bit value, it is really should be passed promoted
561     // to 64 bits.
562     if (VA.getLocInfo() == CCValAssign::SExt)
563       ResValue = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ResValue);
564     else if (VA.getLocInfo() == CCValAssign::ZExt)
565       ResValue = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ResValue);
566     else if (VA.getLocInfo() == CCValAssign::AExt)
567       ResValue = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ResValue);
568
569     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ResValue, Flag);
570
571     // Guarantee that all emitted copies are stuck together,
572     // avoiding something bad.
573     Flag = Chain.getValue(1);
574   }
575
576   if (Flag.getNode())
577     return DAG.getNode(SystemZISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
578
579   // Return Void
580   return DAG.getNode(SystemZISD::RET_FLAG, dl, MVT::Other, Chain);
581 }
582
583 SDValue SystemZTargetLowering::EmitCmp(SDValue LHS, SDValue RHS,
584                                        ISD::CondCode CC, SDValue &SystemZCC,
585                                        SelectionDAG &DAG) {
586   // FIXME: Emit a test if RHS is zero
587
588   bool isUnsigned = false;
589   SystemZCC::CondCodes TCC;
590   switch (CC) {
591   default:
592     llvm_unreachable("Invalid integer condition!");
593   case ISD::SETEQ:
594   case ISD::SETOEQ:
595     TCC = SystemZCC::E;
596     break;
597   case ISD::SETUEQ:
598     TCC = SystemZCC::NLH;
599     break;
600   case ISD::SETNE:
601   case ISD::SETONE:
602     TCC = SystemZCC::NE;
603     break;
604   case ISD::SETUNE:
605     TCC = SystemZCC::LH;
606     break;
607   case ISD::SETO:
608     TCC = SystemZCC::O;
609     break;
610   case ISD::SETUO:
611     TCC = SystemZCC::NO;
612     break;
613   case ISD::SETULE:
614     if (LHS.getValueType().isFloatingPoint()) {
615       TCC = SystemZCC::NH;
616       break;
617     }
618     isUnsigned = true;   // FALLTHROUGH
619   case ISD::SETLE:
620   case ISD::SETOLE:
621     TCC = SystemZCC::LE;
622     break;
623   case ISD::SETUGE:
624     if (LHS.getValueType().isFloatingPoint()) {
625       TCC = SystemZCC::NL;
626       break;
627     }
628     isUnsigned = true;   // FALLTHROUGH
629   case ISD::SETGE:
630   case ISD::SETOGE:
631     TCC = SystemZCC::HE;
632     break;
633   case ISD::SETUGT:
634     if (LHS.getValueType().isFloatingPoint()) {
635       TCC = SystemZCC::NLE;
636       break;
637     }
638     isUnsigned = true;  // FALLTHROUGH
639   case ISD::SETGT:
640   case ISD::SETOGT:
641     TCC = SystemZCC::H;
642     break;
643   case ISD::SETULT:
644     if (LHS.getValueType().isFloatingPoint()) {
645       TCC = SystemZCC::NHE;
646       break;
647     }
648     isUnsigned = true;  // FALLTHROUGH
649   case ISD::SETLT:
650   case ISD::SETOLT:
651     TCC = SystemZCC::L;
652     break;
653   }
654
655   SystemZCC = DAG.getConstant(TCC, MVT::i32);
656
657   DebugLoc dl = LHS.getDebugLoc();
658   return DAG.getNode((isUnsigned ? SystemZISD::UCMP : SystemZISD::CMP),
659                      dl, MVT::Flag, LHS, RHS);
660 }
661
662
663 SDValue SystemZTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
664   SDValue Chain = Op.getOperand(0);
665   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
666   SDValue LHS   = Op.getOperand(2);
667   SDValue RHS   = Op.getOperand(3);
668   SDValue Dest  = Op.getOperand(4);
669   DebugLoc dl   = Op.getDebugLoc();
670
671   SDValue SystemZCC;
672   SDValue Flag = EmitCmp(LHS, RHS, CC, SystemZCC, DAG);
673   return DAG.getNode(SystemZISD::BRCOND, dl, Op.getValueType(),
674                      Chain, Dest, SystemZCC, Flag);
675 }
676
677 SDValue SystemZTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
678   SDValue LHS    = Op.getOperand(0);
679   SDValue RHS    = Op.getOperand(1);
680   SDValue TrueV  = Op.getOperand(2);
681   SDValue FalseV = Op.getOperand(3);
682   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
683   DebugLoc dl   = Op.getDebugLoc();
684
685   SDValue SystemZCC;
686   SDValue Flag = EmitCmp(LHS, RHS, CC, SystemZCC, DAG);
687
688   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
689   SmallVector<SDValue, 4> Ops;
690   Ops.push_back(TrueV);
691   Ops.push_back(FalseV);
692   Ops.push_back(SystemZCC);
693   Ops.push_back(Flag);
694
695   return DAG.getNode(SystemZISD::SELECT, dl, VTs, &Ops[0], Ops.size());
696 }
697
698 SDValue SystemZTargetLowering::LowerGlobalAddress(SDValue Op,
699                                                   SelectionDAG &DAG) {
700   DebugLoc dl = Op.getDebugLoc();
701   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
702   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
703
704   bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
705   bool ExtraLoadRequired =
706     Subtarget.GVRequiresExtraLoad(GV, getTargetMachine(), false);
707
708   SDValue Result;
709   if (!IsPic && !ExtraLoadRequired) {
710     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
711     Offset = 0;
712   } else {
713     unsigned char OpFlags = 0;
714     if (ExtraLoadRequired)
715       OpFlags = SystemZII::MO_GOTENT;
716
717     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
718   }
719
720   Result = DAG.getNode(SystemZISD::PCRelativeWrapper, dl,
721                        getPointerTy(), Result);
722
723   if (ExtraLoadRequired)
724     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
725                          PseudoSourceValue::getGOT(), 0);
726
727   // If there was a non-zero offset that we didn't fold, create an explicit
728   // addition for it.
729   if (Offset != 0)
730     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
731                          DAG.getConstant(Offset, getPointerTy()));
732
733   return Result;
734 }
735
736 // FIXME: PIC here
737 SDValue SystemZTargetLowering::LowerJumpTable(SDValue Op,
738                                               SelectionDAG &DAG) {
739   DebugLoc dl = Op.getDebugLoc();
740   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
741   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
742
743   return DAG.getNode(SystemZISD::PCRelativeWrapper, dl, getPointerTy(), Result);
744 }
745
746
747 // FIXME: PIC here
748 // FIXME: This is just dirty hack. We need to lower cpool properly
749 SDValue SystemZTargetLowering::LowerConstantPool(SDValue Op,
750                                                  SelectionDAG &DAG) {
751   DebugLoc dl = Op.getDebugLoc();
752   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
753
754   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
755                                              CP->getAlignment(),
756                                              CP->getOffset());
757
758   return DAG.getNode(SystemZISD::PCRelativeWrapper, dl, getPointerTy(), Result);
759 }
760
761 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
762   switch (Opcode) {
763   case SystemZISD::RET_FLAG:           return "SystemZISD::RET_FLAG";
764   case SystemZISD::CALL:               return "SystemZISD::CALL";
765   case SystemZISD::BRCOND:             return "SystemZISD::BRCOND";
766   case SystemZISD::CMP:                return "SystemZISD::CMP";
767   case SystemZISD::UCMP:               return "SystemZISD::UCMP";
768   case SystemZISD::SELECT:             return "SystemZISD::SELECT";
769   case SystemZISD::PCRelativeWrapper:  return "SystemZISD::PCRelativeWrapper";
770   default: return NULL;
771   }
772 }
773
774 //===----------------------------------------------------------------------===//
775 //  Other Lowering Code
776 //===----------------------------------------------------------------------===//
777
778 MachineBasicBlock*
779 SystemZTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
780                                                    MachineBasicBlock *BB) const {
781   const SystemZInstrInfo &TII = *TM.getInstrInfo();
782   DebugLoc dl = MI->getDebugLoc();
783   assert((MI->getOpcode() == SystemZ::Select32  ||
784           MI->getOpcode() == SystemZ::SelectF32 ||
785           MI->getOpcode() == SystemZ::Select64  ||
786           MI->getOpcode() == SystemZ::SelectF64) &&
787          "Unexpected instr type to insert");
788
789   // To "insert" a SELECT instruction, we actually have to insert the diamond
790   // control-flow pattern.  The incoming instruction knows the destination vreg
791   // to set, the condition code register to branch on, the true/false values to
792   // select between, and a branch opcode to use.
793   const BasicBlock *LLVM_BB = BB->getBasicBlock();
794   MachineFunction::iterator I = BB;
795   ++I;
796
797   //  thisMBB:
798   //  ...
799   //   TrueVal = ...
800   //   cmpTY ccX, r1, r2
801   //   jCC copy1MBB
802   //   fallthrough --> copy0MBB
803   MachineBasicBlock *thisMBB = BB;
804   MachineFunction *F = BB->getParent();
805   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
806   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
807   SystemZCC::CondCodes CC = (SystemZCC::CondCodes)MI->getOperand(3).getImm();
808   BuildMI(BB, dl, TII.getBrCond(CC)).addMBB(copy1MBB);
809   F->insert(I, copy0MBB);
810   F->insert(I, copy1MBB);
811   // Update machine-CFG edges by transferring all successors of the current
812   // block to the new block which will contain the Phi node for the select.
813   copy1MBB->transferSuccessors(BB);
814   // Next, add the true and fallthrough blocks as its successors.
815   BB->addSuccessor(copy0MBB);
816   BB->addSuccessor(copy1MBB);
817
818   //  copy0MBB:
819   //   %FalseValue = ...
820   //   # fallthrough to copy1MBB
821   BB = copy0MBB;
822
823   // Update machine-CFG edges
824   BB->addSuccessor(copy1MBB);
825
826   //  copy1MBB:
827   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
828   //  ...
829   BB = copy1MBB;
830   BuildMI(BB, dl, TII.get(SystemZ::PHI),
831           MI->getOperand(0).getReg())
832     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
833     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
834
835   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
836   return BB;
837 }