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