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