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