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