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