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