XCore target: Lower FRAME_TO_ARGS_OFFSET
[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 #define DEBUG_TYPE "xcore-lower"
15
16 #include "XCoreISelLowering.h"
17 #include "XCore.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreTargetObjectFile.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41
42 using namespace llvm;
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::STWSP             : return "XCoreISD::STWSP";
54     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
55     case XCoreISD::LADD              : return "XCoreISD::LADD";
56     case XCoreISD::LSUB              : return "XCoreISD::LSUB";
57     case XCoreISD::LMUL              : return "XCoreISD::LMUL";
58     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
59     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
60     case XCoreISD::CRC8              : return "XCoreISD::CRC8";
61     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
62     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
63     case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
64     case XCoreISD::MEMBARRIER        : return "XCoreISD::MEMBARRIER";
65     default                          : return NULL;
66   }
67 }
68
69 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
70   : TargetLowering(XTM, new XCoreTargetObjectFile()),
71     TM(XTM),
72     Subtarget(*XTM.getSubtargetImpl()) {
73
74   // Set up the register classes.
75   addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
76
77   // Compute derived properties from the register classes
78   computeRegisterProperties();
79
80   // Division is expensive
81   setIntDivIsCheap(false);
82
83   setStackPointerRegisterToSaveRestore(XCore::SP);
84
85   setSchedulingPreference(Sched::Source);
86
87   // Use i32 for setcc operations results (slt, sgt, ...).
88   setBooleanContents(ZeroOrOneBooleanContent);
89   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
90
91   // XCore does not have the NodeTypes below.
92   setOperationAction(ISD::BR_CC,     MVT::i32,   Expand);
93   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
94   setOperationAction(ISD::ADDC, MVT::i32, Expand);
95   setOperationAction(ISD::ADDE, MVT::i32, Expand);
96   setOperationAction(ISD::SUBC, MVT::i32, Expand);
97   setOperationAction(ISD::SUBE, MVT::i32, Expand);
98
99   // Stop the combiner recombining select and set_cc
100   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
101
102   // 64bit
103   setOperationAction(ISD::ADD, MVT::i64, Custom);
104   setOperationAction(ISD::SUB, MVT::i64, Custom);
105   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
106   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
107   setOperationAction(ISD::MULHS, MVT::i32, Expand);
108   setOperationAction(ISD::MULHU, MVT::i32, Expand);
109   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
110   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
111   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
112
113   // Bit Manipulation
114   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
115   setOperationAction(ISD::ROTL , MVT::i32, Expand);
116   setOperationAction(ISD::ROTR , MVT::i32, Expand);
117   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
118   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
119
120   setOperationAction(ISD::TRAP, MVT::Other, Legal);
121
122   // Jump tables.
123   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
124
125   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
126   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
127
128   // Conversion of i64 -> double produces constantpool nodes
129   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
130
131   // Loads
132   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
133   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
134   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135
136   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
137   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
138
139   // Custom expand misaligned loads / stores.
140   setOperationAction(ISD::LOAD, MVT::i32, Custom);
141   setOperationAction(ISD::STORE, MVT::i32, Custom);
142
143   // Varargs
144   setOperationAction(ISD::VAEND, MVT::Other, Expand);
145   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
146   setOperationAction(ISD::VAARG, MVT::Other, Custom);
147   setOperationAction(ISD::VASTART, MVT::Other, Custom);
148
149   // Dynamic stack
150   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
151   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
152   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
153
154   // Exception handling
155   setExceptionPointerRegister(XCore::R0);
156   setExceptionSelectorRegister(XCore::R1);
157   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
158
159   // Atomic operations
160   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
161
162   // TRAMPOLINE is custom lowered.
163   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
164   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
165
166   // We want to custom lower some of our intrinsics.
167   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
168
169   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
170   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
171     = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
172
173   // We have target-specific dag combine patterns for the following nodes:
174   setTargetDAGCombine(ISD::STORE);
175   setTargetDAGCombine(ISD::ADD);
176
177   setMinFunctionAlignment(1);
178 }
179
180 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
181   if (Val.getOpcode() != ISD::LOAD)
182     return false;
183
184   EVT VT1 = Val.getValueType();
185   if (!VT1.isSimple() || !VT1.isInteger() ||
186       !VT2.isSimple() || !VT2.isInteger())
187     return false;
188
189   switch (VT1.getSimpleVT().SimpleTy) {
190   default: break;
191   case MVT::i8:
192     return true;
193   }
194
195   return false;
196 }
197
198 SDValue XCoreTargetLowering::
199 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
200   switch (Op.getOpcode())
201   {
202   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
203   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
204   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
205   case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
206   case ISD::LOAD:               return LowerLOAD(Op, DAG);
207   case ISD::STORE:              return LowerSTORE(Op, DAG);
208   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
209   case ISD::VAARG:              return LowerVAARG(Op, DAG);
210   case ISD::VASTART:            return LowerVASTART(Op, DAG);
211   case ISD::SMUL_LOHI:          return LowerSMUL_LOHI(Op, DAG);
212   case ISD::UMUL_LOHI:          return LowerUMUL_LOHI(Op, DAG);
213   // FIXME: Remove these when LegalizeDAGTypes lands.
214   case ISD::ADD:
215   case ISD::SUB:                return ExpandADDSUB(Op.getNode(), DAG);
216   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
217   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
218   case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
219   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
220   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
221   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
222   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
223   default:
224     llvm_unreachable("unimplemented operand");
225   }
226 }
227
228 /// ReplaceNodeResults - Replace the results of node with an illegal result
229 /// type with new values built out of custom code.
230 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
231                                              SmallVectorImpl<SDValue>&Results,
232                                              SelectionDAG &DAG) const {
233   switch (N->getOpcode()) {
234   default:
235     llvm_unreachable("Don't know how to custom expand this!");
236   case ISD::ADD:
237   case ISD::SUB:
238     Results.push_back(ExpandADDSUB(N, DAG));
239     return;
240   }
241 }
242
243 //===----------------------------------------------------------------------===//
244 //  Misc Lower Operation implementation
245 //===----------------------------------------------------------------------===//
246
247 SDValue XCoreTargetLowering::
248 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
249 {
250   SDLoc dl(Op);
251   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
252                              Op.getOperand(3), Op.getOperand(4));
253   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
254                      Op.getOperand(1));
255 }
256
257 SDValue XCoreTargetLowering::
258 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
259                         SelectionDAG &DAG) const
260 {
261   // FIXME there is no actual debug info here
262   SDLoc dl(GA);
263   const GlobalValue *UnderlyingGV = GV;
264   // If GV is an alias then use the aliasee to determine the wrapper type
265   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
266     UnderlyingGV = GA->resolveAliasedGlobal();
267   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
268     if (GVar->isConstant())
269       return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
270     return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
271   }
272   return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
273 }
274
275 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
276   if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
277     return true;
278
279   Type *ObjType = GV->getType()->getPointerElementType();
280   if (!ObjType->isSized())
281     return false;
282
283   unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
284   return ObjSize < CodeModelLargeSize && ObjSize != 0;
285 }
286
287 SDValue XCoreTargetLowering::
288 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
289 {
290   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
291   const GlobalValue *GV = GN->getGlobal();
292   SDLoc DL(GN);
293   int64_t Offset = GN->getOffset();
294   if (IsSmallObject(GV, *this)) {
295     // We can only fold positive offsets that are a multiple of the word size.
296     int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
297     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
298     GA = getGlobalAddressWrapper(GA, GV, DAG);
299     // Handle the rest of the offset.
300     if (Offset != FoldedOffset) {
301       SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
302       GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
303     }
304     return GA;
305   } else {
306     // Ideally we would not fold in offset with an index <= 11.
307     Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
308     Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
309     Ty = Type::getInt32Ty(*DAG.getContext());
310     Constant *Idx = ConstantInt::get(Ty, Offset);
311     Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
312     SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
313     return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
314                        MachinePointerInfo(), false, false, false, 0);
315   }
316 }
317
318 SDValue XCoreTargetLowering::
319 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
320 {
321   SDLoc DL(Op);
322
323   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
324   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
325
326   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
327 }
328
329 SDValue XCoreTargetLowering::
330 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
331 {
332   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
333   // FIXME there isn't really debug info here
334   SDLoc dl(CP);
335   EVT PtrVT = Op.getValueType();
336   SDValue Res;
337   if (CP->isMachineConstantPoolEntry()) {
338     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
339                                     CP->getAlignment(), CP->getOffset());
340   } else {
341     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
342                                     CP->getAlignment(), CP->getOffset());
343   }
344   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
345 }
346
347 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
348   return MachineJumpTableInfo::EK_Inline;
349 }
350
351 SDValue XCoreTargetLowering::
352 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
353 {
354   SDValue Chain = Op.getOperand(0);
355   SDValue Table = Op.getOperand(1);
356   SDValue Index = Op.getOperand(2);
357   SDLoc dl(Op);
358   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
359   unsigned JTI = JT->getIndex();
360   MachineFunction &MF = DAG.getMachineFunction();
361   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
362   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
363
364   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
365   if (NumEntries <= 32) {
366     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
367   }
368   assert((NumEntries >> 31) == 0);
369   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
370                                     DAG.getConstant(1, MVT::i32));
371   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
372                      ScaledIndex);
373 }
374
375 SDValue XCoreTargetLowering::
376 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
377                                        int64_t Offset, SelectionDAG &DAG) const
378 {
379   if ((Offset & 0x3) == 0) {
380     return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
381                        false, false, false, 0);
382   }
383   // Lower to pair of consecutive word aligned loads plus some bit shifting.
384   int32_t HighOffset = RoundUpToAlignment(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, MVT::i32));
396     HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
397                            DAG.getConstant(HighOffset, MVT::i32));
398   }
399   SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
400   SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
401
402   SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
403                             LowAddr, MachinePointerInfo(),
404                             false, false, false, 0);
405   SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
406                              HighAddr, MachinePointerInfo(),
407                              false, false, false, 0);
408   SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
409   SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
410   SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
411   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
412                       High.getValue(1));
413   SDValue Ops[] = { Result, Chain };
414   return DAG.getMergeValues(Ops, 2, DL);
415 }
416
417 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
418 {
419   APInt KnownZero, KnownOne;
420   DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
421   return KnownZero.countTrailingOnes() >= 2;
422 }
423
424 SDValue XCoreTargetLowering::
425 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
426   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
427   LoadSDNode *LD = cast<LoadSDNode>(Op);
428   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
429          "Unexpected extension type");
430   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
431   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
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(), 2);
467     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
468                                    DAG.getConstant(2, MVT::i32));
469     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
470                                   HighAddr,
471                                   LD->getPointerInfo().getWithOffset(2),
472                                   MVT::i16, LD->isVolatile(),
473                                   LD->isNonTemporal(), 2);
474     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
475                                       DAG.getConstant(16, MVT::i32));
476     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
477     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
478                              High.getValue(1));
479     SDValue Ops[] = { Result, Chain };
480     return DAG.getMergeValues(Ops, 2, DL);
481   }
482
483   // Lower to a call to __misaligned_load(BasePtr).
484   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
485   TargetLowering::ArgListTy Args;
486   TargetLowering::ArgListEntry Entry;
487
488   Entry.Ty = IntPtrTy;
489   Entry.Node = BasePtr;
490   Args.push_back(Entry);
491
492   TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
493                     false, false, 0, CallingConv::C, /*isTailCall=*/false,
494                     /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
495                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
496                     Args, DAG, DL);
497   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
498
499   SDValue Ops[] =
500     { CallResult.first, CallResult.second };
501
502   return DAG.getMergeValues(Ops, 2, DL);
503 }
504
505 SDValue XCoreTargetLowering::
506 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
507 {
508   StoreSDNode *ST = cast<StoreSDNode>(Op);
509   assert(!ST->isTruncatingStore() && "Unexpected store type");
510   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
511   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
512     return SDValue();
513   }
514   unsigned ABIAlignment = getDataLayout()->
515     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
516   // Leave aligned store alone.
517   if (ST->getAlignment() >= ABIAlignment) {
518     return SDValue();
519   }
520   SDValue Chain = ST->getChain();
521   SDValue BasePtr = ST->getBasePtr();
522   SDValue Value = ST->getValue();
523   SDLoc dl(Op);
524
525   if (ST->getAlignment() == 2) {
526     SDValue Low = Value;
527     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
528                                       DAG.getConstant(16, MVT::i32));
529     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
530                                          ST->getPointerInfo(), MVT::i16,
531                                          ST->isVolatile(), ST->isNonTemporal(),
532                                          2);
533     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
534                                    DAG.getConstant(2, MVT::i32));
535     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
536                                           ST->getPointerInfo().getWithOffset(2),
537                                           MVT::i16, ST->isVolatile(),
538                                           ST->isNonTemporal(), 2);
539     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
540   }
541
542   // Lower to a call to __misaligned_store(BasePtr, Value).
543   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
544   TargetLowering::ArgListTy Args;
545   TargetLowering::ArgListEntry Entry;
546
547   Entry.Ty = IntPtrTy;
548   Entry.Node = BasePtr;
549   Args.push_back(Entry);
550
551   Entry.Node = Value;
552   Args.push_back(Entry);
553
554   TargetLowering::CallLoweringInfo CLI(Chain,
555                     Type::getVoidTy(*DAG.getContext()), false, false,
556                     false, false, 0, CallingConv::C, /*isTailCall=*/false,
557                     /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
558                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
559                     Args, DAG, dl);
560   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
561
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, 2, 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, 2, 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() != 0)
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 = getTargetMachine().getRegisterInfo();
809   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
810                             RegInfo->getFrameRegister(MF), MVT::i32);
811 }
812
813 SDValue XCoreTargetLowering::
814 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
815   // This nodes represent llvm.returnaddress on the DAG.
816   // It takes one operand, the index of the return address to return.
817   // An index of zero corresponds to the current function's return address.
818   // An index of one to the parent's return address, and so on.
819   // Depths > 0 not supported yet!
820   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
821     return SDValue();
822
823   MachineFunction &MF = DAG.getMachineFunction();
824   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
825   int FI = XFI->createLRSpillSlot(MF);
826   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
827   return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
828                      MachinePointerInfo::getFixedStack(FI), false, false,
829                      false, 0);
830 }
831
832 SDValue XCoreTargetLowering::
833 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
834   // This node represents offset from frame pointer to first on-stack argument.
835   // This is needed for correct stack adjustment during unwind.
836   // However, we don't know the offset until after the frame has be finalised.
837   // This is done during the XCoreFTAOElim pass.
838   return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
839 }
840
841 SDValue XCoreTargetLowering::
842 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
843   return Op.getOperand(0);
844 }
845
846 SDValue XCoreTargetLowering::
847 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
848   SDValue Chain = Op.getOperand(0);
849   SDValue Trmp = Op.getOperand(1); // trampoline
850   SDValue FPtr = Op.getOperand(2); // nested function
851   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
852
853   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
854
855   // .align 4
856   // LDAPF_u10 r11, nest
857   // LDW_2rus r11, r11[0]
858   // STWSP_ru6 r11, sp[0]
859   // LDAPF_u10 r11, fptr
860   // LDW_2rus r11, r11[0]
861   // BAU_1r r11
862   // nest:
863   // .word nest
864   // fptr:
865   // .word fptr
866   SDValue OutChains[5];
867
868   SDValue Addr = Trmp;
869
870   SDLoc dl(Op);
871   OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
872                               Addr, MachinePointerInfo(TrmpAddr), false, false,
873                               0);
874
875   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
876                      DAG.getConstant(4, MVT::i32));
877   OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
878                               Addr, MachinePointerInfo(TrmpAddr, 4), false,
879                               false, 0);
880
881   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
882                      DAG.getConstant(8, MVT::i32));
883   OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
884                               Addr, MachinePointerInfo(TrmpAddr, 8), false,
885                               false, 0);
886
887   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
888                      DAG.getConstant(12, MVT::i32));
889   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
890                               MachinePointerInfo(TrmpAddr, 12), false, false,
891                               0);
892
893   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
894                      DAG.getConstant(16, MVT::i32));
895   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
896                               MachinePointerInfo(TrmpAddr, 16), false, false,
897                               0);
898
899   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
900 }
901
902 SDValue XCoreTargetLowering::
903 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
904   SDLoc DL(Op);
905   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
906   switch (IntNo) {
907     case Intrinsic::xcore_crc8:
908       EVT VT = Op.getValueType();
909       SDValue Data =
910         DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
911                     Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
912       SDValue Crc(Data.getNode(), 1);
913       SDValue Results[] = { Crc, Data };
914       return DAG.getMergeValues(Results, 2, DL);
915   }
916   return SDValue();
917 }
918
919 SDValue XCoreTargetLowering::
920 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
921   SDLoc DL(Op);
922   return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
923 }
924
925 //===----------------------------------------------------------------------===//
926 //                      Calling Convention Implementation
927 //===----------------------------------------------------------------------===//
928
929 #include "XCoreGenCallingConv.inc"
930
931 //===----------------------------------------------------------------------===//
932 //                  Call Calling Convention Implementation
933 //===----------------------------------------------------------------------===//
934
935 /// XCore call implementation
936 SDValue
937 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
938                                SmallVectorImpl<SDValue> &InVals) const {
939   SelectionDAG &DAG                     = CLI.DAG;
940   SDLoc &dl                             = CLI.DL;
941   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
942   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
943   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
944   SDValue Chain                         = CLI.Chain;
945   SDValue Callee                        = CLI.Callee;
946   bool &isTailCall                      = CLI.IsTailCall;
947   CallingConv::ID CallConv              = CLI.CallConv;
948   bool isVarArg                         = CLI.IsVarArg;
949
950   // XCore target does not yet support tail call optimization.
951   isTailCall = false;
952
953   // For now, only CallingConv::C implemented
954   switch (CallConv)
955   {
956     default:
957       llvm_unreachable("Unsupported calling convention");
958     case CallingConv::Fast:
959     case CallingConv::C:
960       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
961                             Outs, OutVals, Ins, dl, DAG, InVals);
962   }
963 }
964
965 /// LowerCCCCallTo - functions arguments are copied from virtual
966 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
967 /// CALLSEQ_END are emitted.
968 /// TODO: isTailCall, sret.
969 SDValue
970 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
971                                     CallingConv::ID CallConv, bool isVarArg,
972                                     bool isTailCall,
973                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
974                                     const SmallVectorImpl<SDValue> &OutVals,
975                                     const SmallVectorImpl<ISD::InputArg> &Ins,
976                                     SDLoc dl, SelectionDAG &DAG,
977                                     SmallVectorImpl<SDValue> &InVals) const {
978
979   // Analyze operands of the call, assigning locations to each operand.
980   SmallVector<CCValAssign, 16> ArgLocs;
981   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
982                  getTargetMachine(), ArgLocs, *DAG.getContext());
983
984   // The ABI dictates there should be one stack slot available to the callee
985   // on function entry (for saving lr).
986   CCInfo.AllocateStack(4, 4);
987
988   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
989
990   // Get a count of how many bytes are to be pushed on the stack.
991   unsigned NumBytes = CCInfo.getNextStackOffset();
992
993   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
994                                  getPointerTy(), true), dl);
995
996   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
997   SmallVector<SDValue, 12> MemOpChains;
998
999   // Walk the register/memloc assignments, inserting copies/loads.
1000   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1001     CCValAssign &VA = ArgLocs[i];
1002     SDValue Arg = OutVals[i];
1003
1004     // Promote the value if needed.
1005     switch (VA.getLocInfo()) {
1006       default: llvm_unreachable("Unknown loc info!");
1007       case CCValAssign::Full: break;
1008       case CCValAssign::SExt:
1009         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1010         break;
1011       case CCValAssign::ZExt:
1012         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1013         break;
1014       case CCValAssign::AExt:
1015         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1016         break;
1017     }
1018
1019     // Arguments that can be passed on register must be kept at
1020     // RegsToPass vector
1021     if (VA.isRegLoc()) {
1022       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1023     } else {
1024       assert(VA.isMemLoc());
1025
1026       int Offset = VA.getLocMemOffset();
1027
1028       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1029                                         Chain, Arg,
1030                                         DAG.getConstant(Offset/4, MVT::i32)));
1031     }
1032   }
1033
1034   // Transform all store nodes into one single node because
1035   // all store nodes are independent of each other.
1036   if (!MemOpChains.empty())
1037     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1038                         &MemOpChains[0], MemOpChains.size());
1039
1040   // Build a sequence of copy-to-reg nodes chained together with token
1041   // chain and flag operands which copy the outgoing args into registers.
1042   // The InFlag in necessary since all emitted instructions must be
1043   // stuck together.
1044   SDValue InFlag;
1045   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1046     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1047                              RegsToPass[i].second, InFlag);
1048     InFlag = Chain.getValue(1);
1049   }
1050
1051   // If the callee is a GlobalAddress node (quite common, every direct call is)
1052   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1053   // Likewise ExternalSymbol -> TargetExternalSymbol.
1054   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1055     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1056   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1057     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1058
1059   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1060   //             = Chain, Callee, Reg#1, Reg#2, ...
1061   //
1062   // Returns a chain & a flag for retval copy to use.
1063   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1064   SmallVector<SDValue, 8> Ops;
1065   Ops.push_back(Chain);
1066   Ops.push_back(Callee);
1067
1068   // Add argument registers to the end of the list so that they are
1069   // known live into the call.
1070   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1071     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1072                                   RegsToPass[i].second.getValueType()));
1073
1074   if (InFlag.getNode())
1075     Ops.push_back(InFlag);
1076
1077   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1078   InFlag = Chain.getValue(1);
1079
1080   // Create the CALLSEQ_END node.
1081   Chain = DAG.getCALLSEQ_END(Chain,
1082                              DAG.getConstant(NumBytes, getPointerTy(), true),
1083                              DAG.getConstant(0, getPointerTy(), true),
1084                              InFlag, dl);
1085   InFlag = Chain.getValue(1);
1086
1087   // Handle result values, copying them out of physregs into vregs that we
1088   // return.
1089   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1090                          Ins, dl, DAG, InVals);
1091 }
1092
1093 /// LowerCallResult - Lower the result values of a call into the
1094 /// appropriate copies out of appropriate physical registers.
1095 SDValue
1096 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1097                                      CallingConv::ID CallConv, bool isVarArg,
1098                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1099                                      SDLoc dl, SelectionDAG &DAG,
1100                                      SmallVectorImpl<SDValue> &InVals) const {
1101
1102   // Assign locations to each value returned by this call.
1103   SmallVector<CCValAssign, 16> RVLocs;
1104   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1105                  getTargetMachine(), RVLocs, *DAG.getContext());
1106
1107   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1108
1109   // Copy all of the result registers out of their specified physreg.
1110   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1111     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1112                                  RVLocs[i].getValVT(), InFlag).getValue(1);
1113     InFlag = Chain.getValue(2);
1114     InVals.push_back(Chain.getValue(0));
1115   }
1116
1117   return Chain;
1118 }
1119
1120 //===----------------------------------------------------------------------===//
1121 //             Formal Arguments Calling Convention Implementation
1122 //===----------------------------------------------------------------------===//
1123
1124 namespace {
1125   struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1126 }
1127
1128 /// XCore formal arguments implementation
1129 SDValue
1130 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1131                                           CallingConv::ID CallConv,
1132                                           bool isVarArg,
1133                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1134                                           SDLoc dl,
1135                                           SelectionDAG &DAG,
1136                                           SmallVectorImpl<SDValue> &InVals)
1137                                             const {
1138   switch (CallConv)
1139   {
1140     default:
1141       llvm_unreachable("Unsupported calling convention");
1142     case CallingConv::C:
1143     case CallingConv::Fast:
1144       return LowerCCCArguments(Chain, CallConv, isVarArg,
1145                                Ins, dl, DAG, InVals);
1146   }
1147 }
1148
1149 /// LowerCCCArguments - transform physical registers into
1150 /// virtual registers and generate load operations for
1151 /// arguments places on the stack.
1152 /// TODO: sret
1153 SDValue
1154 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1155                                        CallingConv::ID CallConv,
1156                                        bool isVarArg,
1157                                        const SmallVectorImpl<ISD::InputArg>
1158                                          &Ins,
1159                                        SDLoc dl,
1160                                        SelectionDAG &DAG,
1161                                        SmallVectorImpl<SDValue> &InVals) const {
1162   MachineFunction &MF = DAG.getMachineFunction();
1163   MachineFrameInfo *MFI = MF.getFrameInfo();
1164   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1165
1166   // Assign locations to all of the incoming arguments.
1167   SmallVector<CCValAssign, 16> ArgLocs;
1168   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1169                  getTargetMachine(), ArgLocs, *DAG.getContext());
1170
1171   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1172
1173   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1174
1175   unsigned LRSaveSize = StackSlotSize;
1176
1177   // All getCopyFromReg ops must precede any getMemcpys to prevent the
1178   // scheduler clobbering a register before it has been copied.
1179   // The stages are:
1180   // 1. CopyFromReg (and load) arg & vararg registers.
1181   // 2. Chain CopyFromReg nodes into a TokenFactor.
1182   // 3. Memcpy 'byVal' args & push final InVals.
1183   // 4. Chain mem ops nodes into a TokenFactor.
1184   SmallVector<SDValue, 4> CFRegNode;
1185   SmallVector<ArgDataPair, 4> ArgData;
1186   SmallVector<SDValue, 4> MemOps;
1187
1188   // 1a. CopyFromReg (and load) arg registers.
1189   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1190
1191     CCValAssign &VA = ArgLocs[i];
1192     SDValue ArgIn;
1193
1194     if (VA.isRegLoc()) {
1195       // Arguments passed in registers
1196       EVT RegVT = VA.getLocVT();
1197       switch (RegVT.getSimpleVT().SimpleTy) {
1198       default:
1199         {
1200 #ifndef NDEBUG
1201           errs() << "LowerFormalArguments Unhandled argument type: "
1202                  << RegVT.getSimpleVT().SimpleTy << "\n";
1203 #endif
1204           llvm_unreachable(0);
1205         }
1206       case MVT::i32:
1207         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1208         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1209         ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1210         CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1211       }
1212     } else {
1213       // sanity check
1214       assert(VA.isMemLoc());
1215       // Load the argument to a virtual register
1216       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1217       if (ObjSize > StackSlotSize) {
1218         errs() << "LowerFormalArguments Unhandled argument type: "
1219                << EVT(VA.getLocVT()).getEVTString()
1220                << "\n";
1221       }
1222       // Create the frame index object for this incoming parameter...
1223       int FI = MFI->CreateFixedObject(ObjSize,
1224                                       LRSaveSize + VA.getLocMemOffset(),
1225                                       true);
1226
1227       // Create the SelectionDAG nodes corresponding to a load
1228       //from this parameter
1229       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1230       ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1231                           MachinePointerInfo::getFixedStack(FI),
1232                           false, false, false, 0);
1233     }
1234     const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1235     ArgData.push_back(ADP);
1236   }
1237
1238   // 1b. CopyFromReg vararg registers.
1239   if (isVarArg) {
1240     // Argument registers
1241     static const uint16_t ArgRegs[] = {
1242       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1243     };
1244     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1245     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1246                                                      array_lengthof(ArgRegs));
1247     if (FirstVAReg < array_lengthof(ArgRegs)) {
1248       int offset = 0;
1249       // Save remaining registers, storing higher register numbers at a higher
1250       // address
1251       for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1252         // Create a stack slot
1253         int FI = MFI->CreateFixedObject(4, offset, true);
1254         if (i == (int)FirstVAReg) {
1255           XFI->setVarArgsFrameIndex(FI);
1256         }
1257         offset -= StackSlotSize;
1258         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1259         // Move argument from phys reg -> virt reg
1260         unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1261         RegInfo.addLiveIn(ArgRegs[i], VReg);
1262         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1263         CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1264         // Move argument from virt reg -> stack
1265         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1266                                      MachinePointerInfo(), false, false, 0);
1267         MemOps.push_back(Store);
1268       }
1269     } else {
1270       // This will point to the next argument passed via stack.
1271       XFI->setVarArgsFrameIndex(
1272         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1273                                true));
1274     }
1275   }
1276
1277   // 2. chain CopyFromReg nodes into a TokenFactor.
1278   if (!CFRegNode.empty())
1279     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1280                         CFRegNode.size());
1281
1282   // 3. Memcpy 'byVal' args & push final InVals.
1283   // Aggregates passed "byVal" need to be copied by the callee.
1284   // The callee will use a pointer to this copy, rather than the original
1285   // pointer.
1286   for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1287                                                     ArgDE = ArgData.end();
1288        ArgDI != ArgDE; ++ArgDI) {
1289     if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1290       unsigned Size = ArgDI->Flags.getByValSize();
1291       unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1292       // Create a new object on the stack and copy the pointee into it.
1293       int FI = MFI->CreateStackObject(Size, Align, false);
1294       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1295       InVals.push_back(FIN);
1296       MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1297                                      DAG.getConstant(Size, MVT::i32),
1298                                      Align, false, false,
1299                                      MachinePointerInfo(),
1300                                      MachinePointerInfo()));
1301     } else {
1302       InVals.push_back(ArgDI->SDV);
1303     }
1304   }
1305
1306   // 4, chain mem ops nodes into a TokenFactor.
1307   if (!MemOps.empty()) {
1308     MemOps.push_back(Chain);
1309     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1310                         MemOps.size());
1311   }
1312
1313   return Chain;
1314 }
1315
1316 //===----------------------------------------------------------------------===//
1317 //               Return Value Calling Convention Implementation
1318 //===----------------------------------------------------------------------===//
1319
1320 bool XCoreTargetLowering::
1321 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1322                bool isVarArg,
1323                const SmallVectorImpl<ISD::OutputArg> &Outs,
1324                LLVMContext &Context) const {
1325   SmallVector<CCValAssign, 16> RVLocs;
1326   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1327   return CCInfo.CheckReturn(Outs, RetCC_XCore);
1328 }
1329
1330 SDValue
1331 XCoreTargetLowering::LowerReturn(SDValue Chain,
1332                                  CallingConv::ID CallConv, bool isVarArg,
1333                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1334                                  const SmallVectorImpl<SDValue> &OutVals,
1335                                  SDLoc dl, SelectionDAG &DAG) const {
1336
1337   // CCValAssign - represent the assignment of
1338   // the return value to a location
1339   SmallVector<CCValAssign, 16> RVLocs;
1340
1341   // CCState - Info about the registers and stack slot.
1342   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1343                  getTargetMachine(), RVLocs, *DAG.getContext());
1344
1345   // Analyze return values.
1346   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1347
1348   SDValue Flag;
1349   SmallVector<SDValue, 4> RetOps(1, Chain);
1350
1351   // Return on XCore is always a "retsp 0"
1352   RetOps.push_back(DAG.getConstant(0, MVT::i32));
1353
1354   // Copy the result values into the output registers.
1355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356     CCValAssign &VA = RVLocs[i];
1357     assert(VA.isRegLoc() && "Can only return in registers!");
1358
1359     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1360                              OutVals[i], Flag);
1361
1362     // guarantee that all emitted copies are
1363     // stuck together, avoiding something bad
1364     Flag = Chain.getValue(1);
1365     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1366   }
1367
1368   RetOps[0] = Chain;  // Update chain.
1369
1370   // Add the flag if we have it.
1371   if (Flag.getNode())
1372     RetOps.push_back(Flag);
1373
1374   return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1375                      &RetOps[0], RetOps.size());
1376 }
1377
1378 //===----------------------------------------------------------------------===//
1379 //  Other Lowering Code
1380 //===----------------------------------------------------------------------===//
1381
1382 MachineBasicBlock *
1383 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1384                                                  MachineBasicBlock *BB) const {
1385   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1386   DebugLoc dl = MI->getDebugLoc();
1387   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1388          "Unexpected instr type to insert");
1389
1390   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1391   // control-flow pattern.  The incoming instruction knows the destination vreg
1392   // to set, the condition code register to branch on, the true/false values to
1393   // select between, and a branch opcode to use.
1394   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1395   MachineFunction::iterator It = BB;
1396   ++It;
1397
1398   //  thisMBB:
1399   //  ...
1400   //   TrueVal = ...
1401   //   cmpTY ccX, r1, r2
1402   //   bCC copy1MBB
1403   //   fallthrough --> copy0MBB
1404   MachineBasicBlock *thisMBB = BB;
1405   MachineFunction *F = BB->getParent();
1406   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1407   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1408   F->insert(It, copy0MBB);
1409   F->insert(It, sinkMBB);
1410
1411   // Transfer the remainder of BB and its successor edges to sinkMBB.
1412   sinkMBB->splice(sinkMBB->begin(), BB,
1413                   llvm::next(MachineBasicBlock::iterator(MI)),
1414                   BB->end());
1415   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1416
1417   // Next, add the true and fallthrough blocks as its successors.
1418   BB->addSuccessor(copy0MBB);
1419   BB->addSuccessor(sinkMBB);
1420
1421   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1422     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1423
1424   //  copy0MBB:
1425   //   %FalseValue = ...
1426   //   # fallthrough to sinkMBB
1427   BB = copy0MBB;
1428
1429   // Update machine-CFG edges
1430   BB->addSuccessor(sinkMBB);
1431
1432   //  sinkMBB:
1433   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1434   //  ...
1435   BB = sinkMBB;
1436   BuildMI(*BB, BB->begin(), dl,
1437           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1438     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1439     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1440
1441   MI->eraseFromParent();   // The pseudo instruction is gone now.
1442   return BB;
1443 }
1444
1445 //===----------------------------------------------------------------------===//
1446 // Target Optimization Hooks
1447 //===----------------------------------------------------------------------===//
1448
1449 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1450                                              DAGCombinerInfo &DCI) const {
1451   SelectionDAG &DAG = DCI.DAG;
1452   SDLoc dl(N);
1453   switch (N->getOpcode()) {
1454   default: break;
1455   case XCoreISD::LADD: {
1456     SDValue N0 = N->getOperand(0);
1457     SDValue N1 = N->getOperand(1);
1458     SDValue N2 = N->getOperand(2);
1459     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461     EVT VT = N0.getValueType();
1462
1463     // canonicalize constant to RHS
1464     if (N0C && !N1C)
1465       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1466
1467     // fold (ladd 0, 0, x) -> 0, x & 1
1468     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1469       SDValue Carry = DAG.getConstant(0, VT);
1470       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1471                                    DAG.getConstant(1, VT));
1472       SDValue Ops[] = { Result, Carry };
1473       return DAG.getMergeValues(Ops, 2, dl);
1474     }
1475
1476     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1477     // low bit set
1478     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1479       APInt KnownZero, KnownOne;
1480       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1481                                          VT.getSizeInBits() - 1);
1482       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1483       if ((KnownZero & Mask) == Mask) {
1484         SDValue Carry = DAG.getConstant(0, VT);
1485         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1486         SDValue Ops[] = { Result, Carry };
1487         return DAG.getMergeValues(Ops, 2, dl);
1488       }
1489     }
1490   }
1491   break;
1492   case XCoreISD::LSUB: {
1493     SDValue N0 = N->getOperand(0);
1494     SDValue N1 = N->getOperand(1);
1495     SDValue N2 = N->getOperand(2);
1496     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1497     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1498     EVT VT = N0.getValueType();
1499
1500     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1501     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1502       APInt KnownZero, KnownOne;
1503       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1504                                          VT.getSizeInBits() - 1);
1505       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1506       if ((KnownZero & Mask) == Mask) {
1507         SDValue Borrow = N2;
1508         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1509                                      DAG.getConstant(0, VT), N2);
1510         SDValue Ops[] = { Result, Borrow };
1511         return DAG.getMergeValues(Ops, 2, dl);
1512       }
1513     }
1514
1515     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1516     // low bit set
1517     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1518       APInt KnownZero, KnownOne;
1519       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1520                                          VT.getSizeInBits() - 1);
1521       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1522       if ((KnownZero & Mask) == Mask) {
1523         SDValue Borrow = DAG.getConstant(0, VT);
1524         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1525         SDValue Ops[] = { Result, Borrow };
1526         return DAG.getMergeValues(Ops, 2, dl);
1527       }
1528     }
1529   }
1530   break;
1531   case XCoreISD::LMUL: {
1532     SDValue N0 = N->getOperand(0);
1533     SDValue N1 = N->getOperand(1);
1534     SDValue N2 = N->getOperand(2);
1535     SDValue N3 = N->getOperand(3);
1536     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1537     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1538     EVT VT = N0.getValueType();
1539     // Canonicalize multiplicative constant to RHS. If both multiplicative
1540     // operands are constant canonicalize smallest to RHS.
1541     if ((N0C && !N1C) ||
1542         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1543       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1544                          N1, N0, N2, N3);
1545
1546     // lmul(x, 0, a, b)
1547     if (N1C && N1C->isNullValue()) {
1548       // If the high result is unused fold to add(a, b)
1549       if (N->hasNUsesOfValue(0, 0)) {
1550         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1551         SDValue Ops[] = { Lo, Lo };
1552         return DAG.getMergeValues(Ops, 2, dl);
1553       }
1554       // Otherwise fold to ladd(a, b, 0)
1555       SDValue Result =
1556         DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1557       SDValue Carry(Result.getNode(), 1);
1558       SDValue Ops[] = { Carry, Result };
1559       return DAG.getMergeValues(Ops, 2, dl);
1560     }
1561   }
1562   break;
1563   case ISD::ADD: {
1564     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1565     // lmul(x, y, a, b). The high result of lmul will be ignored.
1566     // This is only profitable if the intermediate results are unused
1567     // elsewhere.
1568     SDValue Mul0, Mul1, Addend0, Addend1;
1569     if (N->getValueType(0) == MVT::i32 &&
1570         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1571       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1572                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1573                                     Mul1, Addend0, Addend1);
1574       SDValue Result(Ignored.getNode(), 1);
1575       return Result;
1576     }
1577     APInt HighMask = APInt::getHighBitsSet(64, 32);
1578     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1579     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1580     // before type legalization as it is messy to match the operands after
1581     // that.
1582     if (N->getValueType(0) == MVT::i64 &&
1583         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1584         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1585         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1586         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1587         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1588       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1589                                   Mul0, DAG.getConstant(0, MVT::i32));
1590       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1591                                   Mul1, DAG.getConstant(0, MVT::i32));
1592       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1593                                      Addend0, DAG.getConstant(0, MVT::i32));
1594       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1595                                      Addend1, DAG.getConstant(0, MVT::i32));
1596       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1597                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1598                                Addend0L, Addend1L);
1599       SDValue Lo(Hi.getNode(), 1);
1600       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1601     }
1602   }
1603   break;
1604   case ISD::STORE: {
1605     // Replace unaligned store of unaligned load with memmove.
1606     StoreSDNode *ST  = cast<StoreSDNode>(N);
1607     if (!DCI.isBeforeLegalize() ||
1608         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1609         ST->isVolatile() || ST->isIndexed()) {
1610       break;
1611     }
1612     SDValue Chain = ST->getChain();
1613
1614     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1615     if (StoreBits % 8) {
1616       break;
1617     }
1618     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1619         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1620     unsigned Alignment = ST->getAlignment();
1621     if (Alignment >= ABIAlignment) {
1622       break;
1623     }
1624
1625     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1626       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1627         LD->getAlignment() == Alignment &&
1628         !LD->isVolatile() && !LD->isIndexed() &&
1629         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1630         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1631                               LD->getBasePtr(),
1632                               DAG.getConstant(StoreBits/8, MVT::i32),
1633                               Alignment, false, ST->getPointerInfo(),
1634                               LD->getPointerInfo());
1635       }
1636     }
1637     break;
1638   }
1639   }
1640   return SDValue();
1641 }
1642
1643 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1644                                                          APInt &KnownZero,
1645                                                          APInt &KnownOne,
1646                                                          const SelectionDAG &DAG,
1647                                                          unsigned Depth) const {
1648   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1649   switch (Op.getOpcode()) {
1650   default: break;
1651   case XCoreISD::LADD:
1652   case XCoreISD::LSUB:
1653     if (Op.getResNo() == 1) {
1654       // Top bits of carry / borrow are clear.
1655       KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1656                                         KnownZero.getBitWidth() - 1);
1657     }
1658     break;
1659   }
1660 }
1661
1662 //===----------------------------------------------------------------------===//
1663 //  Addressing mode description hooks
1664 //===----------------------------------------------------------------------===//
1665
1666 static inline bool isImmUs(int64_t val)
1667 {
1668   return (val >= 0 && val <= 11);
1669 }
1670
1671 static inline bool isImmUs2(int64_t val)
1672 {
1673   return (val%2 == 0 && isImmUs(val/2));
1674 }
1675
1676 static inline bool isImmUs4(int64_t val)
1677 {
1678   return (val%4 == 0 && isImmUs(val/4));
1679 }
1680
1681 /// isLegalAddressingMode - Return true if the addressing mode represented
1682 /// by AM is legal for this target, for a load/store of the specified type.
1683 bool
1684 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1685                                               Type *Ty) const {
1686   if (Ty->getTypeID() == Type::VoidTyID)
1687     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1688
1689   const DataLayout *TD = TM.getDataLayout();
1690   unsigned Size = TD->getTypeAllocSize(Ty);
1691   if (AM.BaseGV) {
1692     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1693                  AM.BaseOffs%4 == 0;
1694   }
1695
1696   switch (Size) {
1697   case 1:
1698     // reg + imm
1699     if (AM.Scale == 0) {
1700       return isImmUs(AM.BaseOffs);
1701     }
1702     // reg + reg
1703     return AM.Scale == 1 && AM.BaseOffs == 0;
1704   case 2:
1705   case 3:
1706     // reg + imm
1707     if (AM.Scale == 0) {
1708       return isImmUs2(AM.BaseOffs);
1709     }
1710     // reg + reg<<1
1711     return AM.Scale == 2 && AM.BaseOffs == 0;
1712   default:
1713     // reg + imm
1714     if (AM.Scale == 0) {
1715       return isImmUs4(AM.BaseOffs);
1716     }
1717     // reg + reg<<2
1718     return AM.Scale == 4 && AM.BaseOffs == 0;
1719   }
1720 }
1721
1722 //===----------------------------------------------------------------------===//
1723 //                           XCore Inline Assembly Support
1724 //===----------------------------------------------------------------------===//
1725
1726 std::pair<unsigned, const TargetRegisterClass*>
1727 XCoreTargetLowering::
1728 getRegForInlineAsmConstraint(const std::string &Constraint,
1729                              MVT VT) const {
1730   if (Constraint.size() == 1) {
1731     switch (Constraint[0]) {
1732     default : break;
1733     case 'r':
1734       return std::make_pair(0U, &XCore::GRRegsRegClass);
1735     }
1736   }
1737   // Use the default implementation in TargetLowering to convert the register
1738   // constraint into a member of a register class.
1739   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1740 }