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