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