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