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