Allow alias to point to an arbitrary ConstantExpr.
[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 #include "XCoreISelLowering.h"
15 #include "XCore.h"
16 #include "XCoreMachineFunctionInfo.h"
17 #include "XCoreSubtarget.h"
18 #include "XCoreTargetMachine.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39
40 using namespace llvm;
41
42 #define DEBUG_TYPE "xcore-lower"
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::LDWSP             : return "XCoreISD::LDWSP";
54     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
55     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
56     case XCoreISD::LADD              : return "XCoreISD::LADD";
57     case XCoreISD::LSUB              : return "XCoreISD::LSUB";
58     case XCoreISD::LMUL              : return "XCoreISD::LMUL";
59     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
60     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
61     case XCoreISD::CRC8              : return "XCoreISD::CRC8";
62     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
63     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
64     case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
65     case XCoreISD::EH_RETURN         : return "XCoreISD::EH_RETURN";
66     case XCoreISD::MEMBARRIER        : return "XCoreISD::MEMBARRIER";
67     default                          : return nullptr;
68   }
69 }
70
71 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
72   : TargetLowering(XTM, new XCoreTargetObjectFile()),
73     TM(XTM),
74     Subtarget(*XTM.getSubtargetImpl()) {
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78
79   // Compute derived properties from the register classes
80   computeRegisterProperties();
81
82   // Division is expensive
83   setIntDivIsCheap(false);
84
85   setStackPointerRegisterToSaveRestore(XCore::SP);
86
87   setSchedulingPreference(Sched::Source);
88
89   // Use i32 for setcc operations results (slt, sgt, ...).
90   setBooleanContents(ZeroOrOneBooleanContent);
91   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92
93   // XCore does not have the NodeTypes below.
94   setOperationAction(ISD::BR_CC,     MVT::i32,   Expand);
95   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
96   setOperationAction(ISD::ADDC, MVT::i32, Expand);
97   setOperationAction(ISD::ADDE, MVT::i32, Expand);
98   setOperationAction(ISD::SUBC, MVT::i32, Expand);
99   setOperationAction(ISD::SUBE, MVT::i32, Expand);
100
101   // Stop the combiner recombining select and set_cc
102   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
103
104   // 64bit
105   setOperationAction(ISD::ADD, MVT::i64, Custom);
106   setOperationAction(ISD::SUB, MVT::i64, Custom);
107   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
108   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
109   setOperationAction(ISD::MULHS, MVT::i32, Expand);
110   setOperationAction(ISD::MULHU, MVT::i32, Expand);
111   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
112   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
113   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
114
115   // Bit Manipulation
116   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
117   setOperationAction(ISD::ROTL , MVT::i32, Expand);
118   setOperationAction(ISD::ROTR , MVT::i32, Expand);
119   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
120   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
121
122   setOperationAction(ISD::TRAP, MVT::Other, Legal);
123
124   // Jump tables.
125   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
126
127   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
128   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
129
130   // Conversion of i64 -> double produces constantpool nodes
131   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
132
133   // Loads
134   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
135   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
136   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
137
138   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
139   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
140
141   // Custom expand misaligned loads / stores.
142   setOperationAction(ISD::LOAD, MVT::i32, Custom);
143   setOperationAction(ISD::STORE, MVT::i32, Custom);
144
145   // Varargs
146   setOperationAction(ISD::VAEND, MVT::Other, Expand);
147   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
148   setOperationAction(ISD::VAARG, MVT::Other, Custom);
149   setOperationAction(ISD::VASTART, MVT::Other, Custom);
150
151   // Dynamic stack
152   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
153   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
154   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
155
156   // Exception handling
157   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
158   setExceptionPointerRegister(XCore::R0);
159   setExceptionSelectorRegister(XCore::R1);
160   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
161
162   // Atomic operations
163   // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
164   // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
165   setInsertFencesForAtomic(true);
166   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
167   setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
168   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
169
170   // TRAMPOLINE is custom lowered.
171   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
172   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
173
174   // We want to custom lower some of our intrinsics.
175   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
176
177   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
178   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
179     = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
180
181   // We have target-specific dag combine patterns for the following nodes:
182   setTargetDAGCombine(ISD::STORE);
183   setTargetDAGCombine(ISD::ADD);
184   setTargetDAGCombine(ISD::INTRINSIC_VOID);
185   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
186
187   setMinFunctionAlignment(1);
188   setPrefFunctionAlignment(2);
189 }
190
191 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
192   if (Val.getOpcode() != ISD::LOAD)
193     return false;
194
195   EVT VT1 = Val.getValueType();
196   if (!VT1.isSimple() || !VT1.isInteger() ||
197       !VT2.isSimple() || !VT2.isInteger())
198     return false;
199
200   switch (VT1.getSimpleVT().SimpleTy) {
201   default: break;
202   case MVT::i8:
203     return true;
204   }
205
206   return false;
207 }
208
209 SDValue XCoreTargetLowering::
210 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
211   switch (Op.getOpcode())
212   {
213   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
214   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
215   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
216   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
217   case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
218   case ISD::LOAD:               return LowerLOAD(Op, DAG);
219   case ISD::STORE:              return LowerSTORE(Op, DAG);
220   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
221   case ISD::VAARG:              return LowerVAARG(Op, DAG);
222   case ISD::VASTART:            return LowerVASTART(Op, DAG);
223   case ISD::SMUL_LOHI:          return LowerSMUL_LOHI(Op, DAG);
224   case ISD::UMUL_LOHI:          return LowerUMUL_LOHI(Op, DAG);
225   // FIXME: Remove these when LegalizeDAGTypes lands.
226   case ISD::ADD:
227   case ISD::SUB:                return ExpandADDSUB(Op.getNode(), DAG);
228   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
229   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
230   case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
231   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
232   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
233   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
234   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
235   case ISD::ATOMIC_LOAD:        return LowerATOMIC_LOAD(Op, DAG);
236   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG);
237   default:
238     llvm_unreachable("unimplemented operand");
239   }
240 }
241
242 /// ReplaceNodeResults - Replace the results of node with an illegal result
243 /// type with new values built out of custom code.
244 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
245                                              SmallVectorImpl<SDValue>&Results,
246                                              SelectionDAG &DAG) const {
247   switch (N->getOpcode()) {
248   default:
249     llvm_unreachable("Don't know how to custom expand this!");
250   case ISD::ADD:
251   case ISD::SUB:
252     Results.push_back(ExpandADDSUB(N, DAG));
253     return;
254   }
255 }
256
257 //===----------------------------------------------------------------------===//
258 //  Misc Lower Operation implementation
259 //===----------------------------------------------------------------------===//
260
261 SDValue XCoreTargetLowering::
262 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
263 {
264   SDLoc dl(Op);
265   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
266                              Op.getOperand(3), Op.getOperand(4));
267   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
268                      Op.getOperand(1));
269 }
270
271 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
272                                                      const GlobalValue *GV,
273                                                      SelectionDAG &DAG) const {
274   // FIXME there is no actual debug info here
275   SDLoc dl(GA);
276
277   if (GV->getType()->getElementType()->isFunctionTy())
278     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
279
280   const auto *GVar = dyn_cast<GlobalVariable>(GV);
281   if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
282       (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
283     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
284
285   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
286 }
287
288 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
289   if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
290     return true;
291
292   Type *ObjType = GV->getType()->getPointerElementType();
293   if (!ObjType->isSized())
294     return false;
295
296   unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
297   return ObjSize < CodeModelLargeSize && ObjSize != 0;
298 }
299
300 SDValue XCoreTargetLowering::
301 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
302 {
303   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
304   const GlobalValue *GV = GN->getGlobal();
305   SDLoc DL(GN);
306   int64_t Offset = GN->getOffset();
307   if (IsSmallObject(GV, *this)) {
308     // We can only fold positive offsets that are a multiple of the word size.
309     int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
310     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
311     GA = getGlobalAddressWrapper(GA, GV, DAG);
312     // Handle the rest of the offset.
313     if (Offset != FoldedOffset) {
314       SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
315       GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
316     }
317     return GA;
318   } else {
319     // Ideally we would not fold in offset with an index <= 11.
320     Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
321     Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
322     Ty = Type::getInt32Ty(*DAG.getContext());
323     Constant *Idx = ConstantInt::get(Ty, Offset);
324     Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
325     SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
326     return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
327                        MachinePointerInfo(), false, false, false, 0);
328   }
329 }
330
331 SDValue XCoreTargetLowering::
332 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
333 {
334   SDLoc DL(Op);
335
336   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
337   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
338
339   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
340 }
341
342 SDValue XCoreTargetLowering::
343 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
344 {
345   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
346   // FIXME there isn't really debug info here
347   SDLoc dl(CP);
348   EVT PtrVT = Op.getValueType();
349   SDValue Res;
350   if (CP->isMachineConstantPoolEntry()) {
351     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
352                                     CP->getAlignment(), CP->getOffset());
353   } else {
354     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
355                                     CP->getAlignment(), CP->getOffset());
356   }
357   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
358 }
359
360 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
361   return MachineJumpTableInfo::EK_Inline;
362 }
363
364 SDValue XCoreTargetLowering::
365 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
366 {
367   SDValue Chain = Op.getOperand(0);
368   SDValue Table = Op.getOperand(1);
369   SDValue Index = Op.getOperand(2);
370   SDLoc dl(Op);
371   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
372   unsigned JTI = JT->getIndex();
373   MachineFunction &MF = DAG.getMachineFunction();
374   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
375   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
376
377   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
378   if (NumEntries <= 32) {
379     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
380   }
381   assert((NumEntries >> 31) == 0);
382   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
383                                     DAG.getConstant(1, MVT::i32));
384   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
385                      ScaledIndex);
386 }
387
388 SDValue XCoreTargetLowering::
389 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
390                                        int64_t Offset, SelectionDAG &DAG) const
391 {
392   if ((Offset & 0x3) == 0) {
393     return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
394                        false, false, false, 0);
395   }
396   // Lower to pair of consecutive word aligned loads plus some bit shifting.
397   int32_t HighOffset = RoundUpToAlignment(Offset, 4);
398   int32_t LowOffset = HighOffset - 4;
399   SDValue LowAddr, HighAddr;
400   if (GlobalAddressSDNode *GASD =
401         dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
402     LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
403                                    LowOffset);
404     HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
405                                     HighOffset);
406   } else {
407     LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
408                           DAG.getConstant(LowOffset, MVT::i32));
409     HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
410                            DAG.getConstant(HighOffset, MVT::i32));
411   }
412   SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
413   SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
414
415   SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
416                             LowAddr, MachinePointerInfo(),
417                             false, false, false, 0);
418   SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
419                              HighAddr, MachinePointerInfo(),
420                              false, false, false, 0);
421   SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
422   SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
423   SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
424   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
425                       High.getValue(1));
426   SDValue Ops[] = { Result, Chain };
427   return DAG.getMergeValues(Ops, DL);
428 }
429
430 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
431 {
432   APInt KnownZero, KnownOne;
433   DAG.computeKnownBits(Value, KnownZero, KnownOne);
434   return KnownZero.countTrailingOnes() >= 2;
435 }
436
437 SDValue XCoreTargetLowering::
438 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
440   LoadSDNode *LD = cast<LoadSDNode>(Op);
441   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
442          "Unexpected extension type");
443   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
444   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
445     return SDValue();
446
447   unsigned ABIAlignment = getDataLayout()->
448     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
449   // Leave aligned load alone.
450   if (LD->getAlignment() >= ABIAlignment)
451     return SDValue();
452
453   SDValue Chain = LD->getChain();
454   SDValue BasePtr = LD->getBasePtr();
455   SDLoc DL(Op);
456
457   if (!LD->isVolatile()) {
458     const GlobalValue *GV;
459     int64_t Offset = 0;
460     if (DAG.isBaseWithConstantOffset(BasePtr) &&
461         isWordAligned(BasePtr->getOperand(0), DAG)) {
462       SDValue NewBasePtr = BasePtr->getOperand(0);
463       Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
464       return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
465                                                     Offset, DAG);
466     }
467     if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
468         MinAlign(GV->getAlignment(), 4) == 4) {
469       SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
470                                                 BasePtr->getValueType(0));
471       return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
472                                                     Offset, DAG);
473     }
474   }
475
476   if (LD->getAlignment() == 2) {
477     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
478                                  BasePtr, LD->getPointerInfo(), MVT::i16,
479                                  LD->isVolatile(), LD->isNonTemporal(), 2);
480     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
481                                    DAG.getConstant(2, MVT::i32));
482     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
483                                   HighAddr,
484                                   LD->getPointerInfo().getWithOffset(2),
485                                   MVT::i16, LD->isVolatile(),
486                                   LD->isNonTemporal(), 2);
487     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
488                                       DAG.getConstant(16, MVT::i32));
489     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
490     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
491                              High.getValue(1));
492     SDValue Ops[] = { Result, Chain };
493     return DAG.getMergeValues(Ops, DL);
494   }
495
496   // Lower to a call to __misaligned_load(BasePtr).
497   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
498   TargetLowering::ArgListTy Args;
499   TargetLowering::ArgListEntry Entry;
500
501   Entry.Ty = IntPtrTy;
502   Entry.Node = BasePtr;
503   Args.push_back(Entry);
504
505   TargetLowering::CallLoweringInfo CLI(DAG);
506   CLI.setDebugLoc(DL).setChain(Chain)
507     .setCallee(CallingConv::C, IntPtrTy,
508                DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
509                &Args, 0);
510
511   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
512   SDValue Ops[] = { CallResult.first, CallResult.second };
513   return DAG.getMergeValues(Ops, DL);
514 }
515
516 SDValue XCoreTargetLowering::
517 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
518 {
519   StoreSDNode *ST = cast<StoreSDNode>(Op);
520   assert(!ST->isTruncatingStore() && "Unexpected store type");
521   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
522   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
523     return SDValue();
524   }
525   unsigned ABIAlignment = getDataLayout()->
526     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
527   // Leave aligned store alone.
528   if (ST->getAlignment() >= ABIAlignment) {
529     return SDValue();
530   }
531   SDValue Chain = ST->getChain();
532   SDValue BasePtr = ST->getBasePtr();
533   SDValue Value = ST->getValue();
534   SDLoc dl(Op);
535
536   if (ST->getAlignment() == 2) {
537     SDValue Low = Value;
538     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
539                                       DAG.getConstant(16, MVT::i32));
540     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
541                                          ST->getPointerInfo(), MVT::i16,
542                                          ST->isVolatile(), ST->isNonTemporal(),
543                                          2);
544     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
545                                    DAG.getConstant(2, MVT::i32));
546     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
547                                           ST->getPointerInfo().getWithOffset(2),
548                                           MVT::i16, ST->isVolatile(),
549                                           ST->isNonTemporal(), 2);
550     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
551   }
552
553   // Lower to a call to __misaligned_store(BasePtr, Value).
554   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
555   TargetLowering::ArgListTy Args;
556   TargetLowering::ArgListEntry Entry;
557
558   Entry.Ty = IntPtrTy;
559   Entry.Node = BasePtr;
560   Args.push_back(Entry);
561
562   Entry.Node = Value;
563   Args.push_back(Entry);
564
565   TargetLowering::CallLoweringInfo CLI(DAG);
566   CLI.setDebugLoc(dl).setChain(Chain)
567     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
568                DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
569                &Args, 0);
570
571   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
572   return CallResult.second;
573 }
574
575 SDValue XCoreTargetLowering::
576 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
577 {
578   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
579          "Unexpected operand to lower!");
580   SDLoc dl(Op);
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::MACCS, dl,
585                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
586                            LHS, RHS);
587   SDValue Lo(Hi.getNode(), 1);
588   SDValue Ops[] = { Lo, Hi };
589   return DAG.getMergeValues(Ops, dl);
590 }
591
592 SDValue XCoreTargetLowering::
593 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
594 {
595   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
596          "Unexpected operand to lower!");
597   SDLoc dl(Op);
598   SDValue LHS = Op.getOperand(0);
599   SDValue RHS = Op.getOperand(1);
600   SDValue Zero = DAG.getConstant(0, MVT::i32);
601   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
602                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
603                            Zero, Zero);
604   SDValue Lo(Hi.getNode(), 1);
605   SDValue Ops[] = { Lo, Hi };
606   return DAG.getMergeValues(Ops, dl);
607 }
608
609 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
610 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
611 /// each intermediate result in the calculation must also have a single use.
612 /// If the Op is in the correct form the constituent parts are written to Mul0,
613 /// Mul1, Addend0 and Addend1.
614 static bool
615 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
616             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
617 {
618   if (Op.getOpcode() != ISD::ADD)
619     return false;
620   SDValue N0 = Op.getOperand(0);
621   SDValue N1 = Op.getOperand(1);
622   SDValue AddOp;
623   SDValue OtherOp;
624   if (N0.getOpcode() == ISD::ADD) {
625     AddOp = N0;
626     OtherOp = N1;
627   } else if (N1.getOpcode() == ISD::ADD) {
628     AddOp = N1;
629     OtherOp = N0;
630   } else {
631     return false;
632   }
633   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
634     return false;
635   if (OtherOp.getOpcode() == ISD::MUL) {
636     // add(add(a,b),mul(x,y))
637     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
638       return false;
639     Mul0 = OtherOp.getOperand(0);
640     Mul1 = OtherOp.getOperand(1);
641     Addend0 = AddOp.getOperand(0);
642     Addend1 = AddOp.getOperand(1);
643     return true;
644   }
645   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
646     // add(add(mul(x,y),a),b)
647     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
648       return false;
649     Mul0 = AddOp.getOperand(0).getOperand(0);
650     Mul1 = AddOp.getOperand(0).getOperand(1);
651     Addend0 = AddOp.getOperand(1);
652     Addend1 = OtherOp;
653     return true;
654   }
655   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
656     // add(add(a,mul(x,y)),b)
657     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
658       return false;
659     Mul0 = AddOp.getOperand(1).getOperand(0);
660     Mul1 = AddOp.getOperand(1).getOperand(1);
661     Addend0 = AddOp.getOperand(0);
662     Addend1 = OtherOp;
663     return true;
664   }
665   return false;
666 }
667
668 SDValue XCoreTargetLowering::
669 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
670 {
671   SDValue Mul;
672   SDValue Other;
673   if (N->getOperand(0).getOpcode() == ISD::MUL) {
674     Mul = N->getOperand(0);
675     Other = N->getOperand(1);
676   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
677     Mul = N->getOperand(1);
678     Other = N->getOperand(0);
679   } else {
680     return SDValue();
681   }
682   SDLoc dl(N);
683   SDValue LL, RL, AddendL, AddendH;
684   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685                    Mul.getOperand(0),  DAG.getConstant(0, MVT::i32));
686   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687                    Mul.getOperand(1),  DAG.getConstant(0, MVT::i32));
688   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689                         Other,  DAG.getConstant(0, MVT::i32));
690   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691                         Other,  DAG.getConstant(1, MVT::i32));
692   APInt HighMask = APInt::getHighBitsSet(64, 32);
693   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
694   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
695   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
696       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
697     // The inputs are both zero-extended.
698     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
699                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
700                              AddendL, LL, RL);
701     SDValue Lo(Hi.getNode(), 1);
702     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
703   }
704   if (LHSSB > 32 && RHSSB > 32) {
705     // The inputs are both sign-extended.
706     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
707                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
708                              AddendL, LL, RL);
709     SDValue Lo(Hi.getNode(), 1);
710     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
711   }
712   SDValue LH, RH;
713   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
714                    Mul.getOperand(0),  DAG.getConstant(1, MVT::i32));
715   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
716                    Mul.getOperand(1),  DAG.getConstant(1, MVT::i32));
717   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
718                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
719                            AddendL, LL, RL);
720   SDValue Lo(Hi.getNode(), 1);
721   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
722   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
723   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
724   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
725   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
726 }
727
728 SDValue XCoreTargetLowering::
729 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
730 {
731   assert(N->getValueType(0) == MVT::i64 &&
732          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
733         "Unknown operand to lower!");
734
735   if (N->getOpcode() == ISD::ADD) {
736     SDValue Result = TryExpandADDWithMul(N, DAG);
737     if (Result.getNode())
738       return Result;
739   }
740
741   SDLoc dl(N);
742
743   // Extract components
744   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
746   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
748   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
749                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
750   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
752
753   // Expand
754   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
755                                                    XCoreISD::LSUB;
756   SDValue Zero = DAG.getConstant(0, MVT::i32);
757   SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
758                            LHSL, RHSL, Zero);
759   SDValue Carry(Lo.getNode(), 1);
760
761   SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
762                            LHSH, RHSH, Carry);
763   SDValue Ignored(Hi.getNode(), 1);
764   // Merge the pieces
765   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
766 }
767
768 SDValue XCoreTargetLowering::
769 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
770 {
771   // Whist llvm does not support aggregate varargs we can ignore
772   // the possibility of the ValueType being an implicit byVal vararg.
773   SDNode *Node = Op.getNode();
774   EVT VT = Node->getValueType(0); // not an aggregate
775   SDValue InChain = Node->getOperand(0);
776   SDValue VAListPtr = Node->getOperand(1);
777   EVT PtrVT = VAListPtr.getValueType();
778   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
779   SDLoc dl(Node);
780   SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
781                                VAListPtr, MachinePointerInfo(SV),
782                                false, false, false, 0);
783   // Increment the pointer, VAList, to the next vararg
784   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
785                                 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
786   // Store the incremented VAList to the legalized pointer
787   InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
788                          MachinePointerInfo(SV), false, false, 0);
789   // Load the actual argument out of the pointer VAList
790   return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
791                      false, false, false, 0);
792 }
793
794 SDValue XCoreTargetLowering::
795 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
796 {
797   SDLoc dl(Op);
798   // vastart stores the address of the VarArgsFrameIndex slot into the
799   // memory location argument
800   MachineFunction &MF = DAG.getMachineFunction();
801   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
802   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
803   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
804                       MachinePointerInfo(), false, false, 0);
805 }
806
807 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
808                                             SelectionDAG &DAG) const {
809   // This nodes represent llvm.frameaddress on the DAG.
810   // It takes one operand, the index of the frame address to return.
811   // An index of zero corresponds to the current function's frame address.
812   // An index of one to the parent's frame address, and so on.
813   // Depths > 0 not supported yet!
814   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
815     return SDValue();
816
817   MachineFunction &MF = DAG.getMachineFunction();
818   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
819   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
820                             RegInfo->getFrameRegister(MF), MVT::i32);
821 }
822
823 SDValue XCoreTargetLowering::
824 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
825   // This nodes represent llvm.returnaddress on the DAG.
826   // It takes one operand, the index of the return address to return.
827   // An index of zero corresponds to the current function's return address.
828   // An index of one to the parent's return address, and so on.
829   // Depths > 0 not supported yet!
830   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
831     return SDValue();
832
833   MachineFunction &MF = DAG.getMachineFunction();
834   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
835   int FI = XFI->createLRSpillSlot(MF);
836   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
837   return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
838                      MachinePointerInfo::getFixedStack(FI), false, false,
839                      false, 0);
840 }
841
842 SDValue XCoreTargetLowering::
843 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
844   // This node represents offset from frame pointer to first on-stack argument.
845   // This is needed for correct stack adjustment during unwind.
846   // However, we don't know the offset until after the frame has be finalised.
847   // This is done during the XCoreFTAOElim pass.
848   return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
849 }
850
851 SDValue XCoreTargetLowering::
852 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
853   // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
854   // This node represents 'eh_return' gcc dwarf builtin, which is used to
855   // return from exception. The general meaning is: adjust stack by OFFSET and
856   // pass execution to HANDLER.
857   MachineFunction &MF = DAG.getMachineFunction();
858   SDValue Chain     = Op.getOperand(0);
859   SDValue Offset    = Op.getOperand(1);
860   SDValue Handler   = Op.getOperand(2);
861   SDLoc dl(Op);
862
863   // Absolute SP = (FP + FrameToArgs) + Offset
864   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
865   SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
866                             RegInfo->getFrameRegister(MF), MVT::i32);
867   SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
868                                     MVT::i32);
869   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
870   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
871
872   // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
873   // which leaves 2 caller saved registers, R2 & R3 for us to use.
874   unsigned StackReg = XCore::R2;
875   unsigned HandlerReg = XCore::R3;
876
877   SDValue OutChains[] = {
878     DAG.getCopyToReg(Chain, dl, StackReg, Stack),
879     DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
880   };
881
882   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
883
884   return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
885                      DAG.getRegister(StackReg, MVT::i32),
886                      DAG.getRegister(HandlerReg, MVT::i32));
887
888 }
889
890 SDValue XCoreTargetLowering::
891 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
892   return Op.getOperand(0);
893 }
894
895 SDValue XCoreTargetLowering::
896 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
897   SDValue Chain = Op.getOperand(0);
898   SDValue Trmp = Op.getOperand(1); // trampoline
899   SDValue FPtr = Op.getOperand(2); // nested function
900   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
901
902   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
903
904   // .align 4
905   // LDAPF_u10 r11, nest
906   // LDW_2rus r11, r11[0]
907   // STWSP_ru6 r11, sp[0]
908   // LDAPF_u10 r11, fptr
909   // LDW_2rus r11, r11[0]
910   // BAU_1r r11
911   // nest:
912   // .word nest
913   // fptr:
914   // .word fptr
915   SDValue OutChains[5];
916
917   SDValue Addr = Trmp;
918
919   SDLoc dl(Op);
920   OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
921                               Addr, MachinePointerInfo(TrmpAddr), false, false,
922                               0);
923
924   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
925                      DAG.getConstant(4, MVT::i32));
926   OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
927                               Addr, MachinePointerInfo(TrmpAddr, 4), false,
928                               false, 0);
929
930   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
931                      DAG.getConstant(8, MVT::i32));
932   OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
933                               Addr, MachinePointerInfo(TrmpAddr, 8), false,
934                               false, 0);
935
936   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
937                      DAG.getConstant(12, MVT::i32));
938   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
939                               MachinePointerInfo(TrmpAddr, 12), false, false,
940                               0);
941
942   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
943                      DAG.getConstant(16, MVT::i32));
944   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
945                               MachinePointerInfo(TrmpAddr, 16), false, false,
946                               0);
947
948   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
949 }
950
951 SDValue XCoreTargetLowering::
952 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
953   SDLoc DL(Op);
954   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
955   switch (IntNo) {
956     case Intrinsic::xcore_crc8:
957       EVT VT = Op.getValueType();
958       SDValue Data =
959         DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
960                     Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
961       SDValue Crc(Data.getNode(), 1);
962       SDValue Results[] = { Crc, Data };
963       return DAG.getMergeValues(Results, DL);
964   }
965   return SDValue();
966 }
967
968 SDValue XCoreTargetLowering::
969 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
970   SDLoc DL(Op);
971   return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
972 }
973
974 SDValue XCoreTargetLowering::
975 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
976   AtomicSDNode *N = cast<AtomicSDNode>(Op);
977   assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
978   assert(N->getOrdering() <= Monotonic &&
979          "setInsertFencesForAtomic(true) and yet greater than Monotonic");
980   if (N->getMemoryVT() == MVT::i32) {
981     if (N->getAlignment() < 4)
982       report_fatal_error("atomic load must be aligned");
983     return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
984                        N->getBasePtr(), N->getPointerInfo(),
985                        N->isVolatile(), N->isNonTemporal(),
986                        N->isInvariant(), N->getAlignment(),
987                        N->getTBAAInfo(), N->getRanges());
988   }
989   if (N->getMemoryVT() == MVT::i16) {
990     if (N->getAlignment() < 2)
991       report_fatal_error("atomic load must be aligned");
992     return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
993                           N->getBasePtr(), N->getPointerInfo(), MVT::i16,
994                           N->isVolatile(), N->isNonTemporal(),
995                           N->getAlignment(), N->getTBAAInfo());
996   }
997   if (N->getMemoryVT() == MVT::i8)
998     return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
999                           N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1000                           N->isVolatile(), N->isNonTemporal(),
1001                           N->getAlignment(), N->getTBAAInfo());
1002   return SDValue();
1003 }
1004
1005 SDValue XCoreTargetLowering::
1006 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1007   AtomicSDNode *N = cast<AtomicSDNode>(Op);
1008   assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1009   assert(N->getOrdering() <= Monotonic &&
1010          "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1011   if (N->getMemoryVT() == MVT::i32) {
1012     if (N->getAlignment() < 4)
1013       report_fatal_error("atomic store must be aligned");
1014     return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1015                         N->getBasePtr(), N->getPointerInfo(),
1016                         N->isVolatile(), N->isNonTemporal(),
1017                         N->getAlignment(), N->getTBAAInfo());
1018   }
1019   if (N->getMemoryVT() == MVT::i16) {
1020     if (N->getAlignment() < 2)
1021       report_fatal_error("atomic store must be aligned");
1022     return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1023                              N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1024                              N->isVolatile(), N->isNonTemporal(),
1025                              N->getAlignment(), N->getTBAAInfo());
1026   }
1027   if (N->getMemoryVT() == MVT::i8)
1028     return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1029                              N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1030                              N->isVolatile(), N->isNonTemporal(),
1031                              N->getAlignment(), N->getTBAAInfo());
1032   return SDValue();
1033 }
1034
1035 //===----------------------------------------------------------------------===//
1036 //                      Calling Convention Implementation
1037 //===----------------------------------------------------------------------===//
1038
1039 #include "XCoreGenCallingConv.inc"
1040
1041 //===----------------------------------------------------------------------===//
1042 //                  Call Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1044
1045 /// XCore call implementation
1046 SDValue
1047 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1048                                SmallVectorImpl<SDValue> &InVals) const {
1049   SelectionDAG &DAG                     = CLI.DAG;
1050   SDLoc &dl                             = CLI.DL;
1051   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1052   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1053   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1054   SDValue Chain                         = CLI.Chain;
1055   SDValue Callee                        = CLI.Callee;
1056   bool &isTailCall                      = CLI.IsTailCall;
1057   CallingConv::ID CallConv              = CLI.CallConv;
1058   bool isVarArg                         = CLI.IsVarArg;
1059
1060   // XCore target does not yet support tail call optimization.
1061   isTailCall = false;
1062
1063   // For now, only CallingConv::C implemented
1064   switch (CallConv)
1065   {
1066     default:
1067       llvm_unreachable("Unsupported calling convention");
1068     case CallingConv::Fast:
1069     case CallingConv::C:
1070       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1071                             Outs, OutVals, Ins, dl, DAG, InVals);
1072   }
1073 }
1074
1075 /// LowerCallResult - Lower the result values of a call into the
1076 /// appropriate copies out of appropriate physical registers / memory locations.
1077 static SDValue
1078 LowerCallResult(SDValue Chain, SDValue InFlag,
1079                 const SmallVectorImpl<CCValAssign> &RVLocs,
1080                 SDLoc dl, SelectionDAG &DAG,
1081                 SmallVectorImpl<SDValue> &InVals) {
1082   SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1083   // Copy results out of physical registers.
1084   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1085     const CCValAssign &VA = RVLocs[i];
1086     if (VA.isRegLoc()) {
1087       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1088                                  InFlag).getValue(1);
1089       InFlag = Chain.getValue(2);
1090       InVals.push_back(Chain.getValue(0));
1091     } else {
1092       assert(VA.isMemLoc());
1093       ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1094                                              InVals.size()));
1095       // Reserve space for this result.
1096       InVals.push_back(SDValue());
1097     }
1098   }
1099
1100   // Copy results out of memory.
1101   SmallVector<SDValue, 4> MemOpChains;
1102   for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1103     int offset = ResultMemLocs[i].first;
1104     unsigned index = ResultMemLocs[i].second;
1105     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1106     SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1107     SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1108     InVals[index] = load;
1109     MemOpChains.push_back(load.getValue(1));
1110   }
1111
1112   // Transform all loads nodes into one single node because
1113   // all load nodes are independent of each other.
1114   if (!MemOpChains.empty())
1115     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1116
1117   return Chain;
1118 }
1119
1120 /// LowerCCCCallTo - functions arguments are copied from virtual
1121 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1122 /// CALLSEQ_END are emitted.
1123 /// TODO: isTailCall, sret.
1124 SDValue
1125 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1126                                     CallingConv::ID CallConv, bool isVarArg,
1127                                     bool isTailCall,
1128                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1129                                     const SmallVectorImpl<SDValue> &OutVals,
1130                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1131                                     SDLoc dl, SelectionDAG &DAG,
1132                                     SmallVectorImpl<SDValue> &InVals) const {
1133
1134   // Analyze operands of the call, assigning locations to each operand.
1135   SmallVector<CCValAssign, 16> ArgLocs;
1136   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1137                  getTargetMachine(), ArgLocs, *DAG.getContext());
1138
1139   // The ABI dictates there should be one stack slot available to the callee
1140   // on function entry (for saving lr).
1141   CCInfo.AllocateStack(4, 4);
1142
1143   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1144
1145   SmallVector<CCValAssign, 16> RVLocs;
1146   // Analyze return values to determine the number of bytes of stack required.
1147   CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1148                     getTargetMachine(), RVLocs, *DAG.getContext());
1149   RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1150   RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1151
1152   // Get a count of how many bytes are to be pushed on the stack.
1153   unsigned NumBytes = RetCCInfo.getNextStackOffset();
1154
1155   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1156                                  getPointerTy(), true), dl);
1157
1158   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1159   SmallVector<SDValue, 12> MemOpChains;
1160
1161   // Walk the register/memloc assignments, inserting copies/loads.
1162   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1163     CCValAssign &VA = ArgLocs[i];
1164     SDValue Arg = OutVals[i];
1165
1166     // Promote the value if needed.
1167     switch (VA.getLocInfo()) {
1168       default: llvm_unreachable("Unknown loc info!");
1169       case CCValAssign::Full: break;
1170       case CCValAssign::SExt:
1171         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1172         break;
1173       case CCValAssign::ZExt:
1174         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1175         break;
1176       case CCValAssign::AExt:
1177         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1178         break;
1179     }
1180
1181     // Arguments that can be passed on register must be kept at
1182     // RegsToPass vector
1183     if (VA.isRegLoc()) {
1184       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1185     } else {
1186       assert(VA.isMemLoc());
1187
1188       int Offset = VA.getLocMemOffset();
1189
1190       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1191                                         Chain, Arg,
1192                                         DAG.getConstant(Offset/4, MVT::i32)));
1193     }
1194   }
1195
1196   // Transform all store nodes into one single node because
1197   // all store nodes are independent of each other.
1198   if (!MemOpChains.empty())
1199     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1200
1201   // Build a sequence of copy-to-reg nodes chained together with token
1202   // chain and flag operands which copy the outgoing args into registers.
1203   // The InFlag in necessary since all emitted instructions must be
1204   // stuck together.
1205   SDValue InFlag;
1206   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1207     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1208                              RegsToPass[i].second, InFlag);
1209     InFlag = Chain.getValue(1);
1210   }
1211
1212   // If the callee is a GlobalAddress node (quite common, every direct call is)
1213   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1214   // Likewise ExternalSymbol -> TargetExternalSymbol.
1215   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1216     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1217   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1218     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1219
1220   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1221   //             = Chain, Callee, Reg#1, Reg#2, ...
1222   //
1223   // Returns a chain & a flag for retval copy to use.
1224   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1225   SmallVector<SDValue, 8> Ops;
1226   Ops.push_back(Chain);
1227   Ops.push_back(Callee);
1228
1229   // Add argument registers to the end of the list so that they are
1230   // known live into the call.
1231   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1232     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1233                                   RegsToPass[i].second.getValueType()));
1234
1235   if (InFlag.getNode())
1236     Ops.push_back(InFlag);
1237
1238   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1239   InFlag = Chain.getValue(1);
1240
1241   // Create the CALLSEQ_END node.
1242   Chain = DAG.getCALLSEQ_END(Chain,
1243                              DAG.getConstant(NumBytes, getPointerTy(), true),
1244                              DAG.getConstant(0, getPointerTy(), true),
1245                              InFlag, dl);
1246   InFlag = Chain.getValue(1);
1247
1248   // Handle result values, copying them out of physregs into vregs that we
1249   // return.
1250   return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1251 }
1252
1253 //===----------------------------------------------------------------------===//
1254 //             Formal Arguments Calling Convention Implementation
1255 //===----------------------------------------------------------------------===//
1256
1257 namespace {
1258   struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1259 }
1260
1261 /// XCore formal arguments implementation
1262 SDValue
1263 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1264                                           CallingConv::ID CallConv,
1265                                           bool isVarArg,
1266                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1267                                           SDLoc dl,
1268                                           SelectionDAG &DAG,
1269                                           SmallVectorImpl<SDValue> &InVals)
1270                                             const {
1271   switch (CallConv)
1272   {
1273     default:
1274       llvm_unreachable("Unsupported calling convention");
1275     case CallingConv::C:
1276     case CallingConv::Fast:
1277       return LowerCCCArguments(Chain, CallConv, isVarArg,
1278                                Ins, dl, DAG, InVals);
1279   }
1280 }
1281
1282 /// LowerCCCArguments - transform physical registers into
1283 /// virtual registers and generate load operations for
1284 /// arguments places on the stack.
1285 /// TODO: sret
1286 SDValue
1287 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1288                                        CallingConv::ID CallConv,
1289                                        bool isVarArg,
1290                                        const SmallVectorImpl<ISD::InputArg>
1291                                          &Ins,
1292                                        SDLoc dl,
1293                                        SelectionDAG &DAG,
1294                                        SmallVectorImpl<SDValue> &InVals) const {
1295   MachineFunction &MF = DAG.getMachineFunction();
1296   MachineFrameInfo *MFI = MF.getFrameInfo();
1297   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1298   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1299
1300   // Assign locations to all of the incoming arguments.
1301   SmallVector<CCValAssign, 16> ArgLocs;
1302   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1303                  getTargetMachine(), ArgLocs, *DAG.getContext());
1304
1305   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1306
1307   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1308
1309   unsigned LRSaveSize = StackSlotSize;
1310
1311   if (!isVarArg)
1312     XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1313
1314   // All getCopyFromReg ops must precede any getMemcpys to prevent the
1315   // scheduler clobbering a register before it has been copied.
1316   // The stages are:
1317   // 1. CopyFromReg (and load) arg & vararg registers.
1318   // 2. Chain CopyFromReg nodes into a TokenFactor.
1319   // 3. Memcpy 'byVal' args & push final InVals.
1320   // 4. Chain mem ops nodes into a TokenFactor.
1321   SmallVector<SDValue, 4> CFRegNode;
1322   SmallVector<ArgDataPair, 4> ArgData;
1323   SmallVector<SDValue, 4> MemOps;
1324
1325   // 1a. CopyFromReg (and load) arg registers.
1326   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1327
1328     CCValAssign &VA = ArgLocs[i];
1329     SDValue ArgIn;
1330
1331     if (VA.isRegLoc()) {
1332       // Arguments passed in registers
1333       EVT RegVT = VA.getLocVT();
1334       switch (RegVT.getSimpleVT().SimpleTy) {
1335       default:
1336         {
1337 #ifndef NDEBUG
1338           errs() << "LowerFormalArguments Unhandled argument type: "
1339                  << RegVT.getSimpleVT().SimpleTy << "\n";
1340 #endif
1341           llvm_unreachable(nullptr);
1342         }
1343       case MVT::i32:
1344         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1345         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1346         ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1347         CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1348       }
1349     } else {
1350       // sanity check
1351       assert(VA.isMemLoc());
1352       // Load the argument to a virtual register
1353       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1354       if (ObjSize > StackSlotSize) {
1355         errs() << "LowerFormalArguments Unhandled argument type: "
1356                << EVT(VA.getLocVT()).getEVTString()
1357                << "\n";
1358       }
1359       // Create the frame index object for this incoming parameter...
1360       int FI = MFI->CreateFixedObject(ObjSize,
1361                                       LRSaveSize + VA.getLocMemOffset(),
1362                                       true);
1363
1364       // Create the SelectionDAG nodes corresponding to a load
1365       //from this parameter
1366       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1367       ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1368                           MachinePointerInfo::getFixedStack(FI),
1369                           false, false, false, 0);
1370     }
1371     const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1372     ArgData.push_back(ADP);
1373   }
1374
1375   // 1b. CopyFromReg vararg registers.
1376   if (isVarArg) {
1377     // Argument registers
1378     static const MCPhysReg ArgRegs[] = {
1379       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1380     };
1381     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1382     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1383                                                      array_lengthof(ArgRegs));
1384     if (FirstVAReg < array_lengthof(ArgRegs)) {
1385       int offset = 0;
1386       // Save remaining registers, storing higher register numbers at a higher
1387       // address
1388       for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1389         // Create a stack slot
1390         int FI = MFI->CreateFixedObject(4, offset, true);
1391         if (i == (int)FirstVAReg) {
1392           XFI->setVarArgsFrameIndex(FI);
1393         }
1394         offset -= StackSlotSize;
1395         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1396         // Move argument from phys reg -> virt reg
1397         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1398         RegInfo.addLiveIn(ArgRegs[i], VReg);
1399         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1400         CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1401         // Move argument from virt reg -> stack
1402         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1403                                      MachinePointerInfo(), false, false, 0);
1404         MemOps.push_back(Store);
1405       }
1406     } else {
1407       // This will point to the next argument passed via stack.
1408       XFI->setVarArgsFrameIndex(
1409         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1410                                true));
1411     }
1412   }
1413
1414   // 2. chain CopyFromReg nodes into a TokenFactor.
1415   if (!CFRegNode.empty())
1416     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1417
1418   // 3. Memcpy 'byVal' args & push final InVals.
1419   // Aggregates passed "byVal" need to be copied by the callee.
1420   // The callee will use a pointer to this copy, rather than the original
1421   // pointer.
1422   for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1423                                                     ArgDE = ArgData.end();
1424        ArgDI != ArgDE; ++ArgDI) {
1425     if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1426       unsigned Size = ArgDI->Flags.getByValSize();
1427       unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1428       // Create a new object on the stack and copy the pointee into it.
1429       int FI = MFI->CreateStackObject(Size, Align, false);
1430       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1431       InVals.push_back(FIN);
1432       MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1433                                      DAG.getConstant(Size, MVT::i32),
1434                                      Align, false, false,
1435                                      MachinePointerInfo(),
1436                                      MachinePointerInfo()));
1437     } else {
1438       InVals.push_back(ArgDI->SDV);
1439     }
1440   }
1441
1442   // 4, chain mem ops nodes into a TokenFactor.
1443   if (!MemOps.empty()) {
1444     MemOps.push_back(Chain);
1445     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1446   }
1447
1448   return Chain;
1449 }
1450
1451 //===----------------------------------------------------------------------===//
1452 //               Return Value Calling Convention Implementation
1453 //===----------------------------------------------------------------------===//
1454
1455 bool XCoreTargetLowering::
1456 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1457                bool isVarArg,
1458                const SmallVectorImpl<ISD::OutputArg> &Outs,
1459                LLVMContext &Context) const {
1460   SmallVector<CCValAssign, 16> RVLocs;
1461   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1462   if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1463     return false;
1464   if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1465     return false;
1466   return true;
1467 }
1468
1469 SDValue
1470 XCoreTargetLowering::LowerReturn(SDValue Chain,
1471                                  CallingConv::ID CallConv, bool isVarArg,
1472                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1473                                  const SmallVectorImpl<SDValue> &OutVals,
1474                                  SDLoc dl, SelectionDAG &DAG) const {
1475
1476   XCoreFunctionInfo *XFI =
1477     DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1478   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1479
1480   // CCValAssign - represent the assignment of
1481   // the return value to a location
1482   SmallVector<CCValAssign, 16> RVLocs;
1483
1484   // CCState - Info about the registers and stack slot.
1485   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1486                  getTargetMachine(), RVLocs, *DAG.getContext());
1487
1488   // Analyze return values.
1489   if (!isVarArg)
1490     CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1491
1492   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1493
1494   SDValue Flag;
1495   SmallVector<SDValue, 4> RetOps(1, Chain);
1496
1497   // Return on XCore is always a "retsp 0"
1498   RetOps.push_back(DAG.getConstant(0, MVT::i32));
1499
1500   SmallVector<SDValue, 4> MemOpChains;
1501   // Handle return values that must be copied to memory.
1502   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1503     CCValAssign &VA = RVLocs[i];
1504     if (VA.isRegLoc())
1505       continue;
1506     assert(VA.isMemLoc());
1507     if (isVarArg) {
1508       report_fatal_error("Can't return value from vararg function in memory");
1509     }
1510
1511     int Offset = VA.getLocMemOffset();
1512     unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1513     // Create the frame index object for the memory location.
1514     int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1515
1516     // Create a SelectionDAG node corresponding to a store
1517     // to this memory location.
1518     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1519     MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1520                           MachinePointerInfo::getFixedStack(FI), false, false,
1521                           0));
1522   }
1523
1524   // Transform all store nodes into one single node because
1525   // all stores are independent of each other.
1526   if (!MemOpChains.empty())
1527     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1528
1529   // Now handle return values copied to registers.
1530   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1531     CCValAssign &VA = RVLocs[i];
1532     if (!VA.isRegLoc())
1533       continue;
1534     // Copy the result values into the output registers.
1535     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1536
1537     // guarantee that all emitted copies are
1538     // stuck together, avoiding something bad
1539     Flag = Chain.getValue(1);
1540     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1541   }
1542
1543   RetOps[0] = Chain;  // Update chain.
1544
1545   // Add the flag if we have it.
1546   if (Flag.getNode())
1547     RetOps.push_back(Flag);
1548
1549   return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1550 }
1551
1552 //===----------------------------------------------------------------------===//
1553 //  Other Lowering Code
1554 //===----------------------------------------------------------------------===//
1555
1556 MachineBasicBlock *
1557 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1558                                                  MachineBasicBlock *BB) const {
1559   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1560   DebugLoc dl = MI->getDebugLoc();
1561   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1562          "Unexpected instr type to insert");
1563
1564   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1565   // control-flow pattern.  The incoming instruction knows the destination vreg
1566   // to set, the condition code register to branch on, the true/false values to
1567   // select between, and a branch opcode to use.
1568   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1569   MachineFunction::iterator It = BB;
1570   ++It;
1571
1572   //  thisMBB:
1573   //  ...
1574   //   TrueVal = ...
1575   //   cmpTY ccX, r1, r2
1576   //   bCC copy1MBB
1577   //   fallthrough --> copy0MBB
1578   MachineBasicBlock *thisMBB = BB;
1579   MachineFunction *F = BB->getParent();
1580   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1581   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1582   F->insert(It, copy0MBB);
1583   F->insert(It, sinkMBB);
1584
1585   // Transfer the remainder of BB and its successor edges to sinkMBB.
1586   sinkMBB->splice(sinkMBB->begin(), BB,
1587                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1588   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1589
1590   // Next, add the true and fallthrough blocks as its successors.
1591   BB->addSuccessor(copy0MBB);
1592   BB->addSuccessor(sinkMBB);
1593
1594   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1595     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1596
1597   //  copy0MBB:
1598   //   %FalseValue = ...
1599   //   # fallthrough to sinkMBB
1600   BB = copy0MBB;
1601
1602   // Update machine-CFG edges
1603   BB->addSuccessor(sinkMBB);
1604
1605   //  sinkMBB:
1606   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1607   //  ...
1608   BB = sinkMBB;
1609   BuildMI(*BB, BB->begin(), dl,
1610           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1611     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1612     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1613
1614   MI->eraseFromParent();   // The pseudo instruction is gone now.
1615   return BB;
1616 }
1617
1618 //===----------------------------------------------------------------------===//
1619 // Target Optimization Hooks
1620 //===----------------------------------------------------------------------===//
1621
1622 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1623                                              DAGCombinerInfo &DCI) const {
1624   SelectionDAG &DAG = DCI.DAG;
1625   SDLoc dl(N);
1626   switch (N->getOpcode()) {
1627   default: break;
1628   case ISD::INTRINSIC_VOID:
1629     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1630     case Intrinsic::xcore_outt:
1631     case Intrinsic::xcore_outct:
1632     case Intrinsic::xcore_chkct: {
1633       SDValue OutVal = N->getOperand(3);
1634       // These instructions ignore the high bits.
1635       if (OutVal.hasOneUse()) {
1636         unsigned BitWidth = OutVal.getValueSizeInBits();
1637         APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1638         APInt KnownZero, KnownOne;
1639         TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1640                                               !DCI.isBeforeLegalizeOps());
1641         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1642         if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1643             TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1644                                      TLO))
1645           DCI.CommitTargetLoweringOpt(TLO);
1646       }
1647       break;
1648     }
1649     case Intrinsic::xcore_setpt: {
1650       SDValue Time = N->getOperand(3);
1651       // This instruction ignores the high bits.
1652       if (Time.hasOneUse()) {
1653         unsigned BitWidth = Time.getValueSizeInBits();
1654         APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1655         APInt KnownZero, KnownOne;
1656         TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1657                                               !DCI.isBeforeLegalizeOps());
1658         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1659         if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1660             TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1661                                      TLO))
1662           DCI.CommitTargetLoweringOpt(TLO);
1663       }
1664       break;
1665     }
1666     }
1667     break;
1668   case XCoreISD::LADD: {
1669     SDValue N0 = N->getOperand(0);
1670     SDValue N1 = N->getOperand(1);
1671     SDValue N2 = N->getOperand(2);
1672     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1674     EVT VT = N0.getValueType();
1675
1676     // canonicalize constant to RHS
1677     if (N0C && !N1C)
1678       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1679
1680     // fold (ladd 0, 0, x) -> 0, x & 1
1681     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1682       SDValue Carry = DAG.getConstant(0, VT);
1683       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1684                                    DAG.getConstant(1, VT));
1685       SDValue Ops[] = { Result, Carry };
1686       return DAG.getMergeValues(Ops, dl);
1687     }
1688
1689     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1690     // low bit set
1691     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1692       APInt KnownZero, KnownOne;
1693       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1694                                          VT.getSizeInBits() - 1);
1695       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1696       if ((KnownZero & Mask) == Mask) {
1697         SDValue Carry = DAG.getConstant(0, VT);
1698         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1699         SDValue Ops[] = { Result, Carry };
1700         return DAG.getMergeValues(Ops, dl);
1701       }
1702     }
1703   }
1704   break;
1705   case XCoreISD::LSUB: {
1706     SDValue N0 = N->getOperand(0);
1707     SDValue N1 = N->getOperand(1);
1708     SDValue N2 = N->getOperand(2);
1709     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1710     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1711     EVT VT = N0.getValueType();
1712
1713     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1714     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1715       APInt KnownZero, KnownOne;
1716       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1717                                          VT.getSizeInBits() - 1);
1718       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1719       if ((KnownZero & Mask) == Mask) {
1720         SDValue Borrow = N2;
1721         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1722                                      DAG.getConstant(0, VT), N2);
1723         SDValue Ops[] = { Result, Borrow };
1724         return DAG.getMergeValues(Ops, dl);
1725       }
1726     }
1727
1728     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1729     // low bit set
1730     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1731       APInt KnownZero, KnownOne;
1732       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1733                                          VT.getSizeInBits() - 1);
1734       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1735       if ((KnownZero & Mask) == Mask) {
1736         SDValue Borrow = DAG.getConstant(0, VT);
1737         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1738         SDValue Ops[] = { Result, Borrow };
1739         return DAG.getMergeValues(Ops, dl);
1740       }
1741     }
1742   }
1743   break;
1744   case XCoreISD::LMUL: {
1745     SDValue N0 = N->getOperand(0);
1746     SDValue N1 = N->getOperand(1);
1747     SDValue N2 = N->getOperand(2);
1748     SDValue N3 = N->getOperand(3);
1749     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1750     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1751     EVT VT = N0.getValueType();
1752     // Canonicalize multiplicative constant to RHS. If both multiplicative
1753     // operands are constant canonicalize smallest to RHS.
1754     if ((N0C && !N1C) ||
1755         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1756       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1757                          N1, N0, N2, N3);
1758
1759     // lmul(x, 0, a, b)
1760     if (N1C && N1C->isNullValue()) {
1761       // If the high result is unused fold to add(a, b)
1762       if (N->hasNUsesOfValue(0, 0)) {
1763         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1764         SDValue Ops[] = { Lo, Lo };
1765         return DAG.getMergeValues(Ops, dl);
1766       }
1767       // Otherwise fold to ladd(a, b, 0)
1768       SDValue Result =
1769         DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1770       SDValue Carry(Result.getNode(), 1);
1771       SDValue Ops[] = { Carry, Result };
1772       return DAG.getMergeValues(Ops, dl);
1773     }
1774   }
1775   break;
1776   case ISD::ADD: {
1777     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1778     // lmul(x, y, a, b). The high result of lmul will be ignored.
1779     // This is only profitable if the intermediate results are unused
1780     // elsewhere.
1781     SDValue Mul0, Mul1, Addend0, Addend1;
1782     if (N->getValueType(0) == MVT::i32 &&
1783         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1784       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1785                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1786                                     Mul1, Addend0, Addend1);
1787       SDValue Result(Ignored.getNode(), 1);
1788       return Result;
1789     }
1790     APInt HighMask = APInt::getHighBitsSet(64, 32);
1791     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1792     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1793     // before type legalization as it is messy to match the operands after
1794     // that.
1795     if (N->getValueType(0) == MVT::i64 &&
1796         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1797         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1798         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1799         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1800         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1801       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1802                                   Mul0, DAG.getConstant(0, MVT::i32));
1803       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1804                                   Mul1, DAG.getConstant(0, MVT::i32));
1805       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1806                                      Addend0, DAG.getConstant(0, MVT::i32));
1807       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1808                                      Addend1, DAG.getConstant(0, MVT::i32));
1809       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1810                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1811                                Addend0L, Addend1L);
1812       SDValue Lo(Hi.getNode(), 1);
1813       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1814     }
1815   }
1816   break;
1817   case ISD::STORE: {
1818     // Replace unaligned store of unaligned load with memmove.
1819     StoreSDNode *ST  = cast<StoreSDNode>(N);
1820     if (!DCI.isBeforeLegalize() ||
1821         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1822         ST->isVolatile() || ST->isIndexed()) {
1823       break;
1824     }
1825     SDValue Chain = ST->getChain();
1826
1827     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1828     if (StoreBits % 8) {
1829       break;
1830     }
1831     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1832         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1833     unsigned Alignment = ST->getAlignment();
1834     if (Alignment >= ABIAlignment) {
1835       break;
1836     }
1837
1838     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1839       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1840         LD->getAlignment() == Alignment &&
1841         !LD->isVolatile() && !LD->isIndexed() &&
1842         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1843         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1844                               LD->getBasePtr(),
1845                               DAG.getConstant(StoreBits/8, MVT::i32),
1846                               Alignment, false, ST->getPointerInfo(),
1847                               LD->getPointerInfo());
1848       }
1849     }
1850     break;
1851   }
1852   }
1853   return SDValue();
1854 }
1855
1856 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1857                                                         APInt &KnownZero,
1858                                                         APInt &KnownOne,
1859                                                         const SelectionDAG &DAG,
1860                                                         unsigned Depth) const {
1861   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1862   switch (Op.getOpcode()) {
1863   default: break;
1864   case XCoreISD::LADD:
1865   case XCoreISD::LSUB:
1866     if (Op.getResNo() == 1) {
1867       // Top bits of carry / borrow are clear.
1868       KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1869                                         KnownZero.getBitWidth() - 1);
1870     }
1871     break;
1872   case ISD::INTRINSIC_W_CHAIN:
1873     {
1874       unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1875       switch (IntNo) {
1876       case Intrinsic::xcore_getts:
1877         // High bits are known to be zero.
1878         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1879                                           KnownZero.getBitWidth() - 16);
1880         break;
1881       case Intrinsic::xcore_int:
1882       case Intrinsic::xcore_inct:
1883         // High bits are known to be zero.
1884         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1885                                           KnownZero.getBitWidth() - 8);
1886         break;
1887       case Intrinsic::xcore_testct:
1888         // Result is either 0 or 1.
1889         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1890                                           KnownZero.getBitWidth() - 1);
1891         break;
1892       case Intrinsic::xcore_testwct:
1893         // Result is in the range 0 - 4.
1894         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1895                                           KnownZero.getBitWidth() - 3);
1896         break;
1897       }
1898     }
1899     break;
1900   }
1901 }
1902
1903 //===----------------------------------------------------------------------===//
1904 //  Addressing mode description hooks
1905 //===----------------------------------------------------------------------===//
1906
1907 static inline bool isImmUs(int64_t val)
1908 {
1909   return (val >= 0 && val <= 11);
1910 }
1911
1912 static inline bool isImmUs2(int64_t val)
1913 {
1914   return (val%2 == 0 && isImmUs(val/2));
1915 }
1916
1917 static inline bool isImmUs4(int64_t val)
1918 {
1919   return (val%4 == 0 && isImmUs(val/4));
1920 }
1921
1922 /// isLegalAddressingMode - Return true if the addressing mode represented
1923 /// by AM is legal for this target, for a load/store of the specified type.
1924 bool
1925 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1926                                               Type *Ty) const {
1927   if (Ty->getTypeID() == Type::VoidTyID)
1928     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1929
1930   const DataLayout *TD = TM.getDataLayout();
1931   unsigned Size = TD->getTypeAllocSize(Ty);
1932   if (AM.BaseGV) {
1933     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1934                  AM.BaseOffs%4 == 0;
1935   }
1936
1937   switch (Size) {
1938   case 1:
1939     // reg + imm
1940     if (AM.Scale == 0) {
1941       return isImmUs(AM.BaseOffs);
1942     }
1943     // reg + reg
1944     return AM.Scale == 1 && AM.BaseOffs == 0;
1945   case 2:
1946   case 3:
1947     // reg + imm
1948     if (AM.Scale == 0) {
1949       return isImmUs2(AM.BaseOffs);
1950     }
1951     // reg + reg<<1
1952     return AM.Scale == 2 && AM.BaseOffs == 0;
1953   default:
1954     // reg + imm
1955     if (AM.Scale == 0) {
1956       return isImmUs4(AM.BaseOffs);
1957     }
1958     // reg + reg<<2
1959     return AM.Scale == 4 && AM.BaseOffs == 0;
1960   }
1961 }
1962
1963 //===----------------------------------------------------------------------===//
1964 //                           XCore Inline Assembly Support
1965 //===----------------------------------------------------------------------===//
1966
1967 std::pair<unsigned, const TargetRegisterClass*>
1968 XCoreTargetLowering::
1969 getRegForInlineAsmConstraint(const std::string &Constraint,
1970                              MVT VT) const {
1971   if (Constraint.size() == 1) {
1972     switch (Constraint[0]) {
1973     default : break;
1974     case 'r':
1975       return std::make_pair(0U, &XCore::GRRegsRegClass);
1976     }
1977   }
1978   // Use the default implementation in TargetLowering to convert the register
1979   // constraint into a member of a register class.
1980   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1981 }