Make isLegalAddressingMode() taking DataLayout as an argument
[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(DAG.getDataLayout()), DL,
316                        DAG.getEntryNode(), CP, MachinePointerInfo(), false,
317                        false, false, 0);
318   }
319 }
320
321 SDValue XCoreTargetLowering::
322 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
323 {
324   SDLoc DL(Op);
325   auto PtrVT = getPointerTy(DAG.getDataLayout());
326   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
327   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
328
329   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, Result);
330 }
331
332 SDValue XCoreTargetLowering::
333 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
334 {
335   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
336   // FIXME there isn't really debug info here
337   SDLoc dl(CP);
338   EVT PtrVT = Op.getValueType();
339   SDValue Res;
340   if (CP->isMachineConstantPoolEntry()) {
341     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
342                                     CP->getAlignment(), CP->getOffset());
343   } else {
344     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
345                                     CP->getAlignment(), CP->getOffset());
346   }
347   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
348 }
349
350 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
351   return MachineJumpTableInfo::EK_Inline;
352 }
353
354 SDValue XCoreTargetLowering::
355 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
356 {
357   SDValue Chain = Op.getOperand(0);
358   SDValue Table = Op.getOperand(1);
359   SDValue Index = Op.getOperand(2);
360   SDLoc dl(Op);
361   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
362   unsigned JTI = JT->getIndex();
363   MachineFunction &MF = DAG.getMachineFunction();
364   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
365   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
366
367   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
368   if (NumEntries <= 32) {
369     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
370   }
371   assert((NumEntries >> 31) == 0);
372   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
373                                     DAG.getConstant(1, dl, MVT::i32));
374   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
375                      ScaledIndex);
376 }
377
378 SDValue XCoreTargetLowering::
379 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
380                                        int64_t Offset, SelectionDAG &DAG) const
381 {
382   auto PtrVT = getPointerTy(DAG.getDataLayout());
383   if ((Offset & 0x3) == 0) {
384     return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo(), false,
385                        false, false, 0);
386   }
387   // Lower to pair of consecutive word aligned loads plus some bit shifting.
388   int32_t HighOffset = RoundUpToAlignment(Offset, 4);
389   int32_t LowOffset = HighOffset - 4;
390   SDValue LowAddr, HighAddr;
391   if (GlobalAddressSDNode *GASD =
392         dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
393     LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
394                                    LowOffset);
395     HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
396                                     HighOffset);
397   } else {
398     LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
399                           DAG.getConstant(LowOffset, DL, MVT::i32));
400     HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
401                            DAG.getConstant(HighOffset, DL, MVT::i32));
402   }
403   SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
404   SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
405
406   SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo(),
407                             false, false, false, 0);
408   SDValue High = DAG.getLoad(PtrVT, DL, Chain, 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).setCallee(
499       CallingConv::C, IntPtrTy,
500       DAG.getExternalSymbol("__misaligned_load",
501                             getPointerTy(DAG.getDataLayout())),
502       std::move(Args), 0);
503
504   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
505   SDValue Ops[] = { CallResult.first, CallResult.second };
506   return DAG.getMergeValues(Ops, DL);
507 }
508
509 SDValue XCoreTargetLowering::
510 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
511 {
512   StoreSDNode *ST = cast<StoreSDNode>(Op);
513   assert(!ST->isTruncatingStore() && "Unexpected store type");
514   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
515   if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
516                                      ST->getAddressSpace(),
517                                      ST->getAlignment())) {
518     return SDValue();
519   }
520   unsigned ABIAlignment = getDataLayout()->
521     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
522   // Leave aligned store alone.
523   if (ST->getAlignment() >= ABIAlignment) {
524     return SDValue();
525   }
526   SDValue Chain = ST->getChain();
527   SDValue BasePtr = ST->getBasePtr();
528   SDValue Value = ST->getValue();
529   SDLoc dl(Op);
530
531   if (ST->getAlignment() == 2) {
532     SDValue Low = Value;
533     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
534                                       DAG.getConstant(16, dl, MVT::i32));
535     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
536                                          ST->getPointerInfo(), MVT::i16,
537                                          ST->isVolatile(), ST->isNonTemporal(),
538                                          2);
539     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
540                                    DAG.getConstant(2, dl, MVT::i32));
541     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
542                                           ST->getPointerInfo().getWithOffset(2),
543                                           MVT::i16, ST->isVolatile(),
544                                           ST->isNonTemporal(), 2);
545     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
546   }
547
548   // Lower to a call to __misaligned_store(BasePtr, Value).
549   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
550   TargetLowering::ArgListTy Args;
551   TargetLowering::ArgListEntry Entry;
552
553   Entry.Ty = IntPtrTy;
554   Entry.Node = BasePtr;
555   Args.push_back(Entry);
556
557   Entry.Node = Value;
558   Args.push_back(Entry);
559
560   TargetLowering::CallLoweringInfo CLI(DAG);
561   CLI.setDebugLoc(dl).setChain(Chain).setCallee(
562       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
563       DAG.getExternalSymbol("__misaligned_store",
564                             getPointerTy(DAG.getDataLayout())),
565       std::move(Args), 0);
566
567   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
568   return CallResult.second;
569 }
570
571 SDValue XCoreTargetLowering::
572 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
573 {
574   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
575          "Unexpected operand to lower!");
576   SDLoc dl(Op);
577   SDValue LHS = Op.getOperand(0);
578   SDValue RHS = Op.getOperand(1);
579   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
580   SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
581                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
582                            LHS, RHS);
583   SDValue Lo(Hi.getNode(), 1);
584   SDValue Ops[] = { Lo, Hi };
585   return DAG.getMergeValues(Ops, dl);
586 }
587
588 SDValue XCoreTargetLowering::
589 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
590 {
591   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
592          "Unexpected operand to lower!");
593   SDLoc dl(Op);
594   SDValue LHS = Op.getOperand(0);
595   SDValue RHS = Op.getOperand(1);
596   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
597   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
598                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
599                            Zero, Zero);
600   SDValue Lo(Hi.getNode(), 1);
601   SDValue Ops[] = { Lo, Hi };
602   return DAG.getMergeValues(Ops, dl);
603 }
604
605 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
606 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
607 /// each intermediate result in the calculation must also have a single use.
608 /// If the Op is in the correct form the constituent parts are written to Mul0,
609 /// Mul1, Addend0 and Addend1.
610 static bool
611 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
612             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
613 {
614   if (Op.getOpcode() != ISD::ADD)
615     return false;
616   SDValue N0 = Op.getOperand(0);
617   SDValue N1 = Op.getOperand(1);
618   SDValue AddOp;
619   SDValue OtherOp;
620   if (N0.getOpcode() == ISD::ADD) {
621     AddOp = N0;
622     OtherOp = N1;
623   } else if (N1.getOpcode() == ISD::ADD) {
624     AddOp = N1;
625     OtherOp = N0;
626   } else {
627     return false;
628   }
629   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
630     return false;
631   if (OtherOp.getOpcode() == ISD::MUL) {
632     // add(add(a,b),mul(x,y))
633     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
634       return false;
635     Mul0 = OtherOp.getOperand(0);
636     Mul1 = OtherOp.getOperand(1);
637     Addend0 = AddOp.getOperand(0);
638     Addend1 = AddOp.getOperand(1);
639     return true;
640   }
641   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
642     // add(add(mul(x,y),a),b)
643     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
644       return false;
645     Mul0 = AddOp.getOperand(0).getOperand(0);
646     Mul1 = AddOp.getOperand(0).getOperand(1);
647     Addend0 = AddOp.getOperand(1);
648     Addend1 = OtherOp;
649     return true;
650   }
651   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
652     // add(add(a,mul(x,y)),b)
653     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
654       return false;
655     Mul0 = AddOp.getOperand(1).getOperand(0);
656     Mul1 = AddOp.getOperand(1).getOperand(1);
657     Addend0 = AddOp.getOperand(0);
658     Addend1 = OtherOp;
659     return true;
660   }
661   return false;
662 }
663
664 SDValue XCoreTargetLowering::
665 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
666 {
667   SDValue Mul;
668   SDValue Other;
669   if (N->getOperand(0).getOpcode() == ISD::MUL) {
670     Mul = N->getOperand(0);
671     Other = N->getOperand(1);
672   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
673     Mul = N->getOperand(1);
674     Other = N->getOperand(0);
675   } else {
676     return SDValue();
677   }
678   SDLoc dl(N);
679   SDValue LL, RL, AddendL, AddendH;
680   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
681                    Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
682   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
683                    Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
684   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685                         Other, DAG.getConstant(0, dl, MVT::i32));
686   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687                         Other, DAG.getConstant(1, dl, MVT::i32));
688   APInt HighMask = APInt::getHighBitsSet(64, 32);
689   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
690   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
691   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
692       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
693     // The inputs are both zero-extended.
694     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
695                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
696                              AddendL, LL, RL);
697     SDValue Lo(Hi.getNode(), 1);
698     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
699   }
700   if (LHSSB > 32 && RHSSB > 32) {
701     // The inputs are both sign-extended.
702     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
703                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
704                              AddendL, LL, RL);
705     SDValue Lo(Hi.getNode(), 1);
706     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
707   }
708   SDValue LH, RH;
709   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
710                    Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
711   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
712                    Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
713   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
714                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
715                            AddendL, LL, RL);
716   SDValue Lo(Hi.getNode(), 1);
717   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
718   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
719   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
720   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
721   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
722 }
723
724 SDValue XCoreTargetLowering::
725 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
726 {
727   assert(N->getValueType(0) == MVT::i64 &&
728          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
729         "Unknown operand to lower!");
730
731   if (N->getOpcode() == ISD::ADD) {
732     SDValue Result = TryExpandADDWithMul(N, DAG);
733     if (Result.getNode())
734       return Result;
735   }
736
737   SDLoc dl(N);
738
739   // Extract components
740   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
741                              N->getOperand(0),
742                              DAG.getConstant(0, dl, MVT::i32));
743   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
744                              N->getOperand(0),
745                              DAG.getConstant(1, dl, MVT::i32));
746   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747                              N->getOperand(1),
748                              DAG.getConstant(0, dl, MVT::i32));
749   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
750                              N->getOperand(1),
751                              DAG.getConstant(1, dl, MVT::i32));
752
753   // Expand
754   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
755                                                    XCoreISD::LSUB;
756   SDValue Zero = DAG.getConstant(0, dl, 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                                                       dl));
787   // Store the incremented VAList to the legalized pointer
788   InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
789                          MachinePointerInfo(SV), false, false, 0);
790   // Load the actual argument out of the pointer VAList
791   return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
792                      false, false, false, 0);
793 }
794
795 SDValue XCoreTargetLowering::
796 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
797 {
798   SDLoc dl(Op);
799   // vastart stores the address of the VarArgsFrameIndex slot into the
800   // memory location argument
801   MachineFunction &MF = DAG.getMachineFunction();
802   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
803   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
804   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
805                       MachinePointerInfo(), false, false, 0);
806 }
807
808 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
809                                             SelectionDAG &DAG) const {
810   // This nodes represent llvm.frameaddress on the DAG.
811   // It takes one operand, the index of the frame address to return.
812   // An index of zero corresponds to the current function's frame address.
813   // An index of one to the parent's frame address, and so on.
814   // Depths > 0 not supported yet!
815   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
816     return SDValue();
817
818   MachineFunction &MF = DAG.getMachineFunction();
819   const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
820   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
821                             RegInfo->getFrameRegister(MF), MVT::i32);
822 }
823
824 SDValue XCoreTargetLowering::
825 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
826   // This nodes represent llvm.returnaddress on the DAG.
827   // It takes one operand, the index of the return address to return.
828   // An index of zero corresponds to the current function's return address.
829   // An index of one to the parent's return address, and so on.
830   // Depths > 0 not supported yet!
831   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
832     return SDValue();
833
834   MachineFunction &MF = DAG.getMachineFunction();
835   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
836   int FI = XFI->createLRSpillSlot(MF);
837   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
838   return DAG.getLoad(
839       getPointerTy(DAG.getDataLayout()), SDLoc(Op), DAG.getEntryNode(), FIN,
840       MachinePointerInfo::getFixedStack(FI), false, false, false, 0);
841 }
842
843 SDValue XCoreTargetLowering::
844 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
845   // This node represents offset from frame pointer to first on-stack argument.
846   // This is needed for correct stack adjustment during unwind.
847   // However, we don't know the offset until after the frame has be finalised.
848   // This is done during the XCoreFTAOElim pass.
849   return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
850 }
851
852 SDValue XCoreTargetLowering::
853 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
854   // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
855   // This node represents 'eh_return' gcc dwarf builtin, which is used to
856   // return from exception. The general meaning is: adjust stack by OFFSET and
857   // pass execution to HANDLER.
858   MachineFunction &MF = DAG.getMachineFunction();
859   SDValue Chain     = Op.getOperand(0);
860   SDValue Offset    = Op.getOperand(1);
861   SDValue Handler   = Op.getOperand(2);
862   SDLoc dl(Op);
863
864   // Absolute SP = (FP + FrameToArgs) + Offset
865   const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
866   SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
867                             RegInfo->getFrameRegister(MF), MVT::i32);
868   SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
869                                     MVT::i32);
870   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
871   Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
872
873   // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
874   // which leaves 2 caller saved registers, R2 & R3 for us to use.
875   unsigned StackReg = XCore::R2;
876   unsigned HandlerReg = XCore::R3;
877
878   SDValue OutChains[] = {
879     DAG.getCopyToReg(Chain, dl, StackReg, Stack),
880     DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
881   };
882
883   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
884
885   return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
886                      DAG.getRegister(StackReg, MVT::i32),
887                      DAG.getRegister(HandlerReg, MVT::i32));
888
889 }
890
891 SDValue XCoreTargetLowering::
892 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
893   return Op.getOperand(0);
894 }
895
896 SDValue XCoreTargetLowering::
897 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
898   SDValue Chain = Op.getOperand(0);
899   SDValue Trmp = Op.getOperand(1); // trampoline
900   SDValue FPtr = Op.getOperand(2); // nested function
901   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
902
903   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
904
905   // .align 4
906   // LDAPF_u10 r11, nest
907   // LDW_2rus r11, r11[0]
908   // STWSP_ru6 r11, sp[0]
909   // LDAPF_u10 r11, fptr
910   // LDW_2rus r11, r11[0]
911   // BAU_1r r11
912   // nest:
913   // .word nest
914   // fptr:
915   // .word fptr
916   SDValue OutChains[5];
917
918   SDValue Addr = Trmp;
919
920   SDLoc dl(Op);
921   OutChains[0] = DAG.getStore(Chain, dl,
922                               DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
923                               MachinePointerInfo(TrmpAddr), false, false, 0);
924
925   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
926                      DAG.getConstant(4, dl, MVT::i32));
927   OutChains[1] = DAG.getStore(Chain, dl,
928                               DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
929                               MachinePointerInfo(TrmpAddr, 4), false, false, 0);
930
931   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
932                      DAG.getConstant(8, dl, MVT::i32));
933   OutChains[2] = DAG.getStore(Chain, dl,
934                               DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
935                               MachinePointerInfo(TrmpAddr, 8), false, false, 0);
936
937   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
938                      DAG.getConstant(12, dl, MVT::i32));
939   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
940                               MachinePointerInfo(TrmpAddr, 12), false, false,
941                               0);
942
943   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
944                      DAG.getConstant(16, dl, MVT::i32));
945   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
946                               MachinePointerInfo(TrmpAddr, 16), false, false,
947                               0);
948
949   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
950 }
951
952 SDValue XCoreTargetLowering::
953 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
954   SDLoc DL(Op);
955   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
956   switch (IntNo) {
957     case Intrinsic::xcore_crc8:
958       EVT VT = Op.getValueType();
959       SDValue Data =
960         DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
961                     Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
962       SDValue Crc(Data.getNode(), 1);
963       SDValue Results[] = { Crc, Data };
964       return DAG.getMergeValues(Results, DL);
965   }
966   return SDValue();
967 }
968
969 SDValue XCoreTargetLowering::
970 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
971   SDLoc DL(Op);
972   return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
973 }
974
975 SDValue XCoreTargetLowering::
976 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
977   AtomicSDNode *N = cast<AtomicSDNode>(Op);
978   assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
979   assert(N->getOrdering() <= Monotonic &&
980          "setInsertFencesForAtomic(true) and yet greater than Monotonic");
981   if (N->getMemoryVT() == MVT::i32) {
982     if (N->getAlignment() < 4)
983       report_fatal_error("atomic load must be aligned");
984     return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
985                        N->getChain(), N->getBasePtr(), N->getPointerInfo(),
986                        N->isVolatile(), N->isNonTemporal(), N->isInvariant(),
987                        N->getAlignment(), N->getAAInfo(), 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->isInvariant(), N->getAlignment(), N->getAAInfo());
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->isInvariant(), N->getAlignment(), N->getAAInfo());
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->getAAInfo());
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->getAAInfo());
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->getAAInfo());
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, dl, 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(), ArgLocs,
1137                  *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(), RVLocs,
1148                     *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   auto PtrVT = getPointerTy(DAG.getDataLayout());
1155
1156   Chain = DAG.getCALLSEQ_START(Chain,
1157                                DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1158
1159   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1160   SmallVector<SDValue, 12> MemOpChains;
1161
1162   // Walk the register/memloc assignments, inserting copies/loads.
1163   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1164     CCValAssign &VA = ArgLocs[i];
1165     SDValue Arg = OutVals[i];
1166
1167     // Promote the value if needed.
1168     switch (VA.getLocInfo()) {
1169       default: llvm_unreachable("Unknown loc info!");
1170       case CCValAssign::Full: break;
1171       case CCValAssign::SExt:
1172         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1173         break;
1174       case CCValAssign::ZExt:
1175         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1176         break;
1177       case CCValAssign::AExt:
1178         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1179         break;
1180     }
1181
1182     // Arguments that can be passed on register must be kept at
1183     // RegsToPass vector
1184     if (VA.isRegLoc()) {
1185       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1186     } else {
1187       assert(VA.isMemLoc());
1188
1189       int Offset = VA.getLocMemOffset();
1190
1191       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1192                                         Chain, Arg,
1193                                         DAG.getConstant(Offset/4, dl,
1194                                                         MVT::i32)));
1195     }
1196   }
1197
1198   // Transform all store nodes into one single node because
1199   // all store nodes are independent of each other.
1200   if (!MemOpChains.empty())
1201     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1202
1203   // Build a sequence of copy-to-reg nodes chained together with token
1204   // chain and flag operands which copy the outgoing args into registers.
1205   // The InFlag in necessary since all emitted instructions must be
1206   // stuck together.
1207   SDValue InFlag;
1208   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1209     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1210                              RegsToPass[i].second, InFlag);
1211     InFlag = Chain.getValue(1);
1212   }
1213
1214   // If the callee is a GlobalAddress node (quite common, every direct call is)
1215   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1216   // Likewise ExternalSymbol -> TargetExternalSymbol.
1217   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1218     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1219   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1220     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1221
1222   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1223   //             = Chain, Callee, Reg#1, Reg#2, ...
1224   //
1225   // Returns a chain & a flag for retval copy to use.
1226   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1227   SmallVector<SDValue, 8> Ops;
1228   Ops.push_back(Chain);
1229   Ops.push_back(Callee);
1230
1231   // Add argument registers to the end of the list so that they are
1232   // known live into the call.
1233   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1234     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1235                                   RegsToPass[i].second.getValueType()));
1236
1237   if (InFlag.getNode())
1238     Ops.push_back(InFlag);
1239
1240   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1241   InFlag = Chain.getValue(1);
1242
1243   // Create the CALLSEQ_END node.
1244   Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1245                              DAG.getConstant(0, dl, PtrVT, true), 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(), ArgLocs,
1303                  *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     if (FirstVAReg < array_lengthof(ArgRegs)) {
1384       int offset = 0;
1385       // Save remaining registers, storing higher register numbers at a higher
1386       // address
1387       for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1388         // Create a stack slot
1389         int FI = MFI->CreateFixedObject(4, offset, true);
1390         if (i == (int)FirstVAReg) {
1391           XFI->setVarArgsFrameIndex(FI);
1392         }
1393         offset -= StackSlotSize;
1394         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1395         // Move argument from phys reg -> virt reg
1396         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1397         RegInfo.addLiveIn(ArgRegs[i], VReg);
1398         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1399         CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1400         // Move argument from virt reg -> stack
1401         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1402                                      MachinePointerInfo(), false, false, 0);
1403         MemOps.push_back(Store);
1404       }
1405     } else {
1406       // This will point to the next argument passed via stack.
1407       XFI->setVarArgsFrameIndex(
1408         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1409                                true));
1410     }
1411   }
1412
1413   // 2. chain CopyFromReg nodes into a TokenFactor.
1414   if (!CFRegNode.empty())
1415     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1416
1417   // 3. Memcpy 'byVal' args & push final InVals.
1418   // Aggregates passed "byVal" need to be copied by the callee.
1419   // The callee will use a pointer to this copy, rather than the original
1420   // pointer.
1421   for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1422                                                     ArgDE = ArgData.end();
1423        ArgDI != ArgDE; ++ArgDI) {
1424     if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1425       unsigned Size = ArgDI->Flags.getByValSize();
1426       unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1427       // Create a new object on the stack and copy the pointee into it.
1428       int FI = MFI->CreateStackObject(Size, Align, false);
1429       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1430       InVals.push_back(FIN);
1431       MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1432                                      DAG.getConstant(Size, dl, MVT::i32),
1433                                      Align, false, false, false,
1434                                      MachinePointerInfo(),
1435                                      MachinePointerInfo()));
1436     } else {
1437       InVals.push_back(ArgDI->SDV);
1438     }
1439   }
1440
1441   // 4, chain mem ops nodes into a TokenFactor.
1442   if (!MemOps.empty()) {
1443     MemOps.push_back(Chain);
1444     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1445   }
1446
1447   return Chain;
1448 }
1449
1450 //===----------------------------------------------------------------------===//
1451 //               Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1453
1454 bool XCoreTargetLowering::
1455 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1456                bool isVarArg,
1457                const SmallVectorImpl<ISD::OutputArg> &Outs,
1458                LLVMContext &Context) const {
1459   SmallVector<CCValAssign, 16> RVLocs;
1460   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1461   if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1462     return false;
1463   if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1464     return false;
1465   return true;
1466 }
1467
1468 SDValue
1469 XCoreTargetLowering::LowerReturn(SDValue Chain,
1470                                  CallingConv::ID CallConv, bool isVarArg,
1471                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1472                                  const SmallVectorImpl<SDValue> &OutVals,
1473                                  SDLoc dl, SelectionDAG &DAG) const {
1474
1475   XCoreFunctionInfo *XFI =
1476     DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1477   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1478
1479   // CCValAssign - represent the assignment of
1480   // the return value to a location
1481   SmallVector<CCValAssign, 16> RVLocs;
1482
1483   // CCState - Info about the registers and stack slot.
1484   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1485                  *DAG.getContext());
1486
1487   // Analyze return values.
1488   if (!isVarArg)
1489     CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1490
1491   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1492
1493   SDValue Flag;
1494   SmallVector<SDValue, 4> RetOps(1, Chain);
1495
1496   // Return on XCore is always a "retsp 0"
1497   RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1498
1499   SmallVector<SDValue, 4> MemOpChains;
1500   // Handle return values that must be copied to memory.
1501   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1502     CCValAssign &VA = RVLocs[i];
1503     if (VA.isRegLoc())
1504       continue;
1505     assert(VA.isMemLoc());
1506     if (isVarArg) {
1507       report_fatal_error("Can't return value from vararg function in memory");
1508     }
1509
1510     int Offset = VA.getLocMemOffset();
1511     unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1512     // Create the frame index object for the memory location.
1513     int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1514
1515     // Create a SelectionDAG node corresponding to a store
1516     // to this memory location.
1517     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1518     MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1519                           MachinePointerInfo::getFixedStack(FI), false, false,
1520                           0));
1521   }
1522
1523   // Transform all store nodes into one single node because
1524   // all stores are independent of each other.
1525   if (!MemOpChains.empty())
1526     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1527
1528   // Now handle return values copied to registers.
1529   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1530     CCValAssign &VA = RVLocs[i];
1531     if (!VA.isRegLoc())
1532       continue;
1533     // Copy the result values into the output registers.
1534     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1535
1536     // guarantee that all emitted copies are
1537     // stuck together, avoiding something bad
1538     Flag = Chain.getValue(1);
1539     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1540   }
1541
1542   RetOps[0] = Chain;  // Update chain.
1543
1544   // Add the flag if we have it.
1545   if (Flag.getNode())
1546     RetOps.push_back(Flag);
1547
1548   return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1549 }
1550
1551 //===----------------------------------------------------------------------===//
1552 //  Other Lowering Code
1553 //===----------------------------------------------------------------------===//
1554
1555 MachineBasicBlock *
1556 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1557                                                  MachineBasicBlock *BB) const {
1558   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1559   DebugLoc dl = MI->getDebugLoc();
1560   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1561          "Unexpected instr type to insert");
1562
1563   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1564   // control-flow pattern.  The incoming instruction knows the destination vreg
1565   // to set, the condition code register to branch on, the true/false values to
1566   // select between, and a branch opcode to use.
1567   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1568   MachineFunction::iterator It = BB;
1569   ++It;
1570
1571   //  thisMBB:
1572   //  ...
1573   //   TrueVal = ...
1574   //   cmpTY ccX, r1, r2
1575   //   bCC copy1MBB
1576   //   fallthrough --> copy0MBB
1577   MachineBasicBlock *thisMBB = BB;
1578   MachineFunction *F = BB->getParent();
1579   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1580   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1581   F->insert(It, copy0MBB);
1582   F->insert(It, sinkMBB);
1583
1584   // Transfer the remainder of BB and its successor edges to sinkMBB.
1585   sinkMBB->splice(sinkMBB->begin(), BB,
1586                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1587   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1588
1589   // Next, add the true and fallthrough blocks as its successors.
1590   BB->addSuccessor(copy0MBB);
1591   BB->addSuccessor(sinkMBB);
1592
1593   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1594     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1595
1596   //  copy0MBB:
1597   //   %FalseValue = ...
1598   //   # fallthrough to sinkMBB
1599   BB = copy0MBB;
1600
1601   // Update machine-CFG edges
1602   BB->addSuccessor(sinkMBB);
1603
1604   //  sinkMBB:
1605   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1606   //  ...
1607   BB = sinkMBB;
1608   BuildMI(*BB, BB->begin(), dl,
1609           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1610     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1611     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1612
1613   MI->eraseFromParent();   // The pseudo instruction is gone now.
1614   return BB;
1615 }
1616
1617 //===----------------------------------------------------------------------===//
1618 // Target Optimization Hooks
1619 //===----------------------------------------------------------------------===//
1620
1621 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1622                                              DAGCombinerInfo &DCI) const {
1623   SelectionDAG &DAG = DCI.DAG;
1624   SDLoc dl(N);
1625   switch (N->getOpcode()) {
1626   default: break;
1627   case ISD::INTRINSIC_VOID:
1628     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1629     case Intrinsic::xcore_outt:
1630     case Intrinsic::xcore_outct:
1631     case Intrinsic::xcore_chkct: {
1632       SDValue OutVal = N->getOperand(3);
1633       // These instructions ignore the high bits.
1634       if (OutVal.hasOneUse()) {
1635         unsigned BitWidth = OutVal.getValueSizeInBits();
1636         APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1637         APInt KnownZero, KnownOne;
1638         TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1639                                               !DCI.isBeforeLegalizeOps());
1640         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1641         if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1642             TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1643                                      TLO))
1644           DCI.CommitTargetLoweringOpt(TLO);
1645       }
1646       break;
1647     }
1648     case Intrinsic::xcore_setpt: {
1649       SDValue Time = N->getOperand(3);
1650       // This instruction ignores the high bits.
1651       if (Time.hasOneUse()) {
1652         unsigned BitWidth = Time.getValueSizeInBits();
1653         APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1654         APInt KnownZero, KnownOne;
1655         TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1656                                               !DCI.isBeforeLegalizeOps());
1657         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1658         if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1659             TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1660                                      TLO))
1661           DCI.CommitTargetLoweringOpt(TLO);
1662       }
1663       break;
1664     }
1665     }
1666     break;
1667   case XCoreISD::LADD: {
1668     SDValue N0 = N->getOperand(0);
1669     SDValue N1 = N->getOperand(1);
1670     SDValue N2 = N->getOperand(2);
1671     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1672     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1673     EVT VT = N0.getValueType();
1674
1675     // canonicalize constant to RHS
1676     if (N0C && !N1C)
1677       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1678
1679     // fold (ladd 0, 0, x) -> 0, x & 1
1680     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1681       SDValue Carry = DAG.getConstant(0, dl, VT);
1682       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1683                                    DAG.getConstant(1, dl, VT));
1684       SDValue Ops[] = { Result, Carry };
1685       return DAG.getMergeValues(Ops, dl);
1686     }
1687
1688     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1689     // low bit set
1690     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1691       APInt KnownZero, KnownOne;
1692       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1693                                          VT.getSizeInBits() - 1);
1694       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1695       if ((KnownZero & Mask) == Mask) {
1696         SDValue Carry = DAG.getConstant(0, dl, VT);
1697         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1698         SDValue Ops[] = { Result, Carry };
1699         return DAG.getMergeValues(Ops, dl);
1700       }
1701     }
1702   }
1703   break;
1704   case XCoreISD::LSUB: {
1705     SDValue N0 = N->getOperand(0);
1706     SDValue N1 = N->getOperand(1);
1707     SDValue N2 = N->getOperand(2);
1708     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1709     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1710     EVT VT = N0.getValueType();
1711
1712     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1713     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1714       APInt KnownZero, KnownOne;
1715       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1716                                          VT.getSizeInBits() - 1);
1717       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1718       if ((KnownZero & Mask) == Mask) {
1719         SDValue Borrow = N2;
1720         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1721                                      DAG.getConstant(0, dl, VT), N2);
1722         SDValue Ops[] = { Result, Borrow };
1723         return DAG.getMergeValues(Ops, dl);
1724       }
1725     }
1726
1727     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1728     // low bit set
1729     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1730       APInt KnownZero, KnownOne;
1731       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1732                                          VT.getSizeInBits() - 1);
1733       DAG.computeKnownBits(N2, KnownZero, KnownOne);
1734       if ((KnownZero & Mask) == Mask) {
1735         SDValue Borrow = DAG.getConstant(0, dl, VT);
1736         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1737         SDValue Ops[] = { Result, Borrow };
1738         return DAG.getMergeValues(Ops, dl);
1739       }
1740     }
1741   }
1742   break;
1743   case XCoreISD::LMUL: {
1744     SDValue N0 = N->getOperand(0);
1745     SDValue N1 = N->getOperand(1);
1746     SDValue N2 = N->getOperand(2);
1747     SDValue N3 = N->getOperand(3);
1748     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1749     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1750     EVT VT = N0.getValueType();
1751     // Canonicalize multiplicative constant to RHS. If both multiplicative
1752     // operands are constant canonicalize smallest to RHS.
1753     if ((N0C && !N1C) ||
1754         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1755       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1756                          N1, N0, N2, N3);
1757
1758     // lmul(x, 0, a, b)
1759     if (N1C && N1C->isNullValue()) {
1760       // If the high result is unused fold to add(a, b)
1761       if (N->hasNUsesOfValue(0, 0)) {
1762         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1763         SDValue Ops[] = { Lo, Lo };
1764         return DAG.getMergeValues(Ops, dl);
1765       }
1766       // Otherwise fold to ladd(a, b, 0)
1767       SDValue Result =
1768         DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1769       SDValue Carry(Result.getNode(), 1);
1770       SDValue Ops[] = { Carry, Result };
1771       return DAG.getMergeValues(Ops, dl);
1772     }
1773   }
1774   break;
1775   case ISD::ADD: {
1776     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1777     // lmul(x, y, a, b). The high result of lmul will be ignored.
1778     // This is only profitable if the intermediate results are unused
1779     // elsewhere.
1780     SDValue Mul0, Mul1, Addend0, Addend1;
1781     if (N->getValueType(0) == MVT::i32 &&
1782         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1783       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1784                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1785                                     Mul1, Addend0, Addend1);
1786       SDValue Result(Ignored.getNode(), 1);
1787       return Result;
1788     }
1789     APInt HighMask = APInt::getHighBitsSet(64, 32);
1790     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1791     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1792     // before type legalization as it is messy to match the operands after
1793     // that.
1794     if (N->getValueType(0) == MVT::i64 &&
1795         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1796         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1797         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1798         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1799         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1800       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1801                                   Mul0, DAG.getConstant(0, dl, MVT::i32));
1802       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1803                                   Mul1, DAG.getConstant(0, dl, MVT::i32));
1804       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1805                                      Addend0, DAG.getConstant(0, dl, MVT::i32));
1806       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1807                                      Addend1, DAG.getConstant(0, dl, MVT::i32));
1808       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1809                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1810                                Addend0L, Addend1L);
1811       SDValue Lo(Hi.getNode(), 1);
1812       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1813     }
1814   }
1815   break;
1816   case ISD::STORE: {
1817     // Replace unaligned store of unaligned load with memmove.
1818     StoreSDNode *ST  = cast<StoreSDNode>(N);
1819     if (!DCI.isBeforeLegalize() ||
1820         allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1821                                        ST->getAddressSpace(),
1822                                        ST->getAlignment()) ||
1823         ST->isVolatile() || ST->isIndexed()) {
1824       break;
1825     }
1826     SDValue Chain = ST->getChain();
1827
1828     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1829     if (StoreBits % 8) {
1830       break;
1831     }
1832     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1833         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1834     unsigned Alignment = ST->getAlignment();
1835     if (Alignment >= ABIAlignment) {
1836       break;
1837     }
1838
1839     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1840       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1841         LD->getAlignment() == Alignment &&
1842         !LD->isVolatile() && !LD->isIndexed() &&
1843         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1844         bool isTail = isInTailCallPosition(DAG, ST, Chain);
1845         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1846                               LD->getBasePtr(),
1847                               DAG.getConstant(StoreBits/8, dl, MVT::i32),
1848                               Alignment, false, isTail, ST->getPointerInfo(),
1849                               LD->getPointerInfo());
1850       }
1851     }
1852     break;
1853   }
1854   }
1855   return SDValue();
1856 }
1857
1858 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1859                                                         APInt &KnownZero,
1860                                                         APInt &KnownOne,
1861                                                         const SelectionDAG &DAG,
1862                                                         unsigned Depth) const {
1863   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1864   switch (Op.getOpcode()) {
1865   default: break;
1866   case XCoreISD::LADD:
1867   case XCoreISD::LSUB:
1868     if (Op.getResNo() == 1) {
1869       // Top bits of carry / borrow are clear.
1870       KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1871                                         KnownZero.getBitWidth() - 1);
1872     }
1873     break;
1874   case ISD::INTRINSIC_W_CHAIN:
1875     {
1876       unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1877       switch (IntNo) {
1878       case Intrinsic::xcore_getts:
1879         // High bits are known to be zero.
1880         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1881                                           KnownZero.getBitWidth() - 16);
1882         break;
1883       case Intrinsic::xcore_int:
1884       case Intrinsic::xcore_inct:
1885         // High bits are known to be zero.
1886         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1887                                           KnownZero.getBitWidth() - 8);
1888         break;
1889       case Intrinsic::xcore_testct:
1890         // Result is either 0 or 1.
1891         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1892                                           KnownZero.getBitWidth() - 1);
1893         break;
1894       case Intrinsic::xcore_testwct:
1895         // Result is in the range 0 - 4.
1896         KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1897                                           KnownZero.getBitWidth() - 3);
1898         break;
1899       }
1900     }
1901     break;
1902   }
1903 }
1904
1905 //===----------------------------------------------------------------------===//
1906 //  Addressing mode description hooks
1907 //===----------------------------------------------------------------------===//
1908
1909 static inline bool isImmUs(int64_t val)
1910 {
1911   return (val >= 0 && val <= 11);
1912 }
1913
1914 static inline bool isImmUs2(int64_t val)
1915 {
1916   return (val%2 == 0 && isImmUs(val/2));
1917 }
1918
1919 static inline bool isImmUs4(int64_t val)
1920 {
1921   return (val%4 == 0 && isImmUs(val/4));
1922 }
1923
1924 /// isLegalAddressingMode - Return true if the addressing mode represented
1925 /// by AM is legal for this target, for a load/store of the specified type.
1926 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1927                                                 const AddrMode &AM, Type *Ty,
1928                                                 unsigned AS) const {
1929   if (Ty->getTypeID() == Type::VoidTyID)
1930     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1931
1932   unsigned Size = DL.getTypeAllocSize(Ty);
1933   if (AM.BaseGV) {
1934     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1935                  AM.BaseOffs%4 == 0;
1936   }
1937
1938   switch (Size) {
1939   case 1:
1940     // reg + imm
1941     if (AM.Scale == 0) {
1942       return isImmUs(AM.BaseOffs);
1943     }
1944     // reg + reg
1945     return AM.Scale == 1 && AM.BaseOffs == 0;
1946   case 2:
1947   case 3:
1948     // reg + imm
1949     if (AM.Scale == 0) {
1950       return isImmUs2(AM.BaseOffs);
1951     }
1952     // reg + reg<<1
1953     return AM.Scale == 2 && AM.BaseOffs == 0;
1954   default:
1955     // reg + imm
1956     if (AM.Scale == 0) {
1957       return isImmUs4(AM.BaseOffs);
1958     }
1959     // reg + reg<<2
1960     return AM.Scale == 4 && AM.BaseOffs == 0;
1961   }
1962 }
1963
1964 //===----------------------------------------------------------------------===//
1965 //                           XCore Inline Assembly Support
1966 //===----------------------------------------------------------------------===//
1967
1968 std::pair<unsigned, const TargetRegisterClass *>
1969 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1970                                                   StringRef Constraint,
1971                                                   MVT VT) const {
1972   if (Constraint.size() == 1) {
1973     switch (Constraint[0]) {
1974     default : break;
1975     case 'r':
1976       return std::make_pair(0U, &XCore::GRRegsRegClass);
1977     }
1978   }
1979   // Use the default implementation in TargetLowering to convert the register
1980   // constraint into a member of a register class.
1981   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1982 }