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