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