828d6f92caf40ebc7c8fda774c1cbcb62563baae
[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::LMUL              : return "XCoreISD::LMUL";
58     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
59     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
60     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
61     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
62     default                          : return NULL;
63   }
64 }
65
66 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
67   : TargetLowering(XTM, new XCoreTargetObjectFile()),
68     TM(XTM),
69     Subtarget(*XTM.getSubtargetImpl()) {
70
71   // Set up the register classes.
72   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
73
74   // Compute derived properties from the register classes
75   computeRegisterProperties();
76
77   // Division is expensive
78   setIntDivIsCheap(false);
79
80   setShiftAmountType(MVT::i32);
81   setStackPointerRegisterToSaveRestore(XCore::SP);
82
83   setSchedulingPreference(Sched::RegPressure);
84
85   // Use i32 for setcc operations results (slt, sgt, ...).
86   setBooleanContents(ZeroOrOneBooleanContent);
87
88   // XCore does not have the NodeTypes below.
89   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
90   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
91   setOperationAction(ISD::ADDC, MVT::i32, Expand);
92   setOperationAction(ISD::ADDE, MVT::i32, Expand);
93   setOperationAction(ISD::SUBC, MVT::i32, Expand);
94   setOperationAction(ISD::SUBE, MVT::i32, Expand);
95
96   // Stop the combiner recombining select and set_cc
97   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
98   
99   // 64bit
100   setOperationAction(ISD::ADD, MVT::i64, Custom);
101   setOperationAction(ISD::SUB, MVT::i64, Custom);
102   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
103   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
104   setOperationAction(ISD::MULHS, MVT::i32, Expand);
105   setOperationAction(ISD::MULHU, MVT::i32, Expand);
106   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
108   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
109   
110   // Bit Manipulation
111   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
112   setOperationAction(ISD::ROTL , MVT::i32, Expand);
113   setOperationAction(ISD::ROTR , MVT::i32, Expand);
114   
115   setOperationAction(ISD::TRAP, MVT::Other, Legal);
116   
117   // Jump tables.
118   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
119
120   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
121   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
122
123   // Thread Local Storage
124   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
125   
126   // Conversion of i64 -> double produces constantpool nodes
127   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
128
129   // Loads
130   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
131   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
132   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133
134   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
135   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
136
137   // Custom expand misaligned loads / stores.
138   setOperationAction(ISD::LOAD, MVT::i32, Custom);
139   setOperationAction(ISD::STORE, MVT::i32, Custom);
140
141   // Varargs
142   setOperationAction(ISD::VAEND, MVT::Other, Expand);
143   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
144   setOperationAction(ISD::VAARG, MVT::Other, Custom);
145   setOperationAction(ISD::VASTART, MVT::Other, Custom);
146   
147   // Dynamic stack
148   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
149   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
150   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
151
152   // TRAMPOLINE is custom lowered.
153   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
154
155   maxStoresPerMemset = maxStoresPerMemsetOptSize = 4;
156   maxStoresPerMemmove = maxStoresPerMemmoveOptSize
157     = maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 2;
158
159   // We have target-specific dag combine patterns for the following nodes:
160   setTargetDAGCombine(ISD::STORE);
161   setTargetDAGCombine(ISD::ADD);
162 }
163
164 SDValue XCoreTargetLowering::
165 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
166   switch (Op.getOpcode()) 
167   {
168   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
169   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
170   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
171   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
172   case ISD::BR_JT:            return LowerBR_JT(Op, DAG);
173   case ISD::LOAD:             return LowerLOAD(Op, DAG);
174   case ISD::STORE:            return LowerSTORE(Op, DAG);
175   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
176   case ISD::VAARG:            return LowerVAARG(Op, DAG);
177   case ISD::VASTART:          return LowerVASTART(Op, DAG);
178   case ISD::SMUL_LOHI:        return LowerSMUL_LOHI(Op, DAG);
179   case ISD::UMUL_LOHI:        return LowerUMUL_LOHI(Op, DAG);
180   // FIXME: Remove these when LegalizeDAGTypes lands.
181   case ISD::ADD:
182   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
183   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
184   case ISD::TRAMPOLINE:       return LowerTRAMPOLINE(Op, DAG);
185   default:
186     llvm_unreachable("unimplemented operand");
187     return SDValue();
188   }
189 }
190
191 /// ReplaceNodeResults - Replace the results of node with an illegal result
192 /// type with new values built out of custom code.
193 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
194                                              SmallVectorImpl<SDValue>&Results,
195                                              SelectionDAG &DAG) const {
196   switch (N->getOpcode()) {
197   default:
198     llvm_unreachable("Don't know how to custom expand this!");
199     return;
200   case ISD::ADD:
201   case ISD::SUB:
202     Results.push_back(ExpandADDSUB(N, DAG));
203     return;
204   }
205 }
206
207 /// getFunctionAlignment - Return the Log2 alignment of this function.
208 unsigned XCoreTargetLowering::
209 getFunctionAlignment(const Function *) const {
210   return 1;
211 }
212
213 //===----------------------------------------------------------------------===//
214 //  Misc Lower Operation implementation
215 //===----------------------------------------------------------------------===//
216
217 SDValue XCoreTargetLowering::
218 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
219 {
220   DebugLoc dl = Op.getDebugLoc();
221   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
222                              Op.getOperand(3), Op.getOperand(4));
223   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
224                      Op.getOperand(1));
225 }
226
227 SDValue XCoreTargetLowering::
228 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
229                         SelectionDAG &DAG) const
230 {
231   // FIXME there is no actual debug info here
232   DebugLoc dl = GA.getDebugLoc();
233   if (isa<Function>(GV)) {
234     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
235   }
236   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
237   if (!GVar) {
238     // If GV is an alias then use the aliasee to determine constness
239     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
240       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
241   }
242   bool isConst = GVar && GVar->isConstant();
243   if (isConst) {
244     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
245   }
246   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
247 }
248
249 SDValue XCoreTargetLowering::
250 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
251 {
252   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
253   SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
254   // If it's a debug information descriptor, don't mess with it.
255   if (DAG.isVerifiedDebugInfoDesc(Op))
256     return GA;
257   return getGlobalAddressWrapper(GA, GV, DAG);
258 }
259
260 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
261   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
262                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
263 }
264
265 static inline bool isZeroLengthArray(const Type *Ty) {
266   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
267   return AT && (AT->getNumElements() == 0);
268 }
269
270 SDValue XCoreTargetLowering::
271 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
272 {
273   // FIXME there isn't really debug info here
274   DebugLoc dl = Op.getDebugLoc();
275   // transform to label + getid() * size
276   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
277   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
278   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
279   if (!GVar) {
280     // If GV is an alias then use the aliasee to determine size
281     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
282       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
283   }
284   if (! GVar) {
285     llvm_unreachable("Thread local object not a GlobalVariable?");
286     return SDValue();
287   }
288   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
289   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
290 #ifndef NDEBUG
291     errs() << "Size of thread local object " << GVar->getName()
292            << " is unknown\n";
293 #endif
294     llvm_unreachable(0);
295   }
296   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
297   const TargetData *TD = TM.getTargetData();
298   unsigned Size = TD->getTypeAllocSize(Ty);
299   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
300                        DAG.getConstant(Size, MVT::i32));
301   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
302 }
303
304 SDValue XCoreTargetLowering::
305 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
306 {
307   DebugLoc DL = Op.getDebugLoc();
308
309   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
310   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
311
312   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
313 }
314
315 SDValue XCoreTargetLowering::
316 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
317 {
318   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
319   // FIXME there isn't really debug info here
320   DebugLoc dl = CP->getDebugLoc();
321   EVT PtrVT = Op.getValueType();
322   SDValue Res;
323   if (CP->isMachineConstantPoolEntry()) {
324     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
325                                     CP->getAlignment());
326   } else {
327     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
328                                     CP->getAlignment());
329   }
330   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
331 }
332
333 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
334   return MachineJumpTableInfo::EK_Inline;
335 }
336
337 SDValue XCoreTargetLowering::
338 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
339 {
340   SDValue Chain = Op.getOperand(0);
341   SDValue Table = Op.getOperand(1);
342   SDValue Index = Op.getOperand(2);
343   DebugLoc dl = Op.getDebugLoc();
344   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
345   unsigned JTI = JT->getIndex();
346   MachineFunction &MF = DAG.getMachineFunction();
347   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
348   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
349
350   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
351   if (NumEntries <= 32) {
352     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
353   }
354   assert((NumEntries >> 31) == 0);
355   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
356                                     DAG.getConstant(1, MVT::i32));
357   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
358                      ScaledIndex);
359 }
360
361 static bool
362 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
363                                     int64_t &Offset)
364 {
365   if (Addr.getOpcode() != ISD::ADD) {
366     return false;
367   }
368   ConstantSDNode *CN = 0;
369   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
370     return false;
371   }
372   int64_t off = CN->getSExtValue();
373   const SDValue &Base = Addr.getOperand(0);
374   const SDValue *Root = &Base;
375   if (Base.getOpcode() == ISD::ADD &&
376       Base.getOperand(1).getOpcode() == ISD::SHL) {
377     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
378                                                       .getOperand(1));
379     if (CN && (CN->getSExtValue() >= 2)) {
380       Root = &Base.getOperand(0);
381     }
382   }
383   if (isa<FrameIndexSDNode>(*Root)) {
384     // All frame indicies are word aligned
385     AlignedBase = Base;
386     Offset = off;
387     return true;
388   }
389   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
390       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
391     // All dp / cp relative addresses are word aligned
392     AlignedBase = Base;
393     Offset = off;
394     return true;
395   }
396   return false;
397 }
398
399 SDValue XCoreTargetLowering::
400 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
401   LoadSDNode *LD = cast<LoadSDNode>(Op);
402   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
403          "Unexpected extension type");
404   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
405   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
406     return SDValue();
407
408   unsigned ABIAlignment = getTargetData()->
409     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
410   // Leave aligned load alone.
411   if (LD->getAlignment() >= ABIAlignment)
412     return SDValue();
413
414   SDValue Chain = LD->getChain();
415   SDValue BasePtr = LD->getBasePtr();
416   DebugLoc DL = Op.getDebugLoc();
417   
418   SDValue Base;
419   int64_t Offset;
420   if (!LD->isVolatile() &&
421       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
422     if (Offset % 4 == 0) {
423       // We've managed to infer better alignment information than the load
424       // already has. Use an aligned load.
425       //
426       return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
427                          MachinePointerInfo(),
428                          false, false, 0);
429     }
430     // Lower to
431     // ldw low, base[offset >> 2]
432     // ldw high, base[(offset >> 2) + 1]
433     // shr low_shifted, low, (offset & 0x3) * 8
434     // shl high_shifted, high, 32 - (offset & 0x3) * 8
435     // or result, low_shifted, high_shifted
436     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
437     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
438     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
439     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
440     
441     SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
442     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
443     
444     SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
445                               LowAddr, MachinePointerInfo(), false, false, 0);
446     SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
447                                HighAddr, MachinePointerInfo(), false, false, 0);
448     SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
449     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
450     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
451     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
452                              High.getValue(1));
453     SDValue Ops[] = { Result, Chain };
454     return DAG.getMergeValues(Ops, 2, DL);
455   }
456   
457   if (LD->getAlignment() == 2) {
458     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
459                                  BasePtr, LD->getPointerInfo(), MVT::i16,
460                                  LD->isVolatile(), LD->isNonTemporal(), 2);
461     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
462                                    DAG.getConstant(2, MVT::i32));
463     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
464                                   HighAddr,
465                                   LD->getPointerInfo().getWithOffset(2),
466                                   MVT::i16, LD->isVolatile(),
467                                   LD->isNonTemporal(), 2);
468     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
469                                       DAG.getConstant(16, MVT::i32));
470     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
471     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
472                              High.getValue(1));
473     SDValue Ops[] = { Result, Chain };
474     return DAG.getMergeValues(Ops, 2, DL);
475   }
476   
477   // Lower to a call to __misaligned_load(BasePtr).
478   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
479   TargetLowering::ArgListTy Args;
480   TargetLowering::ArgListEntry Entry;
481   
482   Entry.Ty = IntPtrTy;
483   Entry.Node = BasePtr;
484   Args.push_back(Entry);
485   
486   std::pair<SDValue, SDValue> CallResult =
487         LowerCallTo(Chain, IntPtrTy, false, false,
488                     false, false, 0, CallingConv::C, false,
489                     /*isReturnValueUsed=*/true,
490                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
491                     Args, DAG, DL);
492
493   SDValue Ops[] =
494     { CallResult.first, CallResult.second };
495
496   return DAG.getMergeValues(Ops, 2, DL);
497 }
498
499 SDValue XCoreTargetLowering::
500 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
501 {
502   StoreSDNode *ST = cast<StoreSDNode>(Op);
503   assert(!ST->isTruncatingStore() && "Unexpected store type");
504   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
505   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
506     return SDValue();
507   }
508   unsigned ABIAlignment = getTargetData()->
509     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
510   // Leave aligned store alone.
511   if (ST->getAlignment() >= ABIAlignment) {
512     return SDValue();
513   }
514   SDValue Chain = ST->getChain();
515   SDValue BasePtr = ST->getBasePtr();
516   SDValue Value = ST->getValue();
517   DebugLoc dl = Op.getDebugLoc();
518   
519   if (ST->getAlignment() == 2) {
520     SDValue Low = Value;
521     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
522                                       DAG.getConstant(16, MVT::i32));
523     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
524                                          ST->getPointerInfo(), MVT::i16,
525                                          ST->isVolatile(), ST->isNonTemporal(),
526                                          2);
527     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
528                                    DAG.getConstant(2, MVT::i32));
529     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
530                                           ST->getPointerInfo().getWithOffset(2),
531                                           MVT::i16, ST->isVolatile(),
532                                           ST->isNonTemporal(), 2);
533     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
534   }
535   
536   // Lower to a call to __misaligned_store(BasePtr, Value).
537   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
538   TargetLowering::ArgListTy Args;
539   TargetLowering::ArgListEntry Entry;
540   
541   Entry.Ty = IntPtrTy;
542   Entry.Node = BasePtr;
543   Args.push_back(Entry);
544   
545   Entry.Node = Value;
546   Args.push_back(Entry);
547   
548   std::pair<SDValue, SDValue> CallResult =
549         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
550                     false, false, 0, CallingConv::C, false,
551                     /*isReturnValueUsed=*/true,
552                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
553                     Args, DAG, dl);
554
555   return CallResult.second;
556 }
557
558 SDValue XCoreTargetLowering::
559 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
560 {
561   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
562          "Unexpected operand to lower!");
563   DebugLoc dl = Op.getDebugLoc();
564   SDValue LHS = Op.getOperand(0);
565   SDValue RHS = Op.getOperand(1);
566   SDValue Zero = DAG.getConstant(0, MVT::i32);
567   SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
568                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
569                            LHS, RHS);
570   SDValue Lo(Hi.getNode(), 1);
571   SDValue Ops[] = { Lo, Hi };
572   return DAG.getMergeValues(Ops, 2, dl);
573 }
574
575 SDValue XCoreTargetLowering::
576 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
577 {
578   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
579          "Unexpected operand to lower!");
580   DebugLoc dl = Op.getDebugLoc();
581   SDValue LHS = Op.getOperand(0);
582   SDValue RHS = Op.getOperand(1);
583   SDValue Zero = DAG.getConstant(0, MVT::i32);
584   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
585                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
586                            Zero, Zero);
587   SDValue Lo(Hi.getNode(), 1);
588   SDValue Ops[] = { Lo, Hi };
589   return DAG.getMergeValues(Ops, 2, dl);
590 }
591
592 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
593 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
594 /// each intermediate result in the calculation must also have a single use.
595 /// If the Op is in the correct form the constituent parts are written to Mul0,
596 /// Mul1, Addend0 and Addend1.
597 static bool
598 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
599             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
600 {
601   if (Op.getOpcode() != ISD::ADD)
602     return false;
603   SDValue N0 = Op.getOperand(0);
604   SDValue N1 = Op.getOperand(1);
605   SDValue AddOp;
606   SDValue OtherOp;
607   if (N0.getOpcode() == ISD::ADD) {
608     AddOp = N0;
609     OtherOp = N1;
610   } else if (N1.getOpcode() == ISD::ADD) {
611     AddOp = N1;
612     OtherOp = N0;
613   } else {
614     return false;
615   }
616   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
617     return false;
618   if (OtherOp.getOpcode() == ISD::MUL) {
619     // add(add(a,b),mul(x,y))
620     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
621       return false;
622     Mul0 = OtherOp.getOperand(0);
623     Mul1 = OtherOp.getOperand(1);
624     Addend0 = AddOp.getOperand(0);
625     Addend1 = AddOp.getOperand(1);
626     return true;
627   }
628   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
629     // add(add(mul(x,y),a),b)
630     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
631       return false;
632     Mul0 = AddOp.getOperand(0).getOperand(0);
633     Mul1 = AddOp.getOperand(0).getOperand(1);
634     Addend0 = AddOp.getOperand(1);
635     Addend1 = OtherOp;
636     return true;
637   }
638   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
639     // add(add(a,mul(x,y)),b)
640     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
641       return false;
642     Mul0 = AddOp.getOperand(1).getOperand(0);
643     Mul1 = AddOp.getOperand(1).getOperand(1);
644     Addend0 = AddOp.getOperand(0);
645     Addend1 = OtherOp;
646     return true;
647   }
648   return false;
649 }
650
651 SDValue XCoreTargetLowering::
652 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
653 {
654   SDValue Mul;
655   SDValue Other;
656   if (N->getOperand(0).getOpcode() == ISD::MUL) {
657     Mul = N->getOperand(0);
658     Other = N->getOperand(1);
659   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
660     Mul = N->getOperand(1);
661     Other = N->getOperand(0);
662   } else {
663     return SDValue();
664   }
665   DebugLoc dl = N->getDebugLoc();
666   SDValue LL, RL, AddendL, AddendH;
667   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
668                    Mul.getOperand(0),  DAG.getConstant(0, MVT::i32));
669   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
670                    Mul.getOperand(1),  DAG.getConstant(0, MVT::i32));
671   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
672                         Other,  DAG.getConstant(0, MVT::i32));
673   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
674                         Other,  DAG.getConstant(1, MVT::i32));
675   APInt HighMask = APInt::getHighBitsSet(64, 32);
676   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
677   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
678   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
679       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
680     // The inputs are both zero-extended.
681     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
682                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
683                              AddendL, LL, RL);
684     SDValue Lo(Hi.getNode(), 1);
685     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
686   }
687   if (LHSSB > 32 && RHSSB > 32) {
688     // The inputs are both sign-extended.
689     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
690                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
691                              AddendL, LL, RL);
692     SDValue Lo(Hi.getNode(), 1);
693     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
694   }
695   SDValue LH, RH;
696   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
697                    Mul.getOperand(0),  DAG.getConstant(1, MVT::i32));
698   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
699                    Mul.getOperand(1),  DAG.getConstant(1, MVT::i32));
700   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
701                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
702                            AddendL, LL, RL);
703   SDValue Lo(Hi.getNode(), 1);
704   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
705   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
706   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
707   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
708   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
709 }
710
711 SDValue XCoreTargetLowering::
712 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
713 {
714   assert(N->getValueType(0) == MVT::i64 &&
715          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
716         "Unknown operand to lower!");
717
718   if (N->getOpcode() == ISD::ADD) {
719     SDValue Result = TryExpandADDWithMul(N, DAG);
720     if (Result.getNode() != 0)
721       return Result;
722   }
723
724   DebugLoc dl = N->getDebugLoc();
725   
726   // Extract components
727   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
728                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
729   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
730                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
731   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
732                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
733   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
734                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
735   
736   // Expand
737   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
738                                                    XCoreISD::LSUB;
739   SDValue Zero = DAG.getConstant(0, MVT::i32);
740   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
741                                   LHSL, RHSL, Zero);
742   SDValue Lo(Carry.getNode(), 1);
743   
744   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
745                                   LHSH, RHSH, Carry);
746   SDValue Hi(Ignored.getNode(), 1);
747   // Merge the pieces
748   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
749 }
750
751 SDValue XCoreTargetLowering::
752 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
753 {
754   llvm_unreachable("unimplemented");
755   // FIX Arguments passed by reference need a extra dereference.
756   SDNode *Node = Op.getNode();
757   DebugLoc dl = Node->getDebugLoc();
758   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
759   EVT VT = Node->getValueType(0);
760   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
761                                Node->getOperand(1), MachinePointerInfo(V),
762                                false, false, 0);
763   // Increment the pointer, VAList, to the next vararg
764   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList, 
765                      DAG.getConstant(VT.getSizeInBits(), 
766                                      getPointerTy()));
767   // Store the incremented VAList to the legalized pointer
768   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
769                       MachinePointerInfo(V), false, false, 0);
770   // Load the actual argument out of the pointer VAList
771   return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
772                      false, false, 0);
773 }
774
775 SDValue XCoreTargetLowering::
776 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
777 {
778   DebugLoc dl = Op.getDebugLoc();
779   // vastart stores the address of the VarArgsFrameIndex slot into the
780   // memory location argument
781   MachineFunction &MF = DAG.getMachineFunction();
782   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
783   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
784   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), 
785                       MachinePointerInfo(), false, false, 0);
786 }
787
788 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
789                                             SelectionDAG &DAG) const {
790   DebugLoc dl = Op.getDebugLoc();
791   // Depths > 0 not supported yet! 
792   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
793     return SDValue();
794   
795   MachineFunction &MF = DAG.getMachineFunction();
796   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
797   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, 
798                             RegInfo->getFrameRegister(MF), MVT::i32);
799 }
800
801 SDValue XCoreTargetLowering::
802 LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
803   SDValue Chain = Op.getOperand(0);
804   SDValue Trmp = Op.getOperand(1); // trampoline
805   SDValue FPtr = Op.getOperand(2); // nested function
806   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
807
808   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
809
810   // .align 4
811   // LDAPF_u10 r11, nest
812   // LDW_2rus r11, r11[0]
813   // STWSP_ru6 r11, sp[0]
814   // LDAPF_u10 r11, fptr
815   // LDW_2rus r11, r11[0]
816   // BAU_1r r11
817   // nest:
818   // .word nest
819   // fptr:
820   // .word fptr
821   SDValue OutChains[5];
822
823   SDValue Addr = Trmp;
824
825   DebugLoc dl = Op.getDebugLoc();
826   OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
827                               Addr, MachinePointerInfo(TrmpAddr), false, false,
828                               0);
829
830   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
831                      DAG.getConstant(4, MVT::i32));
832   OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
833                               Addr, MachinePointerInfo(TrmpAddr, 4), false,
834                               false, 0);
835
836   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
837                      DAG.getConstant(8, MVT::i32));
838   OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
839                               Addr, MachinePointerInfo(TrmpAddr, 8), false,
840                               false, 0);
841
842   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
843                      DAG.getConstant(12, MVT::i32));
844   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
845                               MachinePointerInfo(TrmpAddr, 12), false, false,
846                               0);
847
848   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
849                      DAG.getConstant(16, MVT::i32));
850   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
851                               MachinePointerInfo(TrmpAddr, 16), false, false,
852                               0);
853
854   SDValue Ops[] =
855     { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5) };
856   return DAG.getMergeValues(Ops, 2, dl);
857 }
858
859 //===----------------------------------------------------------------------===//
860 //                      Calling Convention Implementation
861 //===----------------------------------------------------------------------===//
862
863 #include "XCoreGenCallingConv.inc"
864
865 //===----------------------------------------------------------------------===//
866 //                  Call Calling Convention Implementation
867 //===----------------------------------------------------------------------===//
868
869 /// XCore call implementation
870 SDValue
871 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
872                                CallingConv::ID CallConv, bool isVarArg,
873                                bool &isTailCall,
874                                const SmallVectorImpl<ISD::OutputArg> &Outs,
875                                const SmallVectorImpl<SDValue> &OutVals,
876                                const SmallVectorImpl<ISD::InputArg> &Ins,
877                                DebugLoc dl, SelectionDAG &DAG,
878                                SmallVectorImpl<SDValue> &InVals) const {
879   // XCore target does not yet support tail call optimization.
880   isTailCall = false;
881
882   // For now, only CallingConv::C implemented
883   switch (CallConv)
884   {
885     default:
886       llvm_unreachable("Unsupported calling convention");
887     case CallingConv::Fast:
888     case CallingConv::C:
889       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
890                             Outs, OutVals, Ins, dl, DAG, InVals);
891   }
892 }
893
894 /// LowerCCCCallTo - functions arguments are copied from virtual
895 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
896 /// CALLSEQ_END are emitted.
897 /// TODO: isTailCall, sret.
898 SDValue
899 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
900                                     CallingConv::ID CallConv, bool isVarArg,
901                                     bool isTailCall,
902                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
903                                     const SmallVectorImpl<SDValue> &OutVals,
904                                     const SmallVectorImpl<ISD::InputArg> &Ins,
905                                     DebugLoc dl, SelectionDAG &DAG,
906                                     SmallVectorImpl<SDValue> &InVals) const {
907
908   // Analyze operands of the call, assigning locations to each operand.
909   SmallVector<CCValAssign, 16> ArgLocs;
910   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
911                  ArgLocs, *DAG.getContext());
912
913   // The ABI dictates there should be one stack slot available to the callee
914   // on function entry (for saving lr).
915   CCInfo.AllocateStack(4, 4);
916
917   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
918
919   // Get a count of how many bytes are to be pushed on the stack.
920   unsigned NumBytes = CCInfo.getNextStackOffset();
921
922   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
923                                  getPointerTy(), true));
924
925   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
926   SmallVector<SDValue, 12> MemOpChains;
927
928   // Walk the register/memloc assignments, inserting copies/loads.
929   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
930     CCValAssign &VA = ArgLocs[i];
931     SDValue Arg = OutVals[i];
932
933     // Promote the value if needed.
934     switch (VA.getLocInfo()) {
935       default: llvm_unreachable("Unknown loc info!");
936       case CCValAssign::Full: break;
937       case CCValAssign::SExt:
938         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
939         break;
940       case CCValAssign::ZExt:
941         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
942         break;
943       case CCValAssign::AExt:
944         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
945         break;
946     }
947     
948     // Arguments that can be passed on register must be kept at 
949     // RegsToPass vector
950     if (VA.isRegLoc()) {
951       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
952     } else {
953       assert(VA.isMemLoc());
954
955       int Offset = VA.getLocMemOffset();
956
957       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 
958                                         Chain, Arg,
959                                         DAG.getConstant(Offset/4, MVT::i32)));
960     }
961   }
962
963   // Transform all store nodes into one single node because
964   // all store nodes are independent of each other.
965   if (!MemOpChains.empty())
966     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
967                         &MemOpChains[0], MemOpChains.size());
968
969   // Build a sequence of copy-to-reg nodes chained together with token 
970   // chain and flag operands which copy the outgoing args into registers.
971   // The InFlag in necessary since all emited instructions must be
972   // stuck together.
973   SDValue InFlag;
974   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
975     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
976                              RegsToPass[i].second, InFlag);
977     InFlag = Chain.getValue(1);
978   }
979
980   // If the callee is a GlobalAddress node (quite common, every direct call is)
981   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
982   // Likewise ExternalSymbol -> TargetExternalSymbol.
983   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
984     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
985   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
986     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
987
988   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
989   //             = Chain, Callee, Reg#1, Reg#2, ...  
990   //
991   // Returns a chain & a flag for retval copy to use.
992   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
993   SmallVector<SDValue, 8> Ops;
994   Ops.push_back(Chain);
995   Ops.push_back(Callee);
996
997   // Add argument registers to the end of the list so that they are 
998   // known live into the call.
999   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1000     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1001                                   RegsToPass[i].second.getValueType()));
1002
1003   if (InFlag.getNode())
1004     Ops.push_back(InFlag);
1005
1006   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1007   InFlag = Chain.getValue(1);
1008
1009   // Create the CALLSEQ_END node.
1010   Chain = DAG.getCALLSEQ_END(Chain,
1011                              DAG.getConstant(NumBytes, getPointerTy(), true),
1012                              DAG.getConstant(0, getPointerTy(), true),
1013                              InFlag);
1014   InFlag = Chain.getValue(1);
1015
1016   // Handle result values, copying them out of physregs into vregs that we
1017   // return.
1018   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1019                          Ins, dl, DAG, InVals);
1020 }
1021
1022 /// LowerCallResult - Lower the result values of a call into the
1023 /// appropriate copies out of appropriate physical registers.
1024 SDValue
1025 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1026                                      CallingConv::ID CallConv, bool isVarArg,
1027                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1028                                      DebugLoc dl, SelectionDAG &DAG,
1029                                      SmallVectorImpl<SDValue> &InVals) const {
1030
1031   // Assign locations to each value returned by this call.
1032   SmallVector<CCValAssign, 16> RVLocs;
1033   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1034                  RVLocs, *DAG.getContext());
1035
1036   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1037
1038   // Copy all of the result registers out of their specified physreg.
1039   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1040     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1041                                  RVLocs[i].getValVT(), InFlag).getValue(1);
1042     InFlag = Chain.getValue(2);
1043     InVals.push_back(Chain.getValue(0));
1044   }
1045
1046   return Chain;
1047 }
1048
1049 //===----------------------------------------------------------------------===//
1050 //             Formal Arguments Calling Convention Implementation
1051 //===----------------------------------------------------------------------===//
1052
1053 /// XCore formal arguments implementation
1054 SDValue
1055 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1056                                           CallingConv::ID CallConv,
1057                                           bool isVarArg,
1058                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1059                                           DebugLoc dl,
1060                                           SelectionDAG &DAG,
1061                                           SmallVectorImpl<SDValue> &InVals)
1062                                             const {
1063   switch (CallConv)
1064   {
1065     default:
1066       llvm_unreachable("Unsupported calling convention");
1067     case CallingConv::C:
1068     case CallingConv::Fast:
1069       return LowerCCCArguments(Chain, CallConv, isVarArg,
1070                                Ins, dl, DAG, InVals);
1071   }
1072 }
1073
1074 /// LowerCCCArguments - transform physical registers into
1075 /// virtual registers and generate load operations for
1076 /// arguments places on the stack.
1077 /// TODO: sret
1078 SDValue
1079 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1080                                        CallingConv::ID CallConv,
1081                                        bool isVarArg,
1082                                        const SmallVectorImpl<ISD::InputArg>
1083                                          &Ins,
1084                                        DebugLoc dl,
1085                                        SelectionDAG &DAG,
1086                                        SmallVectorImpl<SDValue> &InVals) const {
1087   MachineFunction &MF = DAG.getMachineFunction();
1088   MachineFrameInfo *MFI = MF.getFrameInfo();
1089   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1090
1091   // Assign locations to all of the incoming arguments.
1092   SmallVector<CCValAssign, 16> ArgLocs;
1093   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1094                  ArgLocs, *DAG.getContext());
1095
1096   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1097
1098   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1099
1100   unsigned LRSaveSize = StackSlotSize;
1101   
1102   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1103
1104     CCValAssign &VA = ArgLocs[i];
1105     
1106     if (VA.isRegLoc()) {
1107       // Arguments passed in registers
1108       EVT RegVT = VA.getLocVT();
1109       switch (RegVT.getSimpleVT().SimpleTy) {
1110       default:
1111         {
1112 #ifndef NDEBUG
1113           errs() << "LowerFormalArguments Unhandled argument type: "
1114                  << RegVT.getSimpleVT().SimpleTy << "\n";
1115 #endif
1116           llvm_unreachable(0);
1117         }
1118       case MVT::i32:
1119         unsigned VReg = RegInfo.createVirtualRegister(
1120                           XCore::GRRegsRegisterClass);
1121         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1122         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1123       }
1124     } else {
1125       // sanity check
1126       assert(VA.isMemLoc());
1127       // Load the argument to a virtual register
1128       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1129       if (ObjSize > StackSlotSize) {
1130         errs() << "LowerFormalArguments Unhandled argument type: "
1131                << EVT(VA.getLocVT()).getEVTString()
1132                << "\n";
1133       }
1134       // Create the frame index object for this incoming parameter...
1135       int FI = MFI->CreateFixedObject(ObjSize,
1136                                       LRSaveSize + VA.getLocMemOffset(),
1137                                       true);
1138
1139       // Create the SelectionDAG nodes corresponding to a load
1140       //from this parameter
1141       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1142       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, 
1143                                    MachinePointerInfo::getFixedStack(FI),
1144                                    false, false, 0));
1145     }
1146   }
1147   
1148   if (isVarArg) {
1149     /* Argument registers */
1150     static const unsigned ArgRegs[] = {
1151       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1152     };
1153     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1154     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1155                                                      array_lengthof(ArgRegs));
1156     if (FirstVAReg < array_lengthof(ArgRegs)) {
1157       SmallVector<SDValue, 4> MemOps;
1158       int offset = 0;
1159       // Save remaining registers, storing higher register numbers at a higher
1160       // address
1161       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1162         // Create a stack slot
1163         int FI = MFI->CreateFixedObject(4, offset, true);
1164         if (i == FirstVAReg) {
1165           XFI->setVarArgsFrameIndex(FI);
1166         }
1167         offset -= StackSlotSize;
1168         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1169         // Move argument from phys reg -> virt reg
1170         unsigned VReg = RegInfo.createVirtualRegister(
1171                           XCore::GRRegsRegisterClass);
1172         RegInfo.addLiveIn(ArgRegs[i], VReg);
1173         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1174         // Move argument from virt reg -> stack
1175         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1176                                      MachinePointerInfo(), false, false, 0);
1177         MemOps.push_back(Store);
1178       }
1179       if (!MemOps.empty())
1180         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1181                             &MemOps[0], MemOps.size());
1182     } else {
1183       // This will point to the next argument passed via stack.
1184       XFI->setVarArgsFrameIndex(
1185         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1186                                true));
1187     }
1188   }
1189   
1190   return Chain;
1191 }
1192
1193 //===----------------------------------------------------------------------===//
1194 //               Return Value Calling Convention Implementation
1195 //===----------------------------------------------------------------------===//
1196
1197 bool XCoreTargetLowering::
1198 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1199                const SmallVectorImpl<ISD::OutputArg> &Outs,
1200                LLVMContext &Context) const {
1201   SmallVector<CCValAssign, 16> RVLocs;
1202   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1203                  RVLocs, Context);
1204   return CCInfo.CheckReturn(Outs, RetCC_XCore);
1205 }
1206
1207 SDValue
1208 XCoreTargetLowering::LowerReturn(SDValue Chain,
1209                                  CallingConv::ID CallConv, bool isVarArg,
1210                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1211                                  const SmallVectorImpl<SDValue> &OutVals,
1212                                  DebugLoc dl, SelectionDAG &DAG) const {
1213
1214   // CCValAssign - represent the assignment of
1215   // the return value to a location
1216   SmallVector<CCValAssign, 16> RVLocs;
1217
1218   // CCState - Info about the registers and stack slot.
1219   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1220                  RVLocs, *DAG.getContext());
1221
1222   // Analize return values.
1223   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1224
1225   // If this is the first return lowered for this function, add 
1226   // the regs to the liveout set for the function.
1227   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1228     for (unsigned i = 0; i != RVLocs.size(); ++i)
1229       if (RVLocs[i].isRegLoc())
1230         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1231   }
1232
1233   SDValue Flag;
1234
1235   // Copy the result values into the output registers.
1236   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1237     CCValAssign &VA = RVLocs[i];
1238     assert(VA.isRegLoc() && "Can only return in registers!");
1239
1240     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
1241                              OutVals[i], Flag);
1242
1243     // guarantee that all emitted copies are
1244     // stuck together, avoiding something bad
1245     Flag = Chain.getValue(1);
1246   }
1247
1248   // Return on XCore is always a "retsp 0"
1249   if (Flag.getNode())
1250     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1251                        Chain, DAG.getConstant(0, MVT::i32), Flag);
1252   else // Return Void
1253     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1254                        Chain, DAG.getConstant(0, MVT::i32));
1255 }
1256
1257 //===----------------------------------------------------------------------===//
1258 //  Other Lowering Code
1259 //===----------------------------------------------------------------------===//
1260
1261 MachineBasicBlock *
1262 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1263                                                  MachineBasicBlock *BB) const {
1264   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1265   DebugLoc dl = MI->getDebugLoc();
1266   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1267          "Unexpected instr type to insert");
1268   
1269   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1270   // control-flow pattern.  The incoming instruction knows the destination vreg
1271   // to set, the condition code register to branch on, the true/false values to
1272   // select between, and a branch opcode to use.
1273   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1274   MachineFunction::iterator It = BB;
1275   ++It;
1276   
1277   //  thisMBB:
1278   //  ...
1279   //   TrueVal = ...
1280   //   cmpTY ccX, r1, r2
1281   //   bCC copy1MBB
1282   //   fallthrough --> copy0MBB
1283   MachineBasicBlock *thisMBB = BB;
1284   MachineFunction *F = BB->getParent();
1285   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1286   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1287   F->insert(It, copy0MBB);
1288   F->insert(It, sinkMBB);
1289
1290   // Transfer the remainder of BB and its successor edges to sinkMBB.
1291   sinkMBB->splice(sinkMBB->begin(), BB,
1292                   llvm::next(MachineBasicBlock::iterator(MI)),
1293                   BB->end());
1294   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1295
1296   // Next, add the true and fallthrough blocks as its successors.
1297   BB->addSuccessor(copy0MBB);
1298   BB->addSuccessor(sinkMBB);
1299   
1300   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1301     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1302
1303   //  copy0MBB:
1304   //   %FalseValue = ...
1305   //   # fallthrough to sinkMBB
1306   BB = copy0MBB;
1307   
1308   // Update machine-CFG edges
1309   BB->addSuccessor(sinkMBB);
1310   
1311   //  sinkMBB:
1312   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1313   //  ...
1314   BB = sinkMBB;
1315   BuildMI(*BB, BB->begin(), dl,
1316           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1317     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1318     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1319   
1320   MI->eraseFromParent();   // The pseudo instruction is gone now.
1321   return BB;
1322 }
1323
1324 //===----------------------------------------------------------------------===//
1325 // Target Optimization Hooks
1326 //===----------------------------------------------------------------------===//
1327
1328 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1329                                              DAGCombinerInfo &DCI) const {
1330   SelectionDAG &DAG = DCI.DAG;
1331   DebugLoc dl = N->getDebugLoc();
1332   switch (N->getOpcode()) {
1333   default: break;
1334   case XCoreISD::LADD: {
1335     SDValue N0 = N->getOperand(0);
1336     SDValue N1 = N->getOperand(1);
1337     SDValue N2 = N->getOperand(2);
1338     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1339     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1340     EVT VT = N0.getValueType();
1341
1342     // canonicalize constant to RHS
1343     if (N0C && !N1C)
1344       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1345
1346     // fold (ladd 0, 0, x) -> 0, x & 1
1347     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1348       SDValue Carry = DAG.getConstant(0, VT);
1349       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1350                                    DAG.getConstant(1, VT));
1351       SDValue Ops [] = { Carry, Result };
1352       return DAG.getMergeValues(Ops, 2, dl);
1353     }
1354
1355     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1356     // low bit set
1357     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) { 
1358       APInt KnownZero, KnownOne;
1359       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1360                                          VT.getSizeInBits() - 1);
1361       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1362       if (KnownZero == Mask) {
1363         SDValue Carry = DAG.getConstant(0, VT);
1364         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1365         SDValue Ops [] = { Carry, Result };
1366         return DAG.getMergeValues(Ops, 2, dl);
1367       }
1368     }
1369   }
1370   break;
1371   case XCoreISD::LSUB: {
1372     SDValue N0 = N->getOperand(0);
1373     SDValue N1 = N->getOperand(1);
1374     SDValue N2 = N->getOperand(2);
1375     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1376     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1377     EVT VT = N0.getValueType();
1378
1379     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1380     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {   
1381       APInt KnownZero, KnownOne;
1382       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1383                                          VT.getSizeInBits() - 1);
1384       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1385       if (KnownZero == Mask) {
1386         SDValue Borrow = N2;
1387         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1388                                      DAG.getConstant(0, VT), N2);
1389         SDValue Ops [] = { Borrow, Result };
1390         return DAG.getMergeValues(Ops, 2, dl);
1391       }
1392     }
1393
1394     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1395     // low bit set
1396     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) { 
1397       APInt KnownZero, KnownOne;
1398       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1399                                          VT.getSizeInBits() - 1);
1400       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1401       if (KnownZero == Mask) {
1402         SDValue Borrow = DAG.getConstant(0, VT);
1403         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1404         SDValue Ops [] = { Borrow, Result };
1405         return DAG.getMergeValues(Ops, 2, dl);
1406       }
1407     }
1408   }
1409   break;
1410   case XCoreISD::LMUL: {
1411     SDValue N0 = N->getOperand(0);
1412     SDValue N1 = N->getOperand(1);
1413     SDValue N2 = N->getOperand(2);
1414     SDValue N3 = N->getOperand(3);
1415     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1416     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1417     EVT VT = N0.getValueType();
1418     // Canonicalize multiplicative constant to RHS. If both multiplicative
1419     // operands are constant canonicalize smallest to RHS.
1420     if ((N0C && !N1C) ||
1421         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1422       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT), N1, N0, N2, N3);
1423
1424     // lmul(x, 0, a, b)
1425     if (N1C && N1C->isNullValue()) {
1426       // If the high result is unused fold to add(a, b)
1427       if (N->hasNUsesOfValue(0, 0)) {
1428         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1429         SDValue Ops [] = { Lo, Lo };
1430         return DAG.getMergeValues(Ops, 2, dl);
1431       }
1432       // Otherwise fold to ladd(a, b, 0)
1433       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1434     }
1435   }
1436   break;
1437   case ISD::ADD: {
1438     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1439     // lmul(x, y, a, b). The high result of lmul will be ignored.
1440     // This is only profitable if the intermediate results are unused
1441     // elsewhere.
1442     SDValue Mul0, Mul1, Addend0, Addend1;
1443     if (N->getValueType(0) == MVT::i32 &&
1444         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1445       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1446                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1447                                     Mul1, Addend0, Addend1);
1448       SDValue Result(Ignored.getNode(), 1);
1449       return Result;
1450     }
1451     APInt HighMask = APInt::getHighBitsSet(64, 32);
1452     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1453     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1454     // before type legalization as it is messy to match the operands after
1455     // that.
1456     if (N->getValueType(0) == MVT::i64 &&
1457         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1458         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1459         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1460         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1461         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1462       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1463                                   Mul0, DAG.getConstant(0, MVT::i32));
1464       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1465                                   Mul1, DAG.getConstant(0, MVT::i32));
1466       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1467                                      Addend0, DAG.getConstant(0, MVT::i32));
1468       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1469                                      Addend1, DAG.getConstant(0, MVT::i32));
1470       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1471                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1472                                Addend0L, Addend1L);
1473       SDValue Lo(Hi.getNode(), 1);
1474       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1475     }
1476   }
1477   break;
1478   case ISD::STORE: {
1479     // Replace unaligned store of unaligned load with memmove.
1480     StoreSDNode *ST  = cast<StoreSDNode>(N);
1481     if (!DCI.isBeforeLegalize() ||
1482         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1483         ST->isVolatile() || ST->isIndexed()) {
1484       break;
1485     }
1486     SDValue Chain = ST->getChain();
1487
1488     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1489     if (StoreBits % 8) {
1490       break;
1491     }
1492     unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1493         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1494     unsigned Alignment = ST->getAlignment();
1495     if (Alignment >= ABIAlignment) {
1496       break;
1497     }
1498
1499     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1500       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1501         LD->getAlignment() == Alignment &&
1502         !LD->isVolatile() && !LD->isIndexed() &&
1503         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1504         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1505                               LD->getBasePtr(),
1506                               DAG.getConstant(StoreBits/8, MVT::i32),
1507                               Alignment, false, ST->getPointerInfo(),
1508                               LD->getPointerInfo());
1509       }
1510     }
1511     break;
1512   }
1513   }
1514   return SDValue();
1515 }
1516
1517 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1518                                                          const APInt &Mask,
1519                                                          APInt &KnownZero,
1520                                                          APInt &KnownOne,
1521                                                          const SelectionDAG &DAG,
1522                                                          unsigned Depth) const {
1523   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1524   switch (Op.getOpcode()) {
1525   default: break;
1526   case XCoreISD::LADD:
1527   case XCoreISD::LSUB:
1528     if (Op.getResNo() == 0) {
1529       // Top bits of carry / borrow are clear.
1530       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1531                                         Mask.getBitWidth() - 1);
1532       KnownZero &= Mask;
1533     }
1534     break;
1535   }
1536 }
1537
1538 //===----------------------------------------------------------------------===//
1539 //  Addressing mode description hooks
1540 //===----------------------------------------------------------------------===//
1541
1542 static inline bool isImmUs(int64_t val)
1543 {
1544   return (val >= 0 && val <= 11);
1545 }
1546
1547 static inline bool isImmUs2(int64_t val)
1548 {
1549   return (val%2 == 0 && isImmUs(val/2));
1550 }
1551
1552 static inline bool isImmUs4(int64_t val)
1553 {
1554   return (val%4 == 0 && isImmUs(val/4));
1555 }
1556
1557 /// isLegalAddressingMode - Return true if the addressing mode represented
1558 /// by AM is legal for this target, for a load/store of the specified type.
1559 bool
1560 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1561                                               const Type *Ty) const {
1562   if (Ty->getTypeID() == Type::VoidTyID)
1563     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1564
1565   const TargetData *TD = TM.getTargetData();
1566   unsigned Size = TD->getTypeAllocSize(Ty);
1567   if (AM.BaseGV) {
1568     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1569                  AM.BaseOffs%4 == 0;
1570   }
1571   
1572   switch (Size) {
1573   case 1:
1574     // reg + imm
1575     if (AM.Scale == 0) {
1576       return isImmUs(AM.BaseOffs);
1577     }
1578     // reg + reg
1579     return AM.Scale == 1 && AM.BaseOffs == 0;
1580   case 2:
1581   case 3:
1582     // reg + imm
1583     if (AM.Scale == 0) {
1584       return isImmUs2(AM.BaseOffs);
1585     }
1586     // reg + reg<<1
1587     return AM.Scale == 2 && AM.BaseOffs == 0;
1588   default:
1589     // reg + imm
1590     if (AM.Scale == 0) {
1591       return isImmUs4(AM.BaseOffs);
1592     }
1593     // reg + reg<<2
1594     return AM.Scale == 4 && AM.BaseOffs == 0;
1595   }
1596   
1597   return false;
1598 }
1599
1600 //===----------------------------------------------------------------------===//
1601 //                           XCore Inline Assembly Support
1602 //===----------------------------------------------------------------------===//
1603
1604 std::vector<unsigned> XCoreTargetLowering::
1605 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1606                                   EVT VT) const 
1607 {
1608   if (Constraint.size() != 1)
1609     return std::vector<unsigned>();
1610
1611   switch (Constraint[0]) {
1612     default : break;
1613     case 'r':
1614       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
1615                                    XCore::R3, XCore::R4,  XCore::R5, 
1616                                    XCore::R6, XCore::R7,  XCore::R8, 
1617                                    XCore::R9, XCore::R10, XCore::R11, 0);
1618       break;
1619   }
1620   return std::vector<unsigned>();
1621 }