Add a bool flag to StackObjects telling whether they reference spill
[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 "XCoreTargetObjectFile.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreSubtarget.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/GlobalAlias.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/VectorExtras.h"
39 #include <queue>
40 #include <set>
41 using namespace llvm;
42
43 const char *XCoreTargetLowering::
44 getTargetNodeName(unsigned Opcode) const 
45 {
46   switch (Opcode) 
47   {
48     case XCoreISD::BL                : return "XCoreISD::BL";
49     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
50     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
51     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
52     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
53     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
54     case XCoreISD::LADD              : return "XCoreISD::LADD";
55     case XCoreISD::LSUB              : return "XCoreISD::LSUB";
56     default                           : return NULL;
57   }
58 }
59
60 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
61   : TargetLowering(XTM, new XCoreTargetObjectFile()),
62     TM(XTM),
63     Subtarget(*XTM.getSubtargetImpl()) {
64
65   // Set up the register classes.
66   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
67
68   // Compute derived properties from the register classes
69   computeRegisterProperties();
70
71   // Division is expensive
72   setIntDivIsCheap(false);
73
74   setShiftAmountType(MVT::i32);
75   setStackPointerRegisterToSaveRestore(XCore::SP);
76
77   setSchedulingPreference(SchedulingForRegPressure);
78
79   // Use i32 for setcc operations results (slt, sgt, ...).
80   setBooleanContents(ZeroOrOneBooleanContent);
81
82   // XCore does not have the NodeTypes below.
83   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
84   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
85   setOperationAction(ISD::ADDC, MVT::i32, Expand);
86   setOperationAction(ISD::ADDE, MVT::i32, Expand);
87   setOperationAction(ISD::SUBC, MVT::i32, Expand);
88   setOperationAction(ISD::SUBE, MVT::i32, Expand);
89
90   // Stop the combiner recombining select and set_cc
91   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
92   
93   // 64bit
94   setOperationAction(ISD::ADD, MVT::i64, Custom);
95   setOperationAction(ISD::SUB, MVT::i64, Custom);
96   setOperationAction(ISD::MULHS, MVT::i32, Expand);
97   setOperationAction(ISD::MULHU, MVT::i32, Expand);
98   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
99   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
100   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
101   
102   // Bit Manipulation
103   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
104   setOperationAction(ISD::ROTL , MVT::i32, Expand);
105   setOperationAction(ISD::ROTR , MVT::i32, Expand);
106   
107   setOperationAction(ISD::TRAP, MVT::Other, Legal);
108   
109   // Expand jump tables for now
110   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
111   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
112
113   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
114   
115   // Thread Local Storage
116   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
117   
118   // Conversion of i64 -> double produces constantpool nodes
119   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
120
121   // Loads
122   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
123   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
124   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
125
126   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
127   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
128
129   // Custom expand misaligned loads / stores.
130   setOperationAction(ISD::LOAD, MVT::i32, Custom);
131   setOperationAction(ISD::STORE, MVT::i32, Custom);
132
133   // Varargs
134   setOperationAction(ISD::VAEND, MVT::Other, Expand);
135   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
136   setOperationAction(ISD::VAARG, MVT::Other, Custom);
137   setOperationAction(ISD::VASTART, MVT::Other, Custom);
138   
139   // Dynamic stack
140   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
141   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
142   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
143   
144   // Debug
145   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
146   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
147
148   maxStoresPerMemset = 4;
149   maxStoresPerMemmove = maxStoresPerMemcpy = 2;
150
151   // We have target-specific dag combine patterns for the following nodes:
152   setTargetDAGCombine(ISD::STORE);
153 }
154
155 SDValue XCoreTargetLowering::
156 LowerOperation(SDValue Op, SelectionDAG &DAG) {
157   switch (Op.getOpcode()) 
158   {
159   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
160   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
161   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
162   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
163   case ISD::LOAD:             return LowerLOAD(Op, DAG);
164   case ISD::STORE:            return LowerSTORE(Op, DAG);
165   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
166   case ISD::VAARG:            return LowerVAARG(Op, DAG);
167   case ISD::VASTART:          return LowerVASTART(Op, DAG);
168   // FIXME: Remove these when LegalizeDAGTypes lands.
169   case ISD::ADD:
170   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
171   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
172   default:
173     llvm_unreachable("unimplemented operand");
174     return SDValue();
175   }
176 }
177
178 /// ReplaceNodeResults - Replace the results of node with an illegal result
179 /// type with new values built out of custom code.
180 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
181                                              SmallVectorImpl<SDValue>&Results,
182                                              SelectionDAG &DAG) {
183   switch (N->getOpcode()) {
184   default:
185     llvm_unreachable("Don't know how to custom expand this!");
186     return;
187   case ISD::ADD:
188   case ISD::SUB:
189     Results.push_back(ExpandADDSUB(N, DAG));
190     return;
191   }
192 }
193
194 /// getFunctionAlignment - Return the Log2 alignment of this function.
195 unsigned XCoreTargetLowering::
196 getFunctionAlignment(const Function *) const {
197   return 1;
198 }
199
200 //===----------------------------------------------------------------------===//
201 //  Misc Lower Operation implementation
202 //===----------------------------------------------------------------------===//
203
204 SDValue XCoreTargetLowering::
205 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
206 {
207   DebugLoc dl = Op.getDebugLoc();
208   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
209                              Op.getOperand(3), Op.getOperand(4));
210   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
211                      Op.getOperand(1));
212 }
213
214 SDValue XCoreTargetLowering::
215 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
216 {
217   // FIXME there is no actual debug info here
218   DebugLoc dl = GA.getDebugLoc();
219   if (isa<Function>(GV)) {
220     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
221   }
222   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
223   if (!GVar) {
224     // If GV is an alias then use the aliasee to determine constness
225     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
226       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
227   }
228   bool isConst = GVar && GVar->isConstant();
229   if (isConst) {
230     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
231   }
232   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
233 }
234
235 SDValue XCoreTargetLowering::
236 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
237 {
238   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
239   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
240   // If it's a debug information descriptor, don't mess with it.
241   if (DAG.isVerifiedDebugInfoDesc(Op))
242     return GA;
243   return getGlobalAddressWrapper(GA, GV, DAG);
244 }
245
246 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
247   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
248                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
249 }
250
251 static inline bool isZeroLengthArray(const Type *Ty) {
252   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
253   return AT && (AT->getNumElements() == 0);
254 }
255
256 SDValue XCoreTargetLowering::
257 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
258 {
259   // FIXME there isn't really debug info here
260   DebugLoc dl = Op.getDebugLoc();
261   // transform to label + getid() * size
262   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
263   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
264   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
265   if (!GVar) {
266     // If GV is an alias then use the aliasee to determine size
267     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
268       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
269   }
270   if (! GVar) {
271     llvm_unreachable("Thread local object not a GlobalVariable?");
272     return SDValue();
273   }
274   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
275   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
276 #ifndef NDEBUG
277     errs() << "Size of thread local object " << GVar->getName()
278            << " is unknown\n";
279 #endif
280     llvm_unreachable(0);
281   }
282   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
283   const TargetData *TD = TM.getTargetData();
284   unsigned Size = TD->getTypeAllocSize(Ty);
285   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
286                        DAG.getConstant(Size, MVT::i32));
287   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
288 }
289
290 SDValue XCoreTargetLowering::
291 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
292 {
293   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
294   // FIXME there isn't really debug info here
295   DebugLoc dl = CP->getDebugLoc();
296   EVT PtrVT = Op.getValueType();
297   SDValue Res;
298   if (CP->isMachineConstantPoolEntry()) {
299     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
300                                     CP->getAlignment());
301   } else {
302     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
303                                     CP->getAlignment());
304   }
305   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
306 }
307
308 SDValue XCoreTargetLowering::
309 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
310 {
311   // FIXME there isn't really debug info here
312   DebugLoc dl = Op.getDebugLoc();
313   EVT PtrVT = Op.getValueType();
314   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
315   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
316   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
317 }
318
319 static bool
320 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
321                                     int64_t &Offset)
322 {
323   if (Addr.getOpcode() != ISD::ADD) {
324     return false;
325   }
326   ConstantSDNode *CN = 0;
327   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
328     return false;
329   }
330   int64_t off = CN->getSExtValue();
331   const SDValue &Base = Addr.getOperand(0);
332   const SDValue *Root = &Base;
333   if (Base.getOpcode() == ISD::ADD &&
334       Base.getOperand(1).getOpcode() == ISD::SHL) {
335     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
336                                                       .getOperand(1));
337     if (CN && (CN->getSExtValue() >= 2)) {
338       Root = &Base.getOperand(0);
339     }
340   }
341   if (isa<FrameIndexSDNode>(*Root)) {
342     // All frame indicies are word aligned
343     AlignedBase = Base;
344     Offset = off;
345     return true;
346   }
347   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
348       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
349     // All dp / cp relative addresses are word aligned
350     AlignedBase = Base;
351     Offset = off;
352     return true;
353   }
354   return false;
355 }
356
357 SDValue XCoreTargetLowering::
358 LowerLOAD(SDValue Op, SelectionDAG &DAG)
359 {
360   LoadSDNode *LD = cast<LoadSDNode>(Op);
361   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
362          "Unexpected extension type");
363   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
364   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
365     return SDValue();
366   }
367   unsigned ABIAlignment = getTargetData()->
368     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
369   // Leave aligned load alone.
370   if (LD->getAlignment() >= ABIAlignment) {
371     return SDValue();
372   }
373   SDValue Chain = LD->getChain();
374   SDValue BasePtr = LD->getBasePtr();
375   DebugLoc dl = Op.getDebugLoc();
376   
377   SDValue Base;
378   int64_t Offset;
379   if (!LD->isVolatile() &&
380       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
381     if (Offset % 4 == 0) {
382       // We've managed to infer better alignment information than the load
383       // already has. Use an aligned load.
384       return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
385     }
386     // Lower to
387     // ldw low, base[offset >> 2]
388     // ldw high, base[(offset >> 2) + 1]
389     // shr low_shifted, low, (offset & 0x3) * 8
390     // shl high_shifted, high, 32 - (offset & 0x3) * 8
391     // or result, low_shifted, high_shifted
392     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
393     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
394     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
395     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
396     
397     SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
398     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
399     
400     SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
401                                LowAddr, NULL, 4);
402     SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
403                                HighAddr, NULL, 4);
404     SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
405     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
406     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
407     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
408                              High.getValue(1));
409     SDValue Ops[] = { Result, Chain };
410     return DAG.getMergeValues(Ops, 2, dl);
411   }
412   
413   if (LD->getAlignment() == 2) {
414     int SVOffset = LD->getSrcValueOffset();
415     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
416                                  BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
417                                  LD->isVolatile(), 2);
418     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
419                                    DAG.getConstant(2, MVT::i32));
420     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
421                                   HighAddr, LD->getSrcValue(), SVOffset + 2,
422                                   MVT::i16, LD->isVolatile(), 2);
423     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
424                                       DAG.getConstant(16, MVT::i32));
425     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
426     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
427                              High.getValue(1));
428     SDValue Ops[] = { Result, Chain };
429     return DAG.getMergeValues(Ops, 2, dl);
430   }
431   
432   // Lower to a call to __misaligned_load(BasePtr).
433   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
434   TargetLowering::ArgListTy Args;
435   TargetLowering::ArgListEntry Entry;
436   
437   Entry.Ty = IntPtrTy;
438   Entry.Node = BasePtr;
439   Args.push_back(Entry);
440   
441   std::pair<SDValue, SDValue> CallResult =
442         LowerCallTo(Chain, IntPtrTy, false, false,
443                     false, false, 0, CallingConv::C, false,
444                     /*isReturnValueUsed=*/true,
445                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
446                     Args, DAG, dl);
447
448   SDValue Ops[] =
449     { CallResult.first, CallResult.second };
450
451   return DAG.getMergeValues(Ops, 2, dl);
452 }
453
454 SDValue XCoreTargetLowering::
455 LowerSTORE(SDValue Op, SelectionDAG &DAG)
456 {
457   StoreSDNode *ST = cast<StoreSDNode>(Op);
458   assert(!ST->isTruncatingStore() && "Unexpected store type");
459   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
460   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
461     return SDValue();
462   }
463   unsigned ABIAlignment = getTargetData()->
464     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
465   // Leave aligned store alone.
466   if (ST->getAlignment() >= ABIAlignment) {
467     return SDValue();
468   }
469   SDValue Chain = ST->getChain();
470   SDValue BasePtr = ST->getBasePtr();
471   SDValue Value = ST->getValue();
472   DebugLoc dl = Op.getDebugLoc();
473   
474   if (ST->getAlignment() == 2) {
475     int SVOffset = ST->getSrcValueOffset();
476     SDValue Low = Value;
477     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
478                                       DAG.getConstant(16, MVT::i32));
479     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
480                                          ST->getSrcValue(), SVOffset, MVT::i16,
481                                          ST->isVolatile(), 2);
482     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
483                                    DAG.getConstant(2, MVT::i32));
484     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
485                                           ST->getSrcValue(), SVOffset + 2,
486                                           MVT::i16, ST->isVolatile(), 2);
487     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
488   }
489   
490   // Lower to a call to __misaligned_store(BasePtr, Value).
491   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
492   TargetLowering::ArgListTy Args;
493   TargetLowering::ArgListEntry Entry;
494   
495   Entry.Ty = IntPtrTy;
496   Entry.Node = BasePtr;
497   Args.push_back(Entry);
498   
499   Entry.Node = Value;
500   Args.push_back(Entry);
501   
502   std::pair<SDValue, SDValue> CallResult =
503         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
504                     false, false, 0, CallingConv::C, false,
505                     /*isReturnValueUsed=*/true,
506                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
507                     Args, DAG, dl);
508
509   return CallResult.second;
510 }
511
512 SDValue XCoreTargetLowering::
513 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
514 {
515   assert(N->getValueType(0) == MVT::i64 &&
516          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
517         "Unknown operand to lower!");
518   DebugLoc dl = N->getDebugLoc();
519   
520   // Extract components
521   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
522                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
523   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
524                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
525   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
526                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
527   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
528                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
529   
530   // Expand
531   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
532                                                    XCoreISD::LSUB;
533   SDValue Zero = DAG.getConstant(0, MVT::i32);
534   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
535                                   LHSL, RHSL, Zero);
536   SDValue Lo(Carry.getNode(), 1);
537   
538   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
539                                   LHSH, RHSH, Carry);
540   SDValue Hi(Ignored.getNode(), 1);
541   // Merge the pieces
542   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
543 }
544
545 SDValue XCoreTargetLowering::
546 LowerVAARG(SDValue Op, SelectionDAG &DAG)
547 {
548   llvm_unreachable("unimplemented");
549   // FIX Arguments passed by reference need a extra dereference.
550   SDNode *Node = Op.getNode();
551   DebugLoc dl = Node->getDebugLoc();
552   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
553   EVT VT = Node->getValueType(0);
554   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
555                                Node->getOperand(1), V, 0);
556   // Increment the pointer, VAList, to the next vararg
557   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList, 
558                      DAG.getConstant(VT.getSizeInBits(), 
559                                      getPointerTy()));
560   // Store the incremented VAList to the legalized pointer
561   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
562   // Load the actual argument out of the pointer VAList
563   return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
564 }
565
566 SDValue XCoreTargetLowering::
567 LowerVASTART(SDValue Op, SelectionDAG &DAG)
568 {
569   DebugLoc dl = Op.getDebugLoc();
570   // vastart stores the address of the VarArgsFrameIndex slot into the
571   // memory location argument
572   MachineFunction &MF = DAG.getMachineFunction();
573   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
574   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
575   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
576   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
577 }
578
579 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
580   DebugLoc dl = Op.getDebugLoc();
581   // Depths > 0 not supported yet! 
582   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
583     return SDValue();
584   
585   MachineFunction &MF = DAG.getMachineFunction();
586   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
587   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, 
588                             RegInfo->getFrameRegister(MF), MVT::i32);
589 }
590
591 //===----------------------------------------------------------------------===//
592 //                      Calling Convention Implementation
593 //===----------------------------------------------------------------------===//
594
595 #include "XCoreGenCallingConv.inc"
596
597 //===----------------------------------------------------------------------===//
598 //                  Call Calling Convention Implementation
599 //===----------------------------------------------------------------------===//
600
601 /// XCore call implementation
602 SDValue
603 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
604                                CallingConv::ID CallConv, bool isVarArg,
605                                bool isTailCall,
606                                const SmallVectorImpl<ISD::OutputArg> &Outs,
607                                const SmallVectorImpl<ISD::InputArg> &Ins,
608                                DebugLoc dl, SelectionDAG &DAG,
609                                SmallVectorImpl<SDValue> &InVals) {
610
611   // For now, only CallingConv::C implemented
612   switch (CallConv)
613   {
614     default:
615       llvm_unreachable("Unsupported calling convention");
616     case CallingConv::Fast:
617     case CallingConv::C:
618       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
619                             Outs, Ins, dl, DAG, InVals);
620   }
621 }
622
623 /// LowerCCCCallTo - functions arguments are copied from virtual
624 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
625 /// CALLSEQ_END are emitted.
626 /// TODO: isTailCall, sret.
627 SDValue
628 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
629                                     CallingConv::ID CallConv, bool isVarArg,
630                                     bool isTailCall,
631                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
632                                     const SmallVectorImpl<ISD::InputArg> &Ins,
633                                     DebugLoc dl, SelectionDAG &DAG,
634                                     SmallVectorImpl<SDValue> &InVals) {
635
636   // Analyze operands of the call, assigning locations to each operand.
637   SmallVector<CCValAssign, 16> ArgLocs;
638   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
639                  ArgLocs, *DAG.getContext());
640
641   // The ABI dictates there should be one stack slot available to the callee
642   // on function entry (for saving lr).
643   CCInfo.AllocateStack(4, 4);
644
645   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
646
647   // Get a count of how many bytes are to be pushed on the stack.
648   unsigned NumBytes = CCInfo.getNextStackOffset();
649
650   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
651                                  getPointerTy(), true));
652
653   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
654   SmallVector<SDValue, 12> MemOpChains;
655
656   // Walk the register/memloc assignments, inserting copies/loads.
657   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
658     CCValAssign &VA = ArgLocs[i];
659     SDValue Arg = Outs[i].Val;
660
661     // Promote the value if needed.
662     switch (VA.getLocInfo()) {
663       default: llvm_unreachable("Unknown loc info!");
664       case CCValAssign::Full: break;
665       case CCValAssign::SExt:
666         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
667         break;
668       case CCValAssign::ZExt:
669         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
670         break;
671       case CCValAssign::AExt:
672         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
673         break;
674     }
675     
676     // Arguments that can be passed on register must be kept at 
677     // RegsToPass vector
678     if (VA.isRegLoc()) {
679       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
680     } else {
681       assert(VA.isMemLoc());
682
683       int Offset = VA.getLocMemOffset();
684
685       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 
686                                         Chain, Arg,
687                                         DAG.getConstant(Offset/4, MVT::i32)));
688     }
689   }
690
691   // Transform all store nodes into one single node because
692   // all store nodes are independent of each other.
693   if (!MemOpChains.empty())
694     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
695                         &MemOpChains[0], MemOpChains.size());
696
697   // Build a sequence of copy-to-reg nodes chained together with token 
698   // chain and flag operands which copy the outgoing args into registers.
699   // The InFlag in necessary since all emited instructions must be
700   // stuck together.
701   SDValue InFlag;
702   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
703     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
704                              RegsToPass[i].second, InFlag);
705     InFlag = Chain.getValue(1);
706   }
707
708   // If the callee is a GlobalAddress node (quite common, every direct call is)
709   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
710   // Likewise ExternalSymbol -> TargetExternalSymbol.
711   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
712     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
713   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
714     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
715
716   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
717   //             = Chain, Callee, Reg#1, Reg#2, ...  
718   //
719   // Returns a chain & a flag for retval copy to use.
720   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
721   SmallVector<SDValue, 8> Ops;
722   Ops.push_back(Chain);
723   Ops.push_back(Callee);
724
725   // Add argument registers to the end of the list so that they are 
726   // known live into the call.
727   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
728     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
729                                   RegsToPass[i].second.getValueType()));
730
731   if (InFlag.getNode())
732     Ops.push_back(InFlag);
733
734   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
735   InFlag = Chain.getValue(1);
736
737   // Create the CALLSEQ_END node.
738   Chain = DAG.getCALLSEQ_END(Chain,
739                              DAG.getConstant(NumBytes, getPointerTy(), true),
740                              DAG.getConstant(0, getPointerTy(), true),
741                              InFlag);
742   InFlag = Chain.getValue(1);
743
744   // Handle result values, copying them out of physregs into vregs that we
745   // return.
746   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
747                          Ins, dl, DAG, InVals);
748 }
749
750 /// LowerCallResult - Lower the result values of a call into the
751 /// appropriate copies out of appropriate physical registers.
752 SDValue
753 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
754                                      CallingConv::ID CallConv, bool isVarArg,
755                                      const SmallVectorImpl<ISD::InputArg> &Ins,
756                                      DebugLoc dl, SelectionDAG &DAG,
757                                      SmallVectorImpl<SDValue> &InVals) {
758
759   // Assign locations to each value returned by this call.
760   SmallVector<CCValAssign, 16> RVLocs;
761   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
762                  RVLocs, *DAG.getContext());
763
764   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
765
766   // Copy all of the result registers out of their specified physreg.
767   for (unsigned i = 0; i != RVLocs.size(); ++i) {
768     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
769                                  RVLocs[i].getValVT(), InFlag).getValue(1);
770     InFlag = Chain.getValue(2);
771     InVals.push_back(Chain.getValue(0));
772   }
773
774   return Chain;
775 }
776
777 //===----------------------------------------------------------------------===//
778 //             Formal Arguments Calling Convention Implementation
779 //===----------------------------------------------------------------------===//
780
781 /// XCore formal arguments implementation
782 SDValue
783 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
784                                           CallingConv::ID CallConv,
785                                           bool isVarArg,
786                                       const SmallVectorImpl<ISD::InputArg> &Ins,
787                                           DebugLoc dl,
788                                           SelectionDAG &DAG,
789                                           SmallVectorImpl<SDValue> &InVals) {
790   switch (CallConv)
791   {
792     default:
793       llvm_unreachable("Unsupported calling convention");
794     case CallingConv::C:
795     case CallingConv::Fast:
796       return LowerCCCArguments(Chain, CallConv, isVarArg,
797                                Ins, dl, DAG, InVals);
798   }
799 }
800
801 /// LowerCCCArguments - transform physical registers into
802 /// virtual registers and generate load operations for
803 /// arguments places on the stack.
804 /// TODO: sret
805 SDValue
806 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
807                                        CallingConv::ID CallConv,
808                                        bool isVarArg,
809                                        const SmallVectorImpl<ISD::InputArg>
810                                          &Ins,
811                                        DebugLoc dl,
812                                        SelectionDAG &DAG,
813                                        SmallVectorImpl<SDValue> &InVals) {
814   MachineFunction &MF = DAG.getMachineFunction();
815   MachineFrameInfo *MFI = MF.getFrameInfo();
816   MachineRegisterInfo &RegInfo = MF.getRegInfo();
817
818   // Assign locations to all of the incoming arguments.
819   SmallVector<CCValAssign, 16> ArgLocs;
820   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
821                  ArgLocs, *DAG.getContext());
822
823   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
824
825   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
826
827   unsigned LRSaveSize = StackSlotSize;
828   
829   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
830
831     CCValAssign &VA = ArgLocs[i];
832     
833     if (VA.isRegLoc()) {
834       // Arguments passed in registers
835       EVT RegVT = VA.getLocVT();
836       switch (RegVT.getSimpleVT().SimpleTy) {
837       default:
838         {
839 #ifndef NDEBUG
840           errs() << "LowerFormalArguments Unhandled argument type: "
841                  << RegVT.getSimpleVT().SimpleTy << "\n";
842 #endif
843           llvm_unreachable(0);
844         }
845       case MVT::i32:
846         unsigned VReg = RegInfo.createVirtualRegister(
847                           XCore::GRRegsRegisterClass);
848         RegInfo.addLiveIn(VA.getLocReg(), VReg);
849         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
850       }
851     } else {
852       // sanity check
853       assert(VA.isMemLoc());
854       // Load the argument to a virtual register
855       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
856       if (ObjSize > StackSlotSize) {
857         errs() << "LowerFormalArguments Unhandled argument type: "
858                << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
859                << "\n";
860       }
861       // Create the frame index object for this incoming parameter...
862       int FI = MFI->CreateFixedObject(ObjSize,
863                                       LRSaveSize + VA.getLocMemOffset(),
864                                       true, false);
865
866       // Create the SelectionDAG nodes corresponding to a load
867       //from this parameter
868       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
869       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
870     }
871   }
872   
873   if (isVarArg) {
874     /* Argument registers */
875     static const unsigned ArgRegs[] = {
876       XCore::R0, XCore::R1, XCore::R2, XCore::R3
877     };
878     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
879     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
880                                                      array_lengthof(ArgRegs));
881     if (FirstVAReg < array_lengthof(ArgRegs)) {
882       SmallVector<SDValue, 4> MemOps;
883       int offset = 0;
884       // Save remaining registers, storing higher register numbers at a higher
885       // address
886       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
887         // Create a stack slot
888         int FI = MFI->CreateFixedObject(4, offset, true, false);
889         if (i == FirstVAReg) {
890           XFI->setVarArgsFrameIndex(FI);
891         }
892         offset -= StackSlotSize;
893         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
894         // Move argument from phys reg -> virt reg
895         unsigned VReg = RegInfo.createVirtualRegister(
896                           XCore::GRRegsRegisterClass);
897         RegInfo.addLiveIn(ArgRegs[i], VReg);
898         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
899         // Move argument from virt reg -> stack
900         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
901         MemOps.push_back(Store);
902       }
903       if (!MemOps.empty())
904         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
905                             &MemOps[0], MemOps.size());
906     } else {
907       // This will point to the next argument passed via stack.
908       XFI->setVarArgsFrameIndex(
909         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
910                                true, false));
911     }
912   }
913   
914   return Chain;
915 }
916
917 //===----------------------------------------------------------------------===//
918 //               Return Value Calling Convention Implementation
919 //===----------------------------------------------------------------------===//
920
921 SDValue
922 XCoreTargetLowering::LowerReturn(SDValue Chain,
923                                  CallingConv::ID CallConv, bool isVarArg,
924                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
925                                  DebugLoc dl, SelectionDAG &DAG) {
926
927   // CCValAssign - represent the assignment of
928   // the return value to a location
929   SmallVector<CCValAssign, 16> RVLocs;
930
931   // CCState - Info about the registers and stack slot.
932   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
933                  RVLocs, *DAG.getContext());
934
935   // Analize return values.
936   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
937
938   // If this is the first return lowered for this function, add 
939   // the regs to the liveout set for the function.
940   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
941     for (unsigned i = 0; i != RVLocs.size(); ++i)
942       if (RVLocs[i].isRegLoc())
943         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
944   }
945
946   SDValue Flag;
947
948   // Copy the result values into the output registers.
949   for (unsigned i = 0; i != RVLocs.size(); ++i) {
950     CCValAssign &VA = RVLocs[i];
951     assert(VA.isRegLoc() && "Can only return in registers!");
952
953     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
954                              Outs[i].Val, Flag);
955
956     // guarantee that all emitted copies are
957     // stuck together, avoiding something bad
958     Flag = Chain.getValue(1);
959   }
960
961   // Return on XCore is always a "retsp 0"
962   if (Flag.getNode())
963     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
964                        Chain, DAG.getConstant(0, MVT::i32), Flag);
965   else // Return Void
966     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
967                        Chain, DAG.getConstant(0, MVT::i32));
968 }
969
970 //===----------------------------------------------------------------------===//
971 //  Other Lowering Code
972 //===----------------------------------------------------------------------===//
973
974 MachineBasicBlock *
975 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
976                                                  MachineBasicBlock *BB,
977                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
978   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
979   DebugLoc dl = MI->getDebugLoc();
980   assert((MI->getOpcode() == XCore::SELECT_CC) &&
981          "Unexpected instr type to insert");
982   
983   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
984   // control-flow pattern.  The incoming instruction knows the destination vreg
985   // to set, the condition code register to branch on, the true/false values to
986   // select between, and a branch opcode to use.
987   const BasicBlock *LLVM_BB = BB->getBasicBlock();
988   MachineFunction::iterator It = BB;
989   ++It;
990   
991   //  thisMBB:
992   //  ...
993   //   TrueVal = ...
994   //   cmpTY ccX, r1, r2
995   //   bCC copy1MBB
996   //   fallthrough --> copy0MBB
997   MachineBasicBlock *thisMBB = BB;
998   MachineFunction *F = BB->getParent();
999   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1000   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1001   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1002     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1003   F->insert(It, copy0MBB);
1004   F->insert(It, sinkMBB);
1005   // Update machine-CFG edges by first adding all successors of the current
1006   // block to the new block which will contain the Phi node for the select.
1007   // Also inform sdisel of the edge changes.
1008   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), 
1009          E = BB->succ_end(); I != E; ++I) {
1010     EM->insert(std::make_pair(*I, sinkMBB));
1011     sinkMBB->addSuccessor(*I);
1012   }
1013   // Next, remove all successors of the current block, and add the true
1014   // and fallthrough blocks as its successors.
1015   while (!BB->succ_empty())
1016     BB->removeSuccessor(BB->succ_begin());
1017   // Next, add the true and fallthrough blocks as its successors.
1018   BB->addSuccessor(copy0MBB);
1019   BB->addSuccessor(sinkMBB);
1020   
1021   //  copy0MBB:
1022   //   %FalseValue = ...
1023   //   # fallthrough to sinkMBB
1024   BB = copy0MBB;
1025   
1026   // Update machine-CFG edges
1027   BB->addSuccessor(sinkMBB);
1028   
1029   //  sinkMBB:
1030   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1031   //  ...
1032   BB = sinkMBB;
1033   BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1034     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1035     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1036   
1037   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1038   return BB;
1039 }
1040
1041 //===----------------------------------------------------------------------===//
1042 // Target Optimization Hooks
1043 //===----------------------------------------------------------------------===//
1044
1045 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1046                                              DAGCombinerInfo &DCI) const {
1047   SelectionDAG &DAG = DCI.DAG;
1048   DebugLoc dl = N->getDebugLoc();
1049   switch (N->getOpcode()) {
1050   default: break;
1051   case ISD::STORE: {
1052     // Replace unaligned store of unaligned load with memmove.
1053     StoreSDNode *ST  = cast<StoreSDNode>(N);
1054     if (!DCI.isBeforeLegalize() ||
1055         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1056         ST->isVolatile() || ST->isIndexed()) {
1057       break;
1058     }
1059     SDValue Chain = ST->getChain();
1060
1061     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1062     if (StoreBits % 8) {
1063       break;
1064     }
1065     unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1066         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1067     unsigned Alignment = ST->getAlignment();
1068     if (Alignment >= ABIAlignment) {
1069       break;
1070     }
1071
1072     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1073       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1074         LD->getAlignment() == Alignment &&
1075         !LD->isVolatile() && !LD->isIndexed() &&
1076         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1077         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1078                               LD->getBasePtr(),
1079                               DAG.getConstant(StoreBits/8, MVT::i32),
1080                               Alignment, ST->getSrcValue(),
1081                               ST->getSrcValueOffset(), LD->getSrcValue(),
1082                               LD->getSrcValueOffset());
1083       }
1084     }
1085     break;
1086   }
1087   }
1088   return SDValue();
1089 }
1090
1091 //===----------------------------------------------------------------------===//
1092 //  Addressing mode description hooks
1093 //===----------------------------------------------------------------------===//
1094
1095 static inline bool isImmUs(int64_t val)
1096 {
1097   return (val >= 0 && val <= 11);
1098 }
1099
1100 static inline bool isImmUs2(int64_t val)
1101 {
1102   return (val%2 == 0 && isImmUs(val/2));
1103 }
1104
1105 static inline bool isImmUs4(int64_t val)
1106 {
1107   return (val%4 == 0 && isImmUs(val/4));
1108 }
1109
1110 /// isLegalAddressingMode - Return true if the addressing mode represented
1111 /// by AM is legal for this target, for a load/store of the specified type.
1112 bool
1113 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1114                                               const Type *Ty) const {
1115   // Be conservative with void
1116   // FIXME: Can we be more aggressive?
1117   if (Ty->getTypeID() == Type::VoidTyID)
1118     return false;
1119
1120   const TargetData *TD = TM.getTargetData();
1121   unsigned Size = TD->getTypeAllocSize(Ty);
1122   if (AM.BaseGV) {
1123     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1124                  AM.BaseOffs%4 == 0;
1125   }
1126   
1127   switch (Size) {
1128   case 1:
1129     // reg + imm
1130     if (AM.Scale == 0) {
1131       return isImmUs(AM.BaseOffs);
1132     }
1133     // reg + reg
1134     return AM.Scale == 1 && AM.BaseOffs == 0;
1135   case 2:
1136   case 3:
1137     // reg + imm
1138     if (AM.Scale == 0) {
1139       return isImmUs2(AM.BaseOffs);
1140     }
1141     // reg + reg<<1
1142     return AM.Scale == 2 && AM.BaseOffs == 0;
1143   default:
1144     // reg + imm
1145     if (AM.Scale == 0) {
1146       return isImmUs4(AM.BaseOffs);
1147     }
1148     // reg + reg<<2
1149     return AM.Scale == 4 && AM.BaseOffs == 0;
1150   }
1151   
1152   return false;
1153 }
1154
1155 //===----------------------------------------------------------------------===//
1156 //                           XCore Inline Assembly Support
1157 //===----------------------------------------------------------------------===//
1158
1159 std::vector<unsigned> XCoreTargetLowering::
1160 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1161                                   EVT VT) const 
1162 {
1163   if (Constraint.size() != 1)
1164     return std::vector<unsigned>();
1165
1166   switch (Constraint[0]) {
1167     default : break;
1168     case 'r':
1169       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
1170                                    XCore::R3, XCore::R4,  XCore::R5, 
1171                                    XCore::R6, XCore::R7,  XCore::R8, 
1172                                    XCore::R9, XCore::R10, XCore::R11, 0);
1173       break;
1174   }
1175   return std::vector<unsigned>();
1176 }