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