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