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