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