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