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