[TargetLowering] StringRefize asm constraint getters.
[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 ((XCoreISD::NodeType)Opcode)
48   {
49     case XCoreISD::FIRST_NUMBER      : break;
50     case XCoreISD::BL                : return "XCoreISD::BL";
51     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
52     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
53     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
54     case XCoreISD::LDWSP             : return "XCoreISD::LDWSP";
55     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
56     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
57     case XCoreISD::LADD              : return "XCoreISD::LADD";
58     case XCoreISD::LSUB              : return "XCoreISD::LSUB";
59     case XCoreISD::LMUL              : return "XCoreISD::LMUL";
60     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
61     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
62     case XCoreISD::CRC8              : return "XCoreISD::CRC8";
63     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
64     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
65     case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
66     case XCoreISD::EH_RETURN         : return "XCoreISD::EH_RETURN";
67     case XCoreISD::MEMBARRIER        : return "XCoreISD::MEMBARRIER";
68   }
69   return nullptr;
70 }
71
72 XCoreTargetLowering::XCoreTargetLowering(const TargetMachine &TM,
73                                          const XCoreSubtarget &Subtarget)
74     : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
75
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78
79   // Compute derived properties from the register classes
80   computeRegisterProperties(Subtarget.getRegisterInfo());
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,   Expand);
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   // 64bit
102   setOperationAction(ISD::ADD, MVT::i64, Custom);
103   setOperationAction(ISD::SUB, MVT::i64, Custom);
104   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
105   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
106   setOperationAction(ISD::MULHS, MVT::i32, Expand);
107   setOperationAction(ISD::MULHU, MVT::i32, Expand);
108   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
109   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
110   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111
112   // Bit Manipulation
113   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
114   setOperationAction(ISD::ROTL , MVT::i32, Expand);
115   setOperationAction(ISD::ROTR , MVT::i32, Expand);
116   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
117   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
118
119   setOperationAction(ISD::TRAP, MVT::Other, Legal);
120
121   // Jump tables.
122   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
123
124   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
125   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
126
127   // Conversion of i64 -> double produces constantpool nodes
128   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
129
130   // Loads
131   for (MVT VT : MVT::integer_valuetypes()) {
132     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
133     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
134     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
135
136     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
137     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Expand);
138   }
139
140   // Custom expand misaligned loads / stores.
141   setOperationAction(ISD::LOAD, MVT::i32, Custom);
142   setOperationAction(ISD::STORE, MVT::i32, Custom);
143
144   // Varargs
145   setOperationAction(ISD::VAEND, MVT::Other, Expand);
146   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
147   setOperationAction(ISD::VAARG, MVT::Other, Custom);
148   setOperationAction(ISD::VASTART, MVT::Other, Custom);
149
150   // Dynamic stack
151   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
152   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
153   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
154
155   // Exception handling
156   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
157   setExceptionPointerRegister(XCore::R0);
158   setExceptionSelectorRegister(XCore::R1);
159   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
160
161   // Atomic operations
162   // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
163   // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
164   setInsertFencesForAtomic(true);
165   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
166   setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
167   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
168
169   // TRAMPOLINE is custom lowered.
170   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
171   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
172
173   // We want to custom lower some of our intrinsics.
174   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
175
176   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
177   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
178     = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
179
180   // We have target-specific dag combine patterns for the following nodes:
181   setTargetDAGCombine(ISD::STORE);
182   setTargetDAGCombine(ISD::ADD);
183   setTargetDAGCombine(ISD::INTRINSIC_VOID);
184   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
185
186   setMinFunctionAlignment(1);
187   setPrefFunctionAlignment(2);
188 }
189
190 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
191   if (Val.getOpcode() != ISD::LOAD)
192     return false;
193
194   EVT VT1 = Val.getValueType();
195   if (!VT1.isSimple() || !VT1.isInteger() ||
196       !VT2.isSimple() || !VT2.isInteger())
197     return false;
198
199   switch (VT1.getSimpleVT().SimpleTy) {
200   default: break;
201   case MVT::i8:
202     return true;
203   }
204
205   return false;
206 }
207
208 SDValue XCoreTargetLowering::
209 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
210   switch (Op.getOpcode())
211   {
212   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
213   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
214   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
215   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
216   case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
217   case ISD::LOAD:               return LowerLOAD(Op, DAG);
218   case ISD::STORE:              return LowerSTORE(Op, DAG);
219   case ISD::VAARG:              return LowerVAARG(Op, DAG);
220   case ISD::VASTART:            return LowerVASTART(Op, DAG);
221   case ISD::SMUL_LOHI:          return LowerSMUL_LOHI(Op, DAG);
222   case ISD::UMUL_LOHI:          return LowerUMUL_LOHI(Op, DAG);
223   // FIXME: Remove these when LegalizeDAGTypes lands.
224   case ISD::ADD:
225   case ISD::SUB:                return ExpandADDSUB(Op.getNode(), DAG);
226   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
227   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
228   case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
229   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
230   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
231   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
232   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
233   case ISD::ATOMIC_LOAD:        return LowerATOMIC_LOAD(Op, DAG);
234   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG);
235   default:
236     llvm_unreachable("unimplemented operand");
237   }
238 }
239
240 /// ReplaceNodeResults - Replace the results of node with an illegal result
241 /// type with new values built out of custom code.
242 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
243                                              SmallVectorImpl<SDValue>&Results,
244                                              SelectionDAG &DAG) const {
245   switch (N->getOpcode()) {
246   default:
247     llvm_unreachable("Don't know how to custom expand this!");
248   case ISD::ADD:
249   case ISD::SUB:
250     Results.push_back(ExpandADDSUB(N, DAG));
251     return;
252   }
253 }
254
255 //===----------------------------------------------------------------------===//
256 //  Misc Lower Operation implementation
257 //===----------------------------------------------------------------------===//
258
259 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
260                                                      const GlobalValue *GV,
261                                                      SelectionDAG &DAG) const {
262   // FIXME there is no actual debug info here
263   SDLoc dl(GA);
264
265   if (GV->getType()->getElementType()->isFunctionTy())
266     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
267
268   const auto *GVar = dyn_cast<GlobalVariable>(GV);
269   if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
270       (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
271     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
272
273   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
274 }
275
276 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
277   if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
278     return true;
279
280   Type *ObjType = GV->getType()->getPointerElementType();
281   if (!ObjType->isSized())
282     return false;
283
284   unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
285   return ObjSize < CodeModelLargeSize && ObjSize != 0;
286 }
287
288 SDValue XCoreTargetLowering::
289 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
290 {
291   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
292   const GlobalValue *GV = GN->getGlobal();
293   SDLoc DL(GN);
294   int64_t Offset = GN->getOffset();
295   if (IsSmallObject(GV, *this)) {
296     // We can only fold positive offsets that are a multiple of the word size.
297     int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
298     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
299     GA = getGlobalAddressWrapper(GA, GV, DAG);
300     // Handle the rest of the offset.
301     if (Offset != FoldedOffset) {
302       SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
303       GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
304     }
305     return GA;
306   } else {
307     // Ideally we would not fold in offset with an index <= 11.
308     Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
309     Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
310     Ty = Type::getInt32Ty(*DAG.getContext());
311     Constant *Idx = ConstantInt::get(Ty, Offset);
312     Constant *GAI = ConstantExpr::getGetElementPtr(
313         Type::getInt8Ty(*DAG.getContext()), GA, Idx);
314     SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
315     return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
316                        MachinePointerInfo(), false, false, false, 0);
317   }
318 }
319
320 SDValue XCoreTargetLowering::
321 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
322 {
323   SDLoc DL(Op);
324
325   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
326   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
327
328   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
329 }
330
331 SDValue XCoreTargetLowering::
332 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
333 {
334   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
335   // FIXME there isn't really debug info here
336   SDLoc dl(CP);
337   EVT PtrVT = Op.getValueType();
338   SDValue Res;
339   if (CP->isMachineConstantPoolEntry()) {
340     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
341                                     CP->getAlignment(), CP->getOffset());
342   } else {
343     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
344                                     CP->getAlignment(), CP->getOffset());
345   }
346   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
347 }
348
349 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
350   return MachineJumpTableInfo::EK_Inline;
351 }
352
353 SDValue XCoreTargetLowering::
354 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
355 {
356   SDValue Chain = Op.getOperand(0);
357   SDValue Table = Op.getOperand(1);
358   SDValue Index = Op.getOperand(2);
359   SDLoc dl(Op);
360   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
361   unsigned JTI = JT->getIndex();
362   MachineFunction &MF = DAG.getMachineFunction();
363   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
364   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
365
366   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
367   if (NumEntries <= 32) {
368     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
369   }
370   assert((NumEntries >> 31) == 0);
371   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
372                                     DAG.getConstant(1, dl, MVT::i32));
373   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
374                      ScaledIndex);
375 }
376
377 SDValue XCoreTargetLowering::
378 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
379                                        int64_t Offset, SelectionDAG &DAG) const
380 {
381   if ((Offset & 0x3) == 0) {
382     return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
383                        false, false, false, 0);
384   }
385   // Lower to pair of consecutive word aligned loads plus some bit shifting.
386   int32_t HighOffset = RoundUpToAlignment(Offset, 4);
387   int32_t LowOffset = HighOffset - 4;
388   SDValue LowAddr, HighAddr;
389   if (GlobalAddressSDNode *GASD =
390         dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
391     LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
392                                    LowOffset);
393     HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
394                                     HighOffset);
395   } else {
396     LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
397                           DAG.getConstant(LowOffset, DL, MVT::i32));
398     HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
399                            DAG.getConstant(HighOffset, DL, MVT::i32));
400   }
401   SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
402   SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
403
404   SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
405                             LowAddr, MachinePointerInfo(),
406                             false, false, false, 0);
407   SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
408                              HighAddr, MachinePointerInfo(),
409                              false, false, false, 0);
410   SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
411   SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
412   SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
413   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
414                       High.getValue(1));
415   SDValue Ops[] = { Result, Chain };
416   return DAG.getMergeValues(Ops, DL);
417 }
418
419 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
420 {
421   APInt KnownZero, KnownOne;
422   DAG.computeKnownBits(Value, KnownZero, KnownOne);
423   return KnownZero.countTrailingOnes() >= 2;
424 }
425
426 SDValue XCoreTargetLowering::
427 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
429   LoadSDNode *LD = cast<LoadSDNode>(Op);
430   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
431          "Unexpected extension type");
432   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
433   if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
434                                      LD->getAddressSpace(),
435                                      LD->getAlignment()))
436     return SDValue();
437
438   unsigned ABIAlignment = getDataLayout()->
439     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
440   // Leave aligned load alone.
441   if (LD->getAlignment() >= ABIAlignment)
442     return SDValue();
443
444   SDValue Chain = LD->getChain();
445   SDValue BasePtr = LD->getBasePtr();
446   SDLoc DL(Op);
447
448   if (!LD->isVolatile()) {
449     const GlobalValue *GV;
450     int64_t Offset = 0;
451     if (DAG.isBaseWithConstantOffset(BasePtr) &&
452         isWordAligned(BasePtr->getOperand(0), DAG)) {
453       SDValue NewBasePtr = BasePtr->getOperand(0);
454       Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
455       return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
456                                                     Offset, DAG);
457     }
458     if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
459         MinAlign(GV->getAlignment(), 4) == 4) {
460       SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
461                                                 BasePtr->getValueType(0));
462       return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
463                                                     Offset, DAG);
464     }
465   }
466
467   if (LD->getAlignment() == 2) {
468     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
469                                  BasePtr, LD->getPointerInfo(), MVT::i16,
470                                  LD->isVolatile(), LD->isNonTemporal(),
471                                  LD->isInvariant(), 2);
472     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
473                                    DAG.getConstant(2, DL, MVT::i32));
474     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
475                                   HighAddr,
476                                   LD->getPointerInfo().getWithOffset(2),
477                                   MVT::i16, LD->isVolatile(),
478                                   LD->isNonTemporal(), LD->isInvariant(), 2);
479     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
480                                       DAG.getConstant(16, DL, MVT::i32));
481     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
482     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
483                              High.getValue(1));
484     SDValue Ops[] = { Result, Chain };
485     return DAG.getMergeValues(Ops, DL);
486   }
487
488   // Lower to a call to __misaligned_load(BasePtr).
489   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
490   TargetLowering::ArgListTy Args;
491   TargetLowering::ArgListEntry Entry;
492
493   Entry.Ty = IntPtrTy;
494   Entry.Node = BasePtr;
495   Args.push_back(Entry);
496
497   TargetLowering::CallLoweringInfo CLI(DAG);
498   CLI.setDebugLoc(DL).setChain(Chain)
499     .setCallee(CallingConv::C, IntPtrTy,
500                DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
501                std::move(Args), 0);
502
503   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
504   SDValue Ops[] = { CallResult.first, CallResult.second };
505   return DAG.getMergeValues(Ops, DL);
506 }
507
508 SDValue XCoreTargetLowering::
509 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
510 {
511   StoreSDNode *ST = cast<StoreSDNode>(Op);
512   assert(!ST->isTruncatingStore() && "Unexpected store type");
513   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
514   if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
515                                      ST->getAddressSpace(),
516                                      ST->getAlignment())) {
517     return SDValue();
518   }
519   unsigned ABIAlignment = getDataLayout()->
520     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
521   // Leave aligned store alone.
522   if (ST->getAlignment() >= ABIAlignment) {
523     return SDValue();
524   }
525   SDValue Chain = ST->getChain();
526   SDValue BasePtr = ST->getBasePtr();
527   SDValue Value = ST->getValue();
528   SDLoc dl(Op);
529
530   if (ST->getAlignment() == 2) {
531     SDValue Low = Value;
532     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
533                                       DAG.getConstant(16, dl, MVT::i32));
534     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
535                                          ST->getPointerInfo(), MVT::i16,
536                                          ST->isVolatile(), ST->isNonTemporal(),
537                                          2);
538     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
539                                    DAG.getConstant(2, dl, MVT::i32));
540     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
541                                           ST->getPointerInfo().getWithOffset(2),
542                                           MVT::i16, ST->isVolatile(),
543                                           ST->isNonTemporal(), 2);
544     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
545   }
546
547   // Lower to a call to __misaligned_store(BasePtr, Value).
548   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
549   TargetLowering::ArgListTy Args;
550   TargetLowering::ArgListEntry Entry;
551
552   Entry.Ty = IntPtrTy;
553   Entry.Node = BasePtr;
554   Args.push_back(Entry);
555
556   Entry.Node = Value;
557   Args.push_back(Entry);
558
559   TargetLowering::CallLoweringInfo CLI(DAG);
560   CLI.setDebugLoc(dl).setChain(Chain)
561     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
562                DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
563                std::move(Args), 0);
564
565   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
566   return CallResult.second;
567 }
568
569 SDValue XCoreTargetLowering::
570 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
571 {
572   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
573          "Unexpected operand to lower!");
574   SDLoc dl(Op);
575   SDValue LHS = Op.getOperand(0);
576   SDValue RHS = Op.getOperand(1);
577   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
578   SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
579                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
580                            LHS, RHS);
581   SDValue Lo(Hi.getNode(), 1);
582   SDValue Ops[] = { Lo, Hi };
583   return DAG.getMergeValues(Ops, dl);
584 }
585
586 SDValue XCoreTargetLowering::
587 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
588 {
589   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
590          "Unexpected operand to lower!");
591   SDLoc dl(Op);
592   SDValue LHS = Op.getOperand(0);
593   SDValue RHS = Op.getOperand(1);
594   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
595   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
596                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
597                            Zero, Zero);
598   SDValue Lo(Hi.getNode(), 1);
599   SDValue Ops[] = { Lo, Hi };
600   return DAG.getMergeValues(Ops, dl);
601 }
602
603 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
604 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
605 /// each intermediate result in the calculation must also have a single use.
606 /// If the Op is in the correct form the constituent parts are written to Mul0,
607 /// Mul1, Addend0 and Addend1.
608 static bool
609 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
610             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
611 {
612   if (Op.getOpcode() != ISD::ADD)
613     return false;
614   SDValue N0 = Op.getOperand(0);
615   SDValue N1 = Op.getOperand(1);
616   SDValue AddOp;
617   SDValue OtherOp;
618   if (N0.getOpcode() == ISD::ADD) {
619     AddOp = N0;
620     OtherOp = N1;
621   } else if (N1.getOpcode() == ISD::ADD) {
622     AddOp = N1;
623     OtherOp = N0;
624   } else {
625     return false;
626   }
627   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
628     return false;
629   if (OtherOp.getOpcode() == ISD::MUL) {
630     // add(add(a,b),mul(x,y))
631     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
632       return false;
633     Mul0 = OtherOp.getOperand(0);
634     Mul1 = OtherOp.getOperand(1);
635     Addend0 = AddOp.getOperand(0);
636     Addend1 = AddOp.getOperand(1);
637     return true;
638   }
639   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
640     // add(add(mul(x,y),a),b)
641     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
642       return false;
643     Mul0 = AddOp.getOperand(0).getOperand(0);
644     Mul1 = AddOp.getOperand(0).getOperand(1);
645     Addend0 = AddOp.getOperand(1);
646     Addend1 = OtherOp;
647     return true;
648   }
649   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
650     // add(add(a,mul(x,y)),b)
651     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
652       return false;
653     Mul0 = AddOp.getOperand(1).getOperand(0);
654     Mul1 = AddOp.getOperand(1).getOperand(1);
655     Addend0 = AddOp.getOperand(0);
656     Addend1 = OtherOp;
657     return true;
658   }
659   return false;
660 }
661
662 SDValue XCoreTargetLowering::
663 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
664 {
665   SDValue Mul;
666   SDValue Other;
667   if (N->getOperand(0).getOpcode() == ISD::MUL) {
668     Mul = N->getOperand(0);
669     Other = N->getOperand(1);
670   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
671     Mul = N->getOperand(1);
672     Other = N->getOperand(0);
673   } else {
674     return SDValue();
675   }
676   SDLoc dl(N);
677   SDValue LL, RL, AddendL, AddendH;
678   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
679                    Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
680   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
681                    Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
682   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
683                         Other, DAG.getConstant(0, dl, MVT::i32));
684   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685                         Other, DAG.getConstant(1, dl, MVT::i32));
686   APInt HighMask = APInt::getHighBitsSet(64, 32);
687   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
688   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
689   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
690       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
691     // The inputs are both zero-extended.
692     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
693                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
694                              AddendL, LL, RL);
695     SDValue Lo(Hi.getNode(), 1);
696     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
697   }
698   if (LHSSB > 32 && RHSSB > 32) {
699     // The inputs are both sign-extended.
700     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
701                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
702                              AddendL, LL, RL);
703     SDValue Lo(Hi.getNode(), 1);
704     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
705   }
706   SDValue LH, RH;
707   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
708                    Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
709   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
710                    Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
711   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
712                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
713                            AddendL, LL, RL);
714   SDValue Lo(Hi.getNode(), 1);
715   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
716   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
717   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
718   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
719   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
720 }
721
722 SDValue XCoreTargetLowering::
723 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
724 {
725   assert(N->getValueType(0) == MVT::i64 &&
726          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
727         "Unknown operand to lower!");
728
729   if (N->getOpcode() == ISD::ADD) {
730     SDValue Result = TryExpandADDWithMul(N, DAG);
731     if (Result.getNode())
732       return Result;
733   }
734
735   SDLoc dl(N);
736
737   // Extract components
738   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
739                              N->getOperand(0),
740                              DAG.getConstant(0, dl, MVT::i32));
741   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
742                              N->getOperand(0),
743                              DAG.getConstant(1, dl, MVT::i32));
744   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745                              N->getOperand(1),
746                              DAG.getConstant(0, dl, MVT::i32));
747   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
748                              N->getOperand(1),
749                              DAG.getConstant(1, dl, MVT::i32));
750
751   // Expand
752   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
753                                                    XCoreISD::LSUB;
754   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
755   SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
756                            LHSL, RHSL, Zero);
757   SDValue Carry(Lo.getNode(), 1);
758
759   SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
760                            LHSH, RHSH, Carry);
761   SDValue Ignored(Hi.getNode(), 1);
762   // Merge the pieces
763   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
764 }
765
766 SDValue XCoreTargetLowering::
767 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
768 {
769   // Whist llvm does not support aggregate varargs we can ignore
770   // the possibility of the ValueType being an implicit byVal vararg.
771   SDNode *Node = Op.getNode();
772   EVT VT = Node->getValueType(0); // not an aggregate
773   SDValue InChain = Node->getOperand(0);
774   SDValue VAListPtr = Node->getOperand(1);
775   EVT PtrVT = VAListPtr.getValueType();
776   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
777   SDLoc dl(Node);
778   SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
779                                VAListPtr, MachinePointerInfo(SV),
780                                false, false, false, 0);
781   // Increment the pointer, VAList, to the next vararg
782   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
783                                 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
784                                                       dl));
785   // Store the incremented VAList to the legalized pointer
786   InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
787                          MachinePointerInfo(SV), false, false, 0);
788   // Load the actual argument out of the pointer VAList
789   return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
790                      false, false, false, 0);
791 }
792
793 SDValue XCoreTargetLowering::
794 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
795 {
796   SDLoc dl(Op);
797   // vastart stores the address of the VarArgsFrameIndex slot into the
798   // memory location argument
799   MachineFunction &MF = DAG.getMachineFunction();
800   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
801   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
802   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
803                       MachinePointerInfo(), false, false, 0);
804 }
805
806 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
807                                             SelectionDAG &DAG) const {
808   // This nodes represent llvm.frameaddress on the DAG.
809   // It takes one operand, the index of the frame address to return.
810   // An index of zero corresponds to the current function's frame address.
811   // An index of one to the parent's frame address, and so on.
812   // Depths > 0 not supported yet!
813   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
814     return SDValue();
815
816   MachineFunction &MF = DAG.getMachineFunction();
817   const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
818   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
819                             RegInfo->getFrameRegister(MF), MVT::i32);
820 }
821
822 SDValue XCoreTargetLowering::
823 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
824   // This nodes represent llvm.returnaddress on the DAG.
825   // It takes one operand, the index of the return address to return.
826   // An index of zero corresponds to the current function's return address.
827   // An index of one to the parent's return address, and so on.
828   // Depths > 0 not supported yet!
829   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
830     return SDValue();
831
832   MachineFunction &MF = DAG.getMachineFunction();
833   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
834   int FI = XFI->createLRSpillSlot(MF);
835   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
836   return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
837                      MachinePointerInfo::getFixedStack(FI), false, false,
838                      false, 0);
839 }
840
841 SDValue XCoreTargetLowering::
842 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
843   // This node represents offset from frame pointer to first on-stack argument.
844   // This is needed for correct stack adjustment during unwind.
845   // However, we don't know the offset until after the frame has be finalised.
846   // This is done during the XCoreFTAOElim pass.
847   return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
848 }
849
850 SDValue XCoreTargetLowering::
851 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
852   // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
853   // This node represents 'eh_return' gcc dwarf builtin, which is used to
854   // return from exception. The general meaning is: adjust stack by OFFSET and
855   // pass execution to HANDLER.
856   MachineFunction &MF = DAG.getMachineFunction();
857   SDValue Chain     = Op.getOperand(0);
858   SDValue Offset    = Op.getOperand(1);
859   SDValue Handler   = Op.getOperand(2);
860   SDLoc dl(Op);
861
862   // Absolute SP = (FP + FrameToArgs) + Offset
863   const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
864   SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
865                             RegInfo->getFrameRegister(MF), MVT::i32);
866   SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
867                                     MVT::i32);
868   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
869   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
870
871   // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
872   // which leaves 2 caller saved registers, R2 & R3 for us to use.
873   unsigned StackReg = XCore::R2;
874   unsigned HandlerReg = XCore::R3;
875
876   SDValue OutChains[] = {
877     DAG.getCopyToReg(Chain, dl, StackReg, Stack),
878     DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
879   };
880
881   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
882
883   return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
884                      DAG.getRegister(StackReg, MVT::i32),
885                      DAG.getRegister(HandlerReg, MVT::i32));
886
887 }
888
889 SDValue XCoreTargetLowering::
890 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
891   return Op.getOperand(0);
892 }
893
894 SDValue XCoreTargetLowering::
895 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
896   SDValue Chain = Op.getOperand(0);
897   SDValue Trmp = Op.getOperand(1); // trampoline
898   SDValue FPtr = Op.getOperand(2); // nested function
899   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
900
901   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
902
903   // .align 4
904   // LDAPF_u10 r11, nest
905   // LDW_2rus r11, r11[0]
906   // STWSP_ru6 r11, sp[0]
907   // LDAPF_u10 r11, fptr
908   // LDW_2rus r11, r11[0]
909   // BAU_1r r11
910   // nest:
911   // .word nest
912   // fptr:
913   // .word fptr
914   SDValue OutChains[5];
915
916   SDValue Addr = Trmp;
917
918   SDLoc dl(Op);
919   OutChains[0] = DAG.getStore(Chain, dl,
920                               DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
921                               MachinePointerInfo(TrmpAddr), false, false, 0);
922
923   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
924                      DAG.getConstant(4, dl, MVT::i32));
925   OutChains[1] = DAG.getStore(Chain, dl,
926                               DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
927                               MachinePointerInfo(TrmpAddr, 4), false, false, 0);
928
929   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
930                      DAG.getConstant(8, dl, MVT::i32));
931   OutChains[2] = DAG.getStore(Chain, dl,
932                               DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
933                               MachinePointerInfo(TrmpAddr, 8), false, false, 0);
934
935   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
936                      DAG.getConstant(12, dl, MVT::i32));
937   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
938                               MachinePointerInfo(TrmpAddr, 12), false, false,
939                               0);
940
941   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
942                      DAG.getConstant(16, dl, MVT::i32));
943   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
944                               MachinePointerInfo(TrmpAddr, 16), false, false,
945                               0);
946
947   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
948 }
949
950 SDValue XCoreTargetLowering::
951 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
952   SDLoc DL(Op);
953   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
954   switch (IntNo) {
955     case Intrinsic::xcore_crc8:
956       EVT VT = Op.getValueType();
957       SDValue Data =
958         DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
959                     Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
960       SDValue Crc(Data.getNode(), 1);
961       SDValue Results[] = { Crc, Data };
962       return DAG.getMergeValues(Results, DL);
963   }
964   return SDValue();
965 }
966
967 SDValue XCoreTargetLowering::
968 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
969   SDLoc DL(Op);
970   return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
971 }
972
973 SDValue XCoreTargetLowering::
974 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
975   AtomicSDNode *N = cast<AtomicSDNode>(Op);
976   assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
977   assert(N->getOrdering() <= Monotonic &&
978          "setInsertFencesForAtomic(true) and yet greater than Monotonic");
979   if (N->getMemoryVT() == MVT::i32) {
980     if (N->getAlignment() < 4)
981       report_fatal_error("atomic load must be aligned");
982     return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
983                        N->getBasePtr(), N->getPointerInfo(),
984                        N->isVolatile(), N->isNonTemporal(),
985                        N->isInvariant(), N->getAlignment(),
986                        N->getAAInfo(), N->getRanges());
987   }
988   if (N->getMemoryVT() == MVT::i16) {
989     if (N->getAlignment() < 2)
990       report_fatal_error("atomic load must be aligned");
991     return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
992                           N->getBasePtr(), N->getPointerInfo(), MVT::i16,
993                           N->isVolatile(), N->isNonTemporal(),
994                           N->isInvariant(), N->getAlignment(), N->getAAInfo());
995   }
996   if (N->getMemoryVT() == MVT::i8)
997     return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
998                           N->getBasePtr(), N->getPointerInfo(), MVT::i8,
999                           N->isVolatile(), N->isNonTemporal(),
1000                           N->isInvariant(), N->getAlignment(), N->getAAInfo());
1001   return SDValue();
1002 }
1003
1004 SDValue XCoreTargetLowering::
1005 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1006   AtomicSDNode *N = cast<AtomicSDNode>(Op);
1007   assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1008   assert(N->getOrdering() <= Monotonic &&
1009          "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1010   if (N->getMemoryVT() == MVT::i32) {
1011     if (N->getAlignment() < 4)
1012       report_fatal_error("atomic store must be aligned");
1013     return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1014                         N->getBasePtr(), N->getPointerInfo(),
1015                         N->isVolatile(), N->isNonTemporal(),
1016                         N->getAlignment(), N->getAAInfo());
1017   }
1018   if (N->getMemoryVT() == MVT::i16) {
1019     if (N->getAlignment() < 2)
1020       report_fatal_error("atomic store must be aligned");
1021     return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1022                              N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1023                              N->isVolatile(), N->isNonTemporal(),
1024                              N->getAlignment(), N->getAAInfo());
1025   }
1026   if (N->getMemoryVT() == MVT::i8)
1027     return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1028                              N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1029                              N->isVolatile(), N->isNonTemporal(),
1030                              N->getAlignment(), N->getAAInfo());
1031   return SDValue();
1032 }
1033
1034 //===----------------------------------------------------------------------===//
1035 //                      Calling Convention Implementation
1036 //===----------------------------------------------------------------------===//
1037
1038 #include "XCoreGenCallingConv.inc"
1039
1040 //===----------------------------------------------------------------------===//
1041 //                  Call Calling Convention Implementation
1042 //===----------------------------------------------------------------------===//
1043
1044 /// XCore call implementation
1045 SDValue
1046 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1047                                SmallVectorImpl<SDValue> &InVals) const {
1048   SelectionDAG &DAG                     = CLI.DAG;
1049   SDLoc &dl                             = CLI.DL;
1050   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1051   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1052   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1053   SDValue Chain                         = CLI.Chain;
1054   SDValue Callee                        = CLI.Callee;
1055   bool &isTailCall                      = CLI.IsTailCall;
1056   CallingConv::ID CallConv              = CLI.CallConv;
1057   bool isVarArg                         = CLI.IsVarArg;
1058
1059   // XCore target does not yet support tail call optimization.
1060   isTailCall = false;
1061
1062   // For now, only CallingConv::C implemented
1063   switch (CallConv)
1064   {
1065     default:
1066       llvm_unreachable("Unsupported calling convention");
1067     case CallingConv::Fast:
1068     case CallingConv::C:
1069       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1070                             Outs, OutVals, Ins, dl, DAG, InVals);
1071   }
1072 }
1073
1074 /// LowerCallResult - Lower the result values of a call into the
1075 /// appropriate copies out of appropriate physical registers / memory locations.
1076 static SDValue
1077 LowerCallResult(SDValue Chain, SDValue InFlag,
1078                 const SmallVectorImpl<CCValAssign> &RVLocs,
1079                 SDLoc dl, SelectionDAG &DAG,
1080                 SmallVectorImpl<SDValue> &InVals) {
1081   SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1082   // Copy results out of physical registers.
1083   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1084     const CCValAssign &VA = RVLocs[i];
1085     if (VA.isRegLoc()) {
1086       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1087                                  InFlag).getValue(1);
1088       InFlag = Chain.getValue(2);
1089       InVals.push_back(Chain.getValue(0));
1090     } else {
1091       assert(VA.isMemLoc());
1092       ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1093                                              InVals.size()));
1094       // Reserve space for this result.
1095       InVals.push_back(SDValue());
1096     }
1097   }
1098
1099   // Copy results out of memory.
1100   SmallVector<SDValue, 4> MemOpChains;
1101   for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1102     int offset = ResultMemLocs[i].first;
1103     unsigned index = ResultMemLocs[i].second;
1104     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1105     SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1106     SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1107     InVals[index] = load;
1108     MemOpChains.push_back(load.getValue(1));
1109   }
1110
1111   // Transform all loads nodes into one single node because
1112   // all load nodes are independent of each other.
1113   if (!MemOpChains.empty())
1114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1115
1116   return Chain;
1117 }
1118
1119 /// LowerCCCCallTo - functions arguments are copied from virtual
1120 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1121 /// CALLSEQ_END are emitted.
1122 /// TODO: isTailCall, sret.
1123 SDValue
1124 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1125                                     CallingConv::ID CallConv, bool isVarArg,
1126                                     bool isTailCall,
1127                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1128                                     const SmallVectorImpl<SDValue> &OutVals,
1129                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1130                                     SDLoc dl, SelectionDAG &DAG,
1131                                     SmallVectorImpl<SDValue> &InVals) const {
1132
1133   // Analyze operands of the call, assigning locations to each operand.
1134   SmallVector<CCValAssign, 16> ArgLocs;
1135   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1136                  *DAG.getContext());
1137
1138   // The ABI dictates there should be one stack slot available to the callee
1139   // on function entry (for saving lr).
1140   CCInfo.AllocateStack(4, 4);
1141
1142   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1143
1144   SmallVector<CCValAssign, 16> RVLocs;
1145   // Analyze return values to determine the number of bytes of stack required.
1146   CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1147                     *DAG.getContext());
1148   RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1149   RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1150
1151   // Get a count of how many bytes are to be pushed on the stack.
1152   unsigned NumBytes = RetCCInfo.getNextStackOffset();
1153
1154   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, dl,
1155                                  getPointerTy(), true), dl);
1156
1157   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1158   SmallVector<SDValue, 12> MemOpChains;
1159
1160   // Walk the register/memloc assignments, inserting copies/loads.
1161   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1162     CCValAssign &VA = ArgLocs[i];
1163     SDValue Arg = OutVals[i];
1164
1165     // Promote the value if needed.
1166     switch (VA.getLocInfo()) {
1167       default: llvm_unreachable("Unknown loc info!");
1168       case CCValAssign::Full: break;
1169       case CCValAssign::SExt:
1170         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1171         break;
1172       case CCValAssign::ZExt:
1173         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1174         break;
1175       case CCValAssign::AExt:
1176         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1177         break;
1178     }
1179
1180     // Arguments that can be passed on register must be kept at
1181     // RegsToPass vector
1182     if (VA.isRegLoc()) {
1183       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1184     } else {
1185       assert(VA.isMemLoc());
1186
1187       int Offset = VA.getLocMemOffset();
1188
1189       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1190                                         Chain, Arg,
1191                                         DAG.getConstant(Offset/4, dl,
1192                                                         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, dl, getPointerTy(),
1244                                              true),
1245                              DAG.getConstant(0, dl, getPointerTy(), true),
1246                              InFlag, dl);
1247   InFlag = Chain.getValue(1);
1248
1249   // Handle result values, copying them out of physregs into vregs that we
1250   // return.
1251   return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 //             Formal Arguments Calling Convention Implementation
1256 //===----------------------------------------------------------------------===//
1257
1258 namespace {
1259   struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1260 }
1261
1262 /// XCore formal arguments implementation
1263 SDValue
1264 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1265                                           CallingConv::ID CallConv,
1266                                           bool isVarArg,
1267                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1268                                           SDLoc dl,
1269                                           SelectionDAG &DAG,
1270                                           SmallVectorImpl<SDValue> &InVals)
1271                                             const {
1272   switch (CallConv)
1273   {
1274     default:
1275       llvm_unreachable("Unsupported calling convention");
1276     case CallingConv::C:
1277     case CallingConv::Fast:
1278       return LowerCCCArguments(Chain, CallConv, isVarArg,
1279                                Ins, dl, DAG, InVals);
1280   }
1281 }
1282
1283 /// LowerCCCArguments - transform physical registers into
1284 /// virtual registers and generate load operations for
1285 /// arguments places on the stack.
1286 /// TODO: sret
1287 SDValue
1288 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1289                                        CallingConv::ID CallConv,
1290                                        bool isVarArg,
1291                                        const SmallVectorImpl<ISD::InputArg>
1292                                          &Ins,
1293                                        SDLoc dl,
1294                                        SelectionDAG &DAG,
1295                                        SmallVectorImpl<SDValue> &InVals) const {
1296   MachineFunction &MF = DAG.getMachineFunction();
1297   MachineFrameInfo *MFI = MF.getFrameInfo();
1298   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1299   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1300
1301   // Assign locations to all of the incoming arguments.
1302   SmallVector<CCValAssign, 16> ArgLocs;
1303   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1304                  *DAG.getContext());
1305
1306   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1307
1308   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1309
1310   unsigned LRSaveSize = StackSlotSize;
1311
1312   if (!isVarArg)
1313     XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1314
1315   // All getCopyFromReg ops must precede any getMemcpys to prevent the
1316   // scheduler clobbering a register before it has been copied.
1317   // The stages are:
1318   // 1. CopyFromReg (and load) arg & vararg registers.
1319   // 2. Chain CopyFromReg nodes into a TokenFactor.
1320   // 3. Memcpy 'byVal' args & push final InVals.
1321   // 4. Chain mem ops nodes into a TokenFactor.
1322   SmallVector<SDValue, 4> CFRegNode;
1323   SmallVector<ArgDataPair, 4> ArgData;
1324   SmallVector<SDValue, 4> MemOps;
1325
1326   // 1a. CopyFromReg (and load) arg registers.
1327   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1328
1329     CCValAssign &VA = ArgLocs[i];
1330     SDValue ArgIn;
1331
1332     if (VA.isRegLoc()) {
1333       // Arguments passed in registers
1334       EVT RegVT = VA.getLocVT();
1335       switch (RegVT.getSimpleVT().SimpleTy) {
1336       default:
1337         {
1338 #ifndef NDEBUG
1339           errs() << "LowerFormalArguments Unhandled argument type: "
1340                  << RegVT.getSimpleVT().SimpleTy << "\n";
1341 #endif
1342           llvm_unreachable(nullptr);
1343         }
1344       case MVT::i32:
1345         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1346         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1347         ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1348         CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1349       }
1350     } else {
1351       // sanity check
1352       assert(VA.isMemLoc());
1353       // Load the argument to a virtual register
1354       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1355       if (ObjSize > StackSlotSize) {
1356         errs() << "LowerFormalArguments Unhandled argument type: "
1357                << EVT(VA.getLocVT()).getEVTString()
1358                << "\n";
1359       }
1360       // Create the frame index object for this incoming parameter...
1361       int FI = MFI->CreateFixedObject(ObjSize,
1362                                       LRSaveSize + VA.getLocMemOffset(),
1363                                       true);
1364
1365       // Create the SelectionDAG nodes corresponding to a load
1366       //from this parameter
1367       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1368       ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1369                           MachinePointerInfo::getFixedStack(FI),
1370                           false, false, false, 0);
1371     }
1372     const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1373     ArgData.push_back(ADP);
1374   }
1375
1376   // 1b. CopyFromReg vararg registers.
1377   if (isVarArg) {
1378     // Argument registers
1379     static const MCPhysReg ArgRegs[] = {
1380       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1381     };
1382     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1383     unsigned FirstVAReg = CCInfo.getFirstUnallocated(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, dl, MVT::i32),
1434                                      Align, false, 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, 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(), RVLocs,
1486                  *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, dl, 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 = *Subtarget.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, dl, VT);
1683       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1684                                    DAG.getConstant(1, dl, 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, dl, 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, dl, 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, dl, 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, dl, MVT::i32));
1803       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1804                                   Mul1, DAG.getConstant(0, dl, MVT::i32));
1805       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1806                                      Addend0, DAG.getConstant(0, dl, MVT::i32));
1807       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1808                                      Addend1, DAG.getConstant(0, dl, 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         allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1822                                        ST->getAddressSpace(),
1823                                        ST->getAlignment()) ||
1824         ST->isVolatile() || ST->isIndexed()) {
1825       break;
1826     }
1827     SDValue Chain = ST->getChain();
1828
1829     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1830     if (StoreBits % 8) {
1831       break;
1832     }
1833     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1834         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1835     unsigned Alignment = ST->getAlignment();
1836     if (Alignment >= ABIAlignment) {
1837       break;
1838     }
1839
1840     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1841       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1842         LD->getAlignment() == Alignment &&
1843         !LD->isVolatile() && !LD->isIndexed() &&
1844         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1845         bool isTail = isInTailCallPosition(DAG, ST, Chain);
1846         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1847                               LD->getBasePtr(),
1848                               DAG.getConstant(StoreBits/8, dl, MVT::i32),
1849                               Alignment, false, isTail, ST->getPointerInfo(),
1850                               LD->getPointerInfo());
1851       }
1852     }
1853     break;
1854   }
1855   }
1856   return SDValue();
1857 }
1858
1859 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1860                                                         APInt &KnownZero,
1861                                                         APInt &KnownOne,
1862                                                         const SelectionDAG &DAG,
1863                                                         unsigned Depth) const {
1864   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1865   switch (Op.getOpcode()) {
1866   default: break;
1867   case XCoreISD::LADD:
1868   case XCoreISD::LSUB:
1869     if (Op.getResNo() == 1) {
1870       // Top bits of carry / borrow are clear.
1871       KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1872                                         KnownZero.getBitWidth() - 1);
1873     }
1874     break;
1875   case ISD::INTRINSIC_W_CHAIN:
1876     {
1877       unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1878       switch (IntNo) {
1879       case Intrinsic::xcore_getts:
1880         // High bits are known to be zero.
1881         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1882                                           KnownZero.getBitWidth() - 16);
1883         break;
1884       case Intrinsic::xcore_int:
1885       case Intrinsic::xcore_inct:
1886         // High bits are known to be zero.
1887         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1888                                           KnownZero.getBitWidth() - 8);
1889         break;
1890       case Intrinsic::xcore_testct:
1891         // Result is either 0 or 1.
1892         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1893                                           KnownZero.getBitWidth() - 1);
1894         break;
1895       case Intrinsic::xcore_testwct:
1896         // Result is in the range 0 - 4.
1897         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1898                                           KnownZero.getBitWidth() - 3);
1899         break;
1900       }
1901     }
1902     break;
1903   }
1904 }
1905
1906 //===----------------------------------------------------------------------===//
1907 //  Addressing mode description hooks
1908 //===----------------------------------------------------------------------===//
1909
1910 static inline bool isImmUs(int64_t val)
1911 {
1912   return (val >= 0 && val <= 11);
1913 }
1914
1915 static inline bool isImmUs2(int64_t val)
1916 {
1917   return (val%2 == 0 && isImmUs(val/2));
1918 }
1919
1920 static inline bool isImmUs4(int64_t val)
1921 {
1922   return (val%4 == 0 && isImmUs(val/4));
1923 }
1924
1925 /// isLegalAddressingMode - Return true if the addressing mode represented
1926 /// by AM is legal for this target, for a load/store of the specified type.
1927 bool
1928 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1929                                            Type *Ty,
1930                                            unsigned AS) const {
1931   if (Ty->getTypeID() == Type::VoidTyID)
1932     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1933
1934   const DataLayout *TD = TM.getDataLayout();
1935   unsigned Size = TD->getTypeAllocSize(Ty);
1936   if (AM.BaseGV) {
1937     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1938                  AM.BaseOffs%4 == 0;
1939   }
1940
1941   switch (Size) {
1942   case 1:
1943     // reg + imm
1944     if (AM.Scale == 0) {
1945       return isImmUs(AM.BaseOffs);
1946     }
1947     // reg + reg
1948     return AM.Scale == 1 && AM.BaseOffs == 0;
1949   case 2:
1950   case 3:
1951     // reg + imm
1952     if (AM.Scale == 0) {
1953       return isImmUs2(AM.BaseOffs);
1954     }
1955     // reg + reg<<1
1956     return AM.Scale == 2 && AM.BaseOffs == 0;
1957   default:
1958     // reg + imm
1959     if (AM.Scale == 0) {
1960       return isImmUs4(AM.BaseOffs);
1961     }
1962     // reg + reg<<2
1963     return AM.Scale == 4 && AM.BaseOffs == 0;
1964   }
1965 }
1966
1967 //===----------------------------------------------------------------------===//
1968 //                           XCore Inline Assembly Support
1969 //===----------------------------------------------------------------------===//
1970
1971 std::pair<unsigned, const TargetRegisterClass *>
1972 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1973                                                   StringRef Constraint,
1974                                                   MVT VT) const {
1975   if (Constraint.size() == 1) {
1976     switch (Constraint[0]) {
1977     default : break;
1978     case 'r':
1979       return std::make_pair(0U, &XCore::GRRegsRegClass);
1980     }
1981   }
1982   // Use the default implementation in TargetLowering to convert the register
1983   // constraint into a member of a register class.
1984   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1985 }