Change the interface to the type legalization method
[oota-llvm.git] / lib / Target / XCore / XCoreISelLowering.cpp
1 //===-- XCoreISelLowering.cpp - XCore 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 XCoreTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "xcore-lower"
15
16 #include "XCoreISelLowering.h"
17 #include "XCoreMachineFunctionInfo.h"
18 #include "XCore.h"
19 #include "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/VectorExtras.h"
36 #include <queue>
37 #include <set>
38 using namespace llvm;
39
40 const char *XCoreTargetLowering::
41 getTargetNodeName(unsigned Opcode) const 
42 {
43   switch (Opcode) 
44   {
45     case XCoreISD::BL                : return "XCoreISD::BL";
46     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
47     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
48     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
49     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
50     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
51     default                           : return NULL;
52   }
53 }
54
55 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
56   : TargetLowering(XTM),
57     TM(XTM),
58     Subtarget(*XTM.getSubtargetImpl()) {
59
60   // Set up the register classes.
61   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
62
63   // Compute derived properties from the register classes
64   computeRegisterProperties();
65
66   // Division is expensive
67   setIntDivIsCheap(false);
68
69   setShiftAmountType(MVT::i32);
70   // shl X, 32 == 0
71   setShiftAmountFlavor(Extend);
72   setStackPointerRegisterToSaveRestore(XCore::SP);
73
74   setSchedulingPreference(SchedulingForRegPressure);
75
76   // Use i32 for setcc operations results (slt, sgt, ...).
77   setBooleanContents(ZeroOrOneBooleanContent);
78
79   // XCore does not have the NodeTypes below.
80   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
81   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
82   setOperationAction(ISD::ADDC, MVT::i32, Expand);
83   setOperationAction(ISD::ADDE, MVT::i32, Expand);
84   setOperationAction(ISD::SUBC, MVT::i32, Expand);
85   setOperationAction(ISD::SUBE, MVT::i32, Expand);
86
87   // Stop the combiner recombining select and set_cc
88   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
89   
90   // 64bit
91   if (!Subtarget.isXS1A()) {
92     setOperationAction(ISD::ADD, MVT::i64, Custom);
93     setOperationAction(ISD::SUB, MVT::i64, Custom);
94   }
95   if (Subtarget.isXS1A()) {
96     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
97   }
98   setOperationAction(ISD::MULHS, MVT::i32, Expand);
99   setOperationAction(ISD::MULHU, MVT::i32, Expand);
100   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
101   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
102   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
103   
104   // Bit Manipulation
105   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
106   setOperationAction(ISD::ROTL , MVT::i32, Expand);
107   setOperationAction(ISD::ROTR , MVT::i32, Expand);
108   
109   // Expand jump tables for now
110   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
111   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
112
113   // RET must be custom lowered, to meet ABI requirements
114   setOperationAction(ISD::RET,           MVT::Other, Custom);
115
116   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
117   
118   // Thread Local Storage
119   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
120   
121   // Conversion of i64 -> double produces constantpool nodes
122   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
123
124   // Loads
125   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
126   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
127   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
128
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
130   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
131   
132   // Varargs
133   setOperationAction(ISD::VAEND, MVT::Other, Expand);
134   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
135   setOperationAction(ISD::VAARG, MVT::Other, Custom);
136   setOperationAction(ISD::VASTART, MVT::Other, Custom);
137   
138   // Dynamic stack
139   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
140   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
141   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
142   
143   // Debug
144   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
145   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
146 }
147
148 SDValue XCoreTargetLowering::
149 LowerOperation(SDValue Op, SelectionDAG &DAG) {
150   switch (Op.getOpcode()) 
151   {
152   case ISD::CALL:             return LowerCALL(Op, DAG);
153   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
154   case ISD::RET:              return LowerRET(Op, DAG);
155   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
156   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
157   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
158   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
159   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
160   case ISD::VAARG:            return LowerVAARG(Op, DAG);
161   case ISD::VASTART:          return LowerVASTART(Op, DAG);
162   // FIXME: Remove these when LegalizeDAGTypes lands.
163   case ISD::ADD:
164   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
165   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
166   default:
167     assert(0 && "unimplemented operand");
168     return SDValue();
169   }
170 }
171
172 /// ReplaceNodeResults - Replace the results of node with an illegal result
173 /// type with new values built out of custom code.
174 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
175                                              SmallVectorImpl<SDValue>&Results,
176                                              SelectionDAG &DAG) {
177   switch (N->getOpcode()) {
178   default:
179     assert(0 && "Don't know how to custom expand this!");
180     return;
181   case ISD::ADD:
182   case ISD::SUB:
183     Results.push_back(ExpandADDSUB(N, DAG));
184     return;
185   }
186 }
187
188 //===----------------------------------------------------------------------===//
189 //  Misc Lower Operation implementation
190 //===----------------------------------------------------------------------===//
191
192 SDValue XCoreTargetLowering::
193 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
194 {
195   SDValue Cond = DAG.getNode(ISD::SETCC, MVT::i32, Op.getOperand(2),
196                              Op.getOperand(3), Op.getOperand(4));
197   return DAG.getNode(ISD::SELECT, MVT::i32, Cond, Op.getOperand(0),
198                      Op.getOperand(1));
199 }
200
201 SDValue XCoreTargetLowering::
202 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
203 {
204   if (isa<Function>(GV)) {
205     return DAG.getNode(XCoreISD::PCRelativeWrapper, MVT::i32, GA);
206   } else if (!Subtarget.isXS1A()) {
207     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
208     if (!GVar) {
209       // If GV is an alias then use the aliasee to determine constness
210       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
211         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
212     }
213     bool isConst = GVar && GVar->isConstant();
214     if (isConst) {
215       return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, GA);
216     }
217   }
218   return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, GA);
219 }
220
221 SDValue XCoreTargetLowering::
222 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
223 {
224   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
225   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
226   // If it's a debug information descriptor, don't mess with it.
227   if (DAG.isVerifiedDebugInfoDesc(Op))
228     return GA;
229   return getGlobalAddressWrapper(GA, GV, DAG);
230 }
231
232 static inline SDValue BuildGetId(SelectionDAG &DAG) {
233   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::i32,
234                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
235 }
236
237 static inline bool isZeroLengthArray(const Type *Ty) {
238   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
239   return AT && (AT->getNumElements() == 0);
240 }
241
242 SDValue XCoreTargetLowering::
243 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
244 {
245   // transform to label + getid() * size
246   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
247   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
248   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
249   if (!GVar) {
250     // If GV is an alias then use the aliasee to determine size
251     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
252       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
253   }
254   if (! GVar) {
255     assert(0 && "Thread local object not a GlobalVariable?");
256     return SDValue();
257   }
258   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
259   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
260     cerr << "Size of thread local object " << GVar->getName()
261          << " is unknown\n";
262     abort();
263   }
264   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
265   const TargetData *TD = TM.getTargetData();
266   unsigned Size = TD->getABITypeSize(Ty);
267   SDValue offset = DAG.getNode(ISD::MUL, MVT::i32, BuildGetId(DAG),
268                        DAG.getConstant(Size, MVT::i32));
269   return DAG.getNode(ISD::ADD, MVT::i32, base, offset);
270 }
271
272 SDValue XCoreTargetLowering::
273 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
274 {
275   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
276   if (Subtarget.isXS1A()) {
277     assert(0 && "Lowering of constant pool unimplemented");
278     return SDValue();
279   } else {
280     MVT PtrVT = Op.getValueType();
281     SDValue Res;
282     if (CP->isMachineConstantPoolEntry()) {
283       Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
284                                       CP->getAlignment());
285     } else {
286       Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
287                                       CP->getAlignment());
288     }
289     return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, Res);
290   }
291 }
292
293 SDValue XCoreTargetLowering::
294 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
295 {
296   MVT PtrVT = Op.getValueType();
297   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
298   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
299   return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, JTI);
300 }
301
302 SDValue XCoreTargetLowering::
303 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
304 {
305   assert(N->getValueType(0) == MVT::i64 &&
306          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
307         "Unknown operand to lower!");
308   assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
309   
310   // Extract components
311   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
312                              DAG.getConstant(0, MVT::i32));
313   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
314                              DAG.getConstant(1, MVT::i32));
315   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
316                              DAG.getConstant(0, MVT::i32));
317   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
318                              DAG.getConstant(1, MVT::i32));
319   
320   // Expand
321   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
322                                                    XCoreISD::LSUB;
323   SDValue Zero = DAG.getConstant(0, MVT::i32);
324   SDValue Carry = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
325                                   LHSL, RHSL, Zero);
326   SDValue Lo(Carry.getNode(), 1);
327   
328   SDValue Ignored = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
329                                   LHSH, RHSH, Carry);
330   SDValue Hi(Ignored.getNode(), 1);
331   // Merge the pieces
332   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
333 }
334
335 SDValue XCoreTargetLowering::
336 LowerVAARG(SDValue Op, SelectionDAG &DAG)
337 {
338   assert(0 && "unimplemented");
339   // FIX Arguments passed by reference need a extra dereference.
340   SDNode *Node = Op.getNode();
341   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
342   MVT VT = Node->getValueType(0);
343   SDValue VAList = DAG.getLoad(getPointerTy(), Node->getOperand(0),
344                                Node->getOperand(1), V, 0);
345   // Increment the pointer, VAList, to the next vararg
346   SDValue Tmp3 = DAG.getNode(ISD::ADD, getPointerTy(), VAList, 
347                      DAG.getConstant(VT.getSizeInBits(), 
348                                      getPointerTy()));
349   // Store the incremented VAList to the legalized pointer
350   Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Node->getOperand(1), V, 0);
351   // Load the actual argument out of the pointer VAList
352   return DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
353 }
354
355 SDValue XCoreTargetLowering::
356 LowerVASTART(SDValue Op, SelectionDAG &DAG)
357 {
358   // vastart stores the address of the VarArgsFrameIndex slot into the
359   // memory location argument
360   MachineFunction &MF = DAG.getMachineFunction();
361   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
362   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
363   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
364   return DAG.getStore(Op.getOperand(0), Addr, Op.getOperand(1), SV, 0);
365 }
366
367 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
368   // Depths > 0 not supported yet! 
369   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
370     return SDValue();
371   
372   MachineFunction &MF = DAG.getMachineFunction();
373   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
374   return DAG.getCopyFromReg(DAG.getEntryNode(), RegInfo->getFrameRegister(MF),
375     MVT::i32);
376 }
377
378 //===----------------------------------------------------------------------===//
379 //                      Calling Convention Implementation
380 //
381 //  The lower operations present on calling convention works on this order:
382 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
383 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
384 //      LowerRET (virt regs --> phys regs)
385 //      LowerCALL (phys regs --> virt regs)
386 //
387 //===----------------------------------------------------------------------===//
388
389 #include "XCoreGenCallingConv.inc"
390
391 //===----------------------------------------------------------------------===//
392 //                  CALL Calling Convention Implementation
393 //===----------------------------------------------------------------------===//
394
395 /// XCore custom CALL implementation
396 SDValue XCoreTargetLowering::
397 LowerCALL(SDValue Op, SelectionDAG &DAG)
398 {
399   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
400   unsigned CallingConv = TheCall->getCallingConv();
401   // For now, only CallingConv::C implemented
402   switch (CallingConv) 
403   {
404     default:
405       assert(0 && "Unsupported calling convention");
406     case CallingConv::Fast:
407     case CallingConv::C:
408       return LowerCCCCallTo(Op, DAG, CallingConv);
409   }
410 }
411
412 /// LowerCCCCallTo - functions arguments are copied from virtual
413 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
414 /// CALLSEQ_END are emitted.
415 /// TODO: isTailCall, sret.
416 SDValue XCoreTargetLowering::
417 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC) 
418 {
419   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
420   SDValue Chain  = TheCall->getChain();
421   SDValue Callee = TheCall->getCallee();
422   bool isVarArg  = TheCall->isVarArg();
423
424   // Analyze operands of the call, assigning locations to each operand.
425   SmallVector<CCValAssign, 16> ArgLocs;
426   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
427
428   // The ABI dictates there should be one stack slot available to the callee
429   // on function entry (for saving lr).
430   CCInfo.AllocateStack(4, 4);
431
432   CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
433
434   // Get a count of how many bytes are to be pushed on the stack.
435   unsigned NumBytes = CCInfo.getNextStackOffset();
436
437   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
438                                  getPointerTy(), true));
439
440   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
441   SmallVector<SDValue, 12> MemOpChains;
442
443   // Walk the register/memloc assignments, inserting copies/loads.
444   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
445     CCValAssign &VA = ArgLocs[i];
446
447     // Arguments start after the 5 first operands of ISD::CALL
448     SDValue Arg = TheCall->getArg(i);
449
450     // Promote the value if needed.
451     switch (VA.getLocInfo()) {
452       default: assert(0 && "Unknown loc info!");
453       case CCValAssign::Full: break;
454       case CCValAssign::SExt:
455         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
456         break;
457       case CCValAssign::ZExt:
458         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
459         break;
460       case CCValAssign::AExt:
461         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
462         break;
463     }
464     
465     // Arguments that can be passed on register must be kept at 
466     // RegsToPass vector
467     if (VA.isRegLoc()) {
468       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
469     } else {
470       assert(VA.isMemLoc());
471
472       int Offset = VA.getLocMemOffset();
473
474       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, MVT::Other, Chain, Arg,
475                                         DAG.getConstant(Offset/4, MVT::i32)));
476     }
477   }
478
479   // Transform all store nodes into one single node because
480   // all store nodes are independent of each other.
481   if (!MemOpChains.empty())
482     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
483                         &MemOpChains[0], MemOpChains.size());
484
485   // Build a sequence of copy-to-reg nodes chained together with token 
486   // chain and flag operands which copy the outgoing args into registers.
487   // The InFlag in necessary since all emited instructions must be
488   // stuck together.
489   SDValue InFlag;
490   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
491     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
492                              RegsToPass[i].second, InFlag);
493     InFlag = Chain.getValue(1);
494   }
495
496   // If the callee is a GlobalAddress node (quite common, every direct call is)
497   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
498   // Likewise ExternalSymbol -> TargetExternalSymbol.
499   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
500     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
501   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
502     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
503
504   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
505   //             = Chain, Callee, Reg#1, Reg#2, ...  
506   //
507   // Returns a chain & a flag for retval copy to use.
508   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
509   SmallVector<SDValue, 8> Ops;
510   Ops.push_back(Chain);
511   Ops.push_back(Callee);
512
513   // Add argument registers to the end of the list so that they are 
514   // known live into the call.
515   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
516     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
517                                   RegsToPass[i].second.getValueType()));
518
519   if (InFlag.getNode())
520     Ops.push_back(InFlag);
521
522   Chain  = DAG.getNode(XCoreISD::BL, NodeTys, &Ops[0], Ops.size());
523   InFlag = Chain.getValue(1);
524
525   // Create the CALLSEQ_END node.
526   Chain = DAG.getCALLSEQ_END(Chain,
527                              DAG.getConstant(NumBytes, getPointerTy(), true),
528                              DAG.getConstant(0, getPointerTy(), true),
529                              InFlag);
530   InFlag = Chain.getValue(1);
531
532   // Handle result values, copying them out of physregs into vregs that we
533   // return.
534   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
535                  Op.getResNo());
536 }
537
538 /// LowerCallResult - Lower the result values of an ISD::CALL into the
539 /// appropriate copies out of appropriate physical registers.  This assumes that
540 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
541 /// being lowered. Returns a SDNode with the same number of values as the 
542 /// ISD::CALL.
543 SDNode *XCoreTargetLowering::
544 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
545         unsigned CallingConv, SelectionDAG &DAG) {
546   bool isVarArg = TheCall->isVarArg();
547
548   // Assign locations to each value returned by this call.
549   SmallVector<CCValAssign, 16> RVLocs;
550   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
551
552   CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
553   SmallVector<SDValue, 8> ResultVals;
554
555   // Copy all of the result registers out of their specified physreg.
556   for (unsigned i = 0; i != RVLocs.size(); ++i) {
557     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
558                                  RVLocs[i].getValVT(), InFlag).getValue(1);
559     InFlag = Chain.getValue(2);
560     ResultVals.push_back(Chain.getValue(0));
561   }
562
563   ResultVals.push_back(Chain);
564
565   // Merge everything together with a MERGE_VALUES node.
566   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
567                      &ResultVals[0], ResultVals.size()).getNode();
568 }
569
570 //===----------------------------------------------------------------------===//
571 //             FORMAL_ARGUMENTS Calling Convention Implementation
572 //===----------------------------------------------------------------------===//
573
574 /// XCore custom FORMAL_ARGUMENTS implementation
575 SDValue XCoreTargetLowering::
576 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 
577 {
578   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
579   switch(CC) 
580   {
581     default:
582       assert(0 && "Unsupported calling convention");
583     case CallingConv::C:
584     case CallingConv::Fast:
585       return LowerCCCArguments(Op, DAG);
586   }
587 }
588
589 /// LowerCCCArguments - transform physical registers into
590 /// virtual registers and generate load operations for
591 /// arguments places on the stack.
592 /// TODO: sret
593 SDValue XCoreTargetLowering::
594 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
595 {
596   MachineFunction &MF = DAG.getMachineFunction();
597   MachineFrameInfo *MFI = MF.getFrameInfo();
598   MachineRegisterInfo &RegInfo = MF.getRegInfo();
599   SDValue Root = Op.getOperand(0);
600   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
601   unsigned CC = MF.getFunction()->getCallingConv();
602
603   // Assign locations to all of the incoming arguments.
604   SmallVector<CCValAssign, 16> ArgLocs;
605   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
606
607   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
608
609   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
610
611   SmallVector<SDValue, 16> ArgValues;
612   
613   unsigned LRSaveSize = StackSlotSize;
614   
615   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
616
617     CCValAssign &VA = ArgLocs[i];
618     
619     if (VA.isRegLoc()) {
620       // Arguments passed in registers
621       MVT RegVT = VA.getLocVT();
622       switch (RegVT.getSimpleVT()) {
623       default:
624         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
625              << RegVT.getSimpleVT()
626              << "\n";
627         abort();
628       case MVT::i32:
629         unsigned VReg = RegInfo.createVirtualRegister(
630                           XCore::GRRegsRegisterClass);
631         RegInfo.addLiveIn(VA.getLocReg(), VReg);
632         ArgValues.push_back(DAG.getCopyFromReg(Root, VReg, RegVT));
633       }
634     } else {
635       // sanity check
636       assert(VA.isMemLoc());
637       // Load the argument to a virtual register
638       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
639       if (ObjSize > StackSlotSize) {
640         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
641              << VA.getLocVT().getSimpleVT()
642              << "\n";
643       }
644       // Create the frame index object for this incoming parameter...
645       int FI = MFI->CreateFixedObject(ObjSize,
646                                       LRSaveSize + VA.getLocMemOffset());
647
648       // Create the SelectionDAG nodes corresponding to a load
649       //from this parameter
650       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
651       ArgValues.push_back(DAG.getLoad(VA.getLocVT(), Root, FIN, NULL, 0));
652     }
653   }
654   
655   if (isVarArg) {
656     /* Argument registers */
657     static const unsigned ArgRegs[] = {
658       XCore::R0, XCore::R1, XCore::R2, XCore::R3
659     };
660     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
661     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
662                                                      array_lengthof(ArgRegs));
663     if (FirstVAReg < array_lengthof(ArgRegs)) {
664       SmallVector<SDValue, 4> MemOps;
665       int offset = 0;
666       // Save remaining registers, storing higher register numbers at a higher
667       // address
668       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
669         // Create a stack slot
670         int FI = MFI->CreateFixedObject(4, offset);
671         if (i == FirstVAReg) {
672           XFI->setVarArgsFrameIndex(FI);
673         }
674         offset -= StackSlotSize;
675         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
676         // Move argument from phys reg -> virt reg
677         unsigned VReg = RegInfo.createVirtualRegister(
678                           XCore::GRRegsRegisterClass);
679         RegInfo.addLiveIn(ArgRegs[i], VReg);
680         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
681         // Move argument from virt reg -> stack
682         SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
683         MemOps.push_back(Store);
684       }
685       if (!MemOps.empty())
686         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
687                            &MemOps[0], MemOps.size());
688     } else {
689       // This will point to the next argument passed via stack.
690       XFI->setVarArgsFrameIndex(
691           MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
692     }
693   }
694   
695   ArgValues.push_back(Root);
696
697   // Return the new list of results.
698   std::vector<MVT> RetVT(Op.getNode()->value_begin(),
699                                     Op.getNode()->value_end());
700   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
701 }
702
703 //===----------------------------------------------------------------------===//
704 //               Return Value Calling Convention Implementation
705 //===----------------------------------------------------------------------===//
706
707 SDValue XCoreTargetLowering::
708 LowerRET(SDValue Op, SelectionDAG &DAG)
709 {
710   // CCValAssign - represent the assignment of
711   // the return value to a location
712   SmallVector<CCValAssign, 16> RVLocs;
713   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
714   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
715
716   // CCState - Info about the registers and stack slot.
717   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
718
719   // Analize return values of ISD::RET
720   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
721
722   // If this is the first return lowered for this function, add 
723   // the regs to the liveout set for the function.
724   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
725     for (unsigned i = 0; i != RVLocs.size(); ++i)
726       if (RVLocs[i].isRegLoc())
727         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
728   }
729
730   // The chain is always operand #0
731   SDValue Chain = Op.getOperand(0);
732   SDValue Flag;
733
734   // Copy the result values into the output registers.
735   for (unsigned i = 0; i != RVLocs.size(); ++i) {
736     CCValAssign &VA = RVLocs[i];
737     assert(VA.isRegLoc() && "Can only return in registers!");
738
739     // ISD::RET => ret chain, (regnum1,val1), ...
740     // So i*2+1 index only the regnums
741     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
742
743     // guarantee that all emitted copies are
744     // stuck together, avoiding something bad
745     Flag = Chain.getValue(1);
746   }
747
748   // Return on XCore is always a "retsp 0"
749   if (Flag.getNode())
750     return DAG.getNode(XCoreISD::RETSP, MVT::Other,
751                        Chain, DAG.getConstant(0, MVT::i32), Flag);
752   else // Return Void
753     return DAG.getNode(XCoreISD::RETSP, MVT::Other,
754                        Chain, DAG.getConstant(0, MVT::i32));
755 }
756
757 //===----------------------------------------------------------------------===//
758 //  Other Lowering Code
759 //===----------------------------------------------------------------------===//
760
761 MachineBasicBlock *
762 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
763                                                MachineBasicBlock *BB) {
764   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
765   assert((MI->getOpcode() == XCore::SELECT_CC) &&
766          "Unexpected instr type to insert");
767   
768   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
769   // control-flow pattern.  The incoming instruction knows the destination vreg
770   // to set, the condition code register to branch on, the true/false values to
771   // select between, and a branch opcode to use.
772   const BasicBlock *LLVM_BB = BB->getBasicBlock();
773   MachineFunction::iterator It = BB;
774   ++It;
775   
776   //  thisMBB:
777   //  ...
778   //   TrueVal = ...
779   //   cmpTY ccX, r1, r2
780   //   bCC copy1MBB
781   //   fallthrough --> copy0MBB
782   MachineBasicBlock *thisMBB = BB;
783   MachineFunction *F = BB->getParent();
784   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
785   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
786   BuildMI(BB, TII.get(XCore::BRFT_lru6))
787     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
788   F->insert(It, copy0MBB);
789   F->insert(It, sinkMBB);
790   // Update machine-CFG edges by transferring all successors of the current
791   // block to the new block which will contain the Phi node for the select.
792   sinkMBB->transferSuccessors(BB);
793   // Next, add the true and fallthrough blocks as its successors.
794   BB->addSuccessor(copy0MBB);
795   BB->addSuccessor(sinkMBB);
796   
797   //  copy0MBB:
798   //   %FalseValue = ...
799   //   # fallthrough to sinkMBB
800   BB = copy0MBB;
801   
802   // Update machine-CFG edges
803   BB->addSuccessor(sinkMBB);
804   
805   //  sinkMBB:
806   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
807   //  ...
808   BB = sinkMBB;
809   BuildMI(BB, TII.get(XCore::PHI), MI->getOperand(0).getReg())
810     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
811     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
812   
813   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
814   return BB;
815 }
816
817 //===----------------------------------------------------------------------===//
818 //  Addressing mode description hooks
819 //===----------------------------------------------------------------------===//
820
821 static inline bool isImmUs(int64_t val)
822 {
823   return (val >= 0 && val <= 11);
824 }
825
826 static inline bool isImmUs2(int64_t val)
827 {
828   return (val%2 == 0 && isImmUs(val/2));
829 }
830
831 static inline bool isImmUs4(int64_t val)
832 {
833   return (val%4 == 0 && isImmUs(val/4));
834 }
835
836 /// isLegalAddressingMode - Return true if the addressing mode represented
837 /// by AM is legal for this target, for a load/store of the specified type.
838 bool
839 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
840                                               const Type *Ty) const {
841   MVT VT = getValueType(Ty, true);
842   // Get expected value type after legalization
843   switch (VT.getSimpleVT()) {
844   // Legal load / stores
845   case MVT::i8:
846   case MVT::i16:
847   case MVT::i32:
848     break;
849   // Expand i1 -> i8
850   case MVT::i1:
851     VT = MVT::i8;
852     break;
853   // Everything else is lowered to words
854   default:
855     VT = MVT::i32;
856     break;
857   }
858   if (AM.BaseGV) {
859     return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
860                  AM.BaseOffs%4 == 0;
861   }
862   
863   switch (VT.getSimpleVT()) {
864   default:
865     return false;
866   case MVT::i8:
867     // reg + imm
868     if (AM.Scale == 0) {
869       return isImmUs(AM.BaseOffs);
870     }
871     return AM.Scale == 1 && AM.BaseOffs == 0;
872   case MVT::i16:
873     // reg + imm
874     if (AM.Scale == 0) {
875       return isImmUs2(AM.BaseOffs);
876     }
877     return AM.Scale == 2 && AM.BaseOffs == 0;
878   case MVT::i32:
879     // reg + imm
880     if (AM.Scale == 0) {
881       return isImmUs4(AM.BaseOffs);
882     }
883     // reg + reg<<2
884     return AM.Scale == 4 && AM.BaseOffs == 0;
885   }
886   
887   return false;
888 }
889
890 //===----------------------------------------------------------------------===//
891 //                           XCore Inline Assembly Support
892 //===----------------------------------------------------------------------===//
893
894 std::vector<unsigned> XCoreTargetLowering::
895 getRegClassForInlineAsmConstraint(const std::string &Constraint,
896                                   MVT VT) const 
897 {
898   if (Constraint.size() != 1)
899     return std::vector<unsigned>();
900
901   switch (Constraint[0]) {
902     default : break;
903     case 'r':
904       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
905                                    XCore::R3, XCore::R4,  XCore::R5, 
906                                    XCore::R6, XCore::R7,  XCore::R8, 
907                                    XCore::R9, XCore::R10, XCore::R11, 0);
908       break;
909   }
910   return std::vector<unsigned>();
911 }