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