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