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