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