Home | History | Annotate | Download | only in XCore
      1 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ---------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the XCoreTargetLowering class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #define DEBUG_TYPE "xcore-lower"
     15 
     16 #include "XCoreISelLowering.h"
     17 #include "XCore.h"
     18 #include "XCoreMachineFunctionInfo.h"
     19 #include "XCoreSubtarget.h"
     20 #include "XCoreTargetMachine.h"
     21 #include "XCoreTargetObjectFile.h"
     22 #include "llvm/CodeGen/CallingConvLower.h"
     23 #include "llvm/CodeGen/MachineFrameInfo.h"
     24 #include "llvm/CodeGen/MachineFunction.h"
     25 #include "llvm/CodeGen/MachineInstrBuilder.h"
     26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
     27 #include "llvm/CodeGen/MachineRegisterInfo.h"
     28 #include "llvm/CodeGen/SelectionDAGISel.h"
     29 #include "llvm/CodeGen/ValueTypes.h"
     30 #include "llvm/IR/CallingConv.h"
     31 #include "llvm/IR/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;
     40 
     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 }
     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::GRRegsRegClass);
     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::i32,   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   // We want to custom lower some of our intrinsics.
    157   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
    158 
    159   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
    160   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
    161     = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
    162 
    163   // We have target-specific dag combine patterns for the following nodes:
    164   setTargetDAGCombine(ISD::STORE);
    165   setTargetDAGCombine(ISD::ADD);
    166 
    167   setMinFunctionAlignment(1);
    168 }
    169 
    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   }
    196 }
    197 
    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   }
    211 }
    212 
    213 //===----------------------------------------------------------------------===//
    214 //  Misc Lower Operation implementation
    215 //===----------------------------------------------------------------------===//
    216 
    217 SDValue XCoreTargetLowering::
    218 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
    219 {
    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));
    225 }
    226 
    227 SDValue XCoreTargetLowering::
    228 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
    229                         SelectionDAG &DAG) const
    230 {
    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);
    243 }
    244 
    245 SDValue XCoreTargetLowering::
    246 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
    247 {
    248   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    249   SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
    250   return getGlobalAddressWrapper(GA, GV, DAG);
    251 }
    252 
    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));
    256 }
    257 
    258 static inline bool isZeroLengthArray(Type *Ty) {
    259   ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
    260   return AT && (AT->getNumElements() == 0);
    261 }
    262 
    263 SDValue XCoreTargetLowering::
    264 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
    265 {
    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);
    294 }
    295 
    296 SDValue XCoreTargetLowering::
    297 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
    298 {
    299   DebugLoc DL = Op.getDebugLoc();
    300 
    301   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
    302   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
    303 
    304   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
    305 }
    306 
    307 SDValue XCoreTargetLowering::
    308 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
    309 {
    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);
    323 }
    324 
    325 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
    326   return MachineJumpTableInfo::EK_Inline;
    327 }
    328 
    329 SDValue XCoreTargetLowering::
    330 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
    331 {
    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);
    341 
    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);
    351 }
    352 
    353 static bool
    354 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
    355                                     int64_t &Offset)
    356 {
    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;
    398 }
    399 
    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();
    408 
    409   unsigned ABIAlignment = getDataLayout()->
    410     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
    411   // Leave aligned load alone.
    412   if (LD->getAlignment() >= ABIAlignment)
    413     return SDValue();
    414 
    415   SDValue Chain = LD->getChain();
    416   SDValue BasePtr = LD->getBasePtr();
    417   DebugLoc DL = Op.getDebugLoc();
    418 
    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);
    441 
    442     SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
    443     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
    444 
    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   }
    459 
    460   if (LD->getAlignment() == 2) {
    461     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
    462                                  BasePtr, LD->getPointerInfo(), MVT::i16,
    463                                  LD->isVolatile(), LD->isNonTemporal(), 2);
    464     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
    465                                    DAG.getConstant(2, MVT::i32));
    466     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
    467                                   HighAddr,
    468                                   LD->getPointerInfo().getWithOffset(2),
    469                                   MVT::i16, LD->isVolatile(),
    470                                   LD->isNonTemporal(), 2);
    471     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
    472                                       DAG.getConstant(16, MVT::i32));
    473     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
    474     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
    475                              High.getValue(1));
    476     SDValue Ops[] = { Result, Chain };
    477     return DAG.getMergeValues(Ops, 2, DL);
    478   }
    479 
    480   // Lower to a call to __misaligned_load(BasePtr).
    481   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
    482   TargetLowering::ArgListTy Args;
    483   TargetLowering::ArgListEntry Entry;
    484 
    485   Entry.Ty = IntPtrTy;
    486   Entry.Node = BasePtr;
    487   Args.push_back(Entry);
    488 
    489   TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
    490                     false, false, 0, CallingConv::C, /*isTailCall=*/false,
    491                     /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
    492                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
    493                     Args, DAG, DL);
    494   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    495 
    496   SDValue Ops[] =
    497     { CallResult.first, CallResult.second };
    498 
    499   return DAG.getMergeValues(Ops, 2, DL);
    500 }
    501 
    502 SDValue XCoreTargetLowering::
    503 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
    504 {
    505   StoreSDNode *ST = cast<StoreSDNode>(Op);
    506   assert(!ST->isTruncatingStore() && "Unexpected store type");
    507   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
    508   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
    509     return SDValue();
    510   }
    511   unsigned ABIAlignment = getDataLayout()->
    512     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
    513   // Leave aligned store alone.
    514   if (ST->getAlignment() >= ABIAlignment) {
    515     return SDValue();
    516   }
    517   SDValue Chain = ST->getChain();
    518   SDValue BasePtr = ST->getBasePtr();
    519   SDValue Value = ST->getValue();
    520   DebugLoc dl = Op.getDebugLoc();
    521 
    522   if (ST->getAlignment() == 2) {
    523     SDValue Low = Value;
    524     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
    525                                       DAG.getConstant(16, MVT::i32));
    526     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
    527                                          ST->getPointerInfo(), MVT::i16,
    528                                          ST->isVolatile(), ST->isNonTemporal(),
    529                                          2);
    530     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
    531                                    DAG.getConstant(2, MVT::i32));
    532     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
    533                                           ST->getPointerInfo().getWithOffset(2),
    534                                           MVT::i16, ST->isVolatile(),
    535                                           ST->isNonTemporal(), 2);
    536     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
    537   }
    538 
    539   // Lower to a call to __misaligned_store(BasePtr, Value).
    540   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
    541   TargetLowering::ArgListTy Args;
    542   TargetLowering::ArgListEntry Entry;
    543 
    544   Entry.Ty = IntPtrTy;
    545   Entry.Node = BasePtr;
    546   Args.push_back(Entry);
    547 
    548   Entry.Node = Value;
    549   Args.push_back(Entry);
    550 
    551   TargetLowering::CallLoweringInfo CLI(Chain,
    552                     Type::getVoidTy(*DAG.getContext()), false, false,
    553                     false, false, 0, CallingConv::C, /*isTailCall=*/false,
    554                     /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
    555                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
    556                     Args, DAG, dl);
    557   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    558 
    559   return CallResult.second;
    560 }
    561 
    562 SDValue XCoreTargetLowering::
    563 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
    564 {
    565   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
    566          "Unexpected operand to lower!");
    567   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);
    577 }
    578 
    579 SDValue XCoreTargetLowering::
    580 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
    581 {
    582   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
    583          "Unexpected operand to lower!");
    584   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);
    594 }
    595 
    596 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
    597 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
    598 /// each intermediate result in the calculation must also have a single use.
    599 /// If the Op is in the correct form the constituent parts are written to Mul0,
    600 /// Mul1, Addend0 and Addend1.
    601 static bool
    602 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
    603             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
    604 {
    605   if (Op.getOpcode() != ISD::ADD)
    606     return false;
    607   SDValue N0 = Op.getOperand(0);
    608   SDValue N1 = Op.getOperand(1);
    609   SDValue AddOp;
    610   SDValue OtherOp;
    611   if (N0.getOpcode() == ISD::ADD) {
    612     AddOp = N0;
    613     OtherOp = N1;
    614   } else if (N1.getOpcode() == ISD::ADD) {
    615     AddOp = N1;
    616     OtherOp = N0;
    617   } else {
    618     return false;
    619   }
    620   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
    621     return false;
    622   if (OtherOp.getOpcode() == ISD::MUL) {
    623     // add(add(a,b),mul(x,y))
    624     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
    625       return false;
    626     Mul0 = OtherOp.getOperand(0);
    627     Mul1 = OtherOp.getOperand(1);
    628     Addend0 = AddOp.getOperand(0);
    629     Addend1 = AddOp.getOperand(1);
    630     return true;
    631   }
    632   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
    633     // add(add(mul(x,y),a),b)
    634     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
    635       return false;
    636     Mul0 = AddOp.getOperand(0).getOperand(0);
    637     Mul1 = AddOp.getOperand(0).getOperand(1);
    638     Addend0 = AddOp.getOperand(1);
    639     Addend1 = OtherOp;
    640     return true;
    641   }
    642   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
    643     // add(add(a,mul(x,y)),b)
    644     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
    645       return false;
    646     Mul0 = AddOp.getOperand(1).getOperand(0);
    647     Mul1 = AddOp.getOperand(1).getOperand(1);
    648     Addend0 = AddOp.getOperand(0);
    649     Addend1 = OtherOp;
    650     return true;
    651   }
    652   return false;
    653 }
    654 
    655 SDValue XCoreTargetLowering::
    656 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
    657 {
    658   SDValue Mul;
    659   SDValue Other;
    660   if (N->getOperand(0).getOpcode() == ISD::MUL) {
    661     Mul = N->getOperand(0);
    662     Other = N->getOperand(1);
    663   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
    664     Mul = N->getOperand(1);
    665     Other = N->getOperand(0);
    666   } else {
    667     return SDValue();
    668   }
    669   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);
    713 }
    714 
    715 SDValue XCoreTargetLowering::
    716 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
    717 {
    718   assert(N->getValueType(0) == MVT::i64 &&
    719          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
    720         "Unknown operand to lower!");
    721 
    722   if (N->getOpcode() == ISD::ADD) {
    723     SDValue Result = TryExpandADDWithMul(N, DAG);
    724     if (Result.getNode() != 0)
    725       return Result;
    726   }
    727 
    728   DebugLoc dl = N->getDebugLoc();
    729 
    730   // Extract components
    731   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    732                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
    733   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    734                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
    735   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    736                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
    737   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
    738                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
    739 
    740   // Expand
    741   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
    742                                                    XCoreISD::LSUB;
    743   SDValue Zero = DAG.getConstant(0, MVT::i32);
    744   SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
    745                            LHSL, RHSL, Zero);
    746   SDValue Carry(Lo.getNode(), 1);
    747 
    748   SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
    749                            LHSH, RHSH, Carry);
    750   SDValue Ignored(Hi.getNode(), 1);
    751   // Merge the pieces
    752   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
    753 }
    754 
    755 SDValue XCoreTargetLowering::
    756 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
    757 {
    758   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);
    777 }
    778 
    779 SDValue XCoreTargetLowering::
    780 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
    781 {
    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);
    790 }
    791 
    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();
    798 
    799   MachineFunction &MF = DAG.getMachineFunction();
    800   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
    801   return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    802                             RegInfo->getFrameRegister(MF), MVT::i32);
    803 }
    804 
    805 SDValue XCoreTargetLowering::
    806 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
    807   return Op.getOperand(0);
    808 }
    809 
    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
    816 
    817   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
    818 
    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];
    831 
    832   SDValue Addr = Trmp;
    833 
    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);
    838 
    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);
    844 
    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);
    850 
    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);
    856 
    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);
    862 
    863   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
    864 }
    865 
    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();
    881 }
    882 
    883 //===----------------------------------------------------------------------===//
    884 //                      Calling Convention Implementation
    885 //===----------------------------------------------------------------------===//
    886 
    887 #include "XCoreGenCallingConv.inc"
    888 
    889 //===----------------------------------------------------------------------===//
    890 //                  Call Calling Convention Implementation
    891 //===----------------------------------------------------------------------===//
    892 
    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;
    907 
    908   // XCore target does not yet support tail call optimization.
    909   isTailCall = false;
    910 
    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   }
    921 }
    922 
    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 {
    936 
    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());
    941 
    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);
    945 
    946   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
    947 
    948   // Get a count of how many bytes are to be pushed on the stack.
    949   unsigned NumBytes = CCInfo.getNextStackOffset();
    950 
    951   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
    952                                  getPointerTy(), true));
    953 
    954   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
    955   SmallVector<SDValue, 12> MemOpChains;
    956 
    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];
    961 
    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     }
    976 
    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());
    983 
    984       int Offset = VA.getLocMemOffset();
    985 
    986       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
    987                                         Chain, Arg,
    988                                         DAG.getConstant(Offset/4, MVT::i32)));
    989     }
    990   }
    991 
    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());
    997 
    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   }
   1008 
   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);
   1016 
   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);
   1025 
   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()));
   1031 
   1032   if (InFlag.getNode())
   1033     Ops.push_back(InFlag);
   1034 
   1035   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
   1036   InFlag = Chain.getValue(1);
   1037 
   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);
   1044 
   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);
   1049 }
   1050 
   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 {
   1059 
   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());
   1064 
   1065   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
   1066 
   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   }
   1074 
   1075   return Chain;
   1076 }
   1077 
   1078 //===----------------------------------------------------------------------===//
   1079 //             Formal Arguments Calling Convention Implementation
   1080 //===----------------------------------------------------------------------===//
   1081 
   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   }
   1101 }
   1102 
   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();
   1119 
   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());
   1124 
   1125   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
   1126 
   1127   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
   1128 
   1129   unsigned LRSaveSize = StackSlotSize;
   1130 
   1131   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   1132 
   1133     CCValAssign &VA = ArgLocs[i];
   1134 
   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);
   1166 
   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   }
   1175 
   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   }
   1216 
   1217   return Chain;
   1218 }
   1219 
   1220 //===----------------------------------------------------------------------===//
   1221 //               Return Value Calling Convention Implementation
   1222 //===----------------------------------------------------------------------===//
   1223 
   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);
   1232 }
   1233 
   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 {
   1240 
   1241   // CCValAssign - represent the assignment of
   1242   // the return value to a location
   1243   SmallVector<CCValAssign, 16> RVLocs;
   1244 
   1245   // CCState - Info about the registers and stack slot.
   1246   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   1247                  getTargetMachine(), RVLocs, *DAG.getContext());
   1248 
   1249   // Analyze return values.
   1250   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
   1251 
   1252   SDValue Flag;
   1253   SmallVector<SDValue, 4> RetOps(1, Chain);
   1254 
   1255   // Return on XCore is always a "retsp 0"
   1256   RetOps.push_back(DAG.getConstant(0, MVT::i32));
   1257 
   1258   // Copy the result values into the output registers.
   1259   for (unsigned i = 0; i != RVLocs.size(); ++i) {
   1260     CCValAssign &VA = RVLocs[i];
   1261     assert(VA.isRegLoc() && "Can only return in registers!");
   1262 
   1263     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
   1264                              OutVals[i], Flag);
   1265 
   1266     // guarantee that all emitted copies are
   1267     // stuck together, avoiding something bad
   1268     Flag = Chain.getValue(1);
   1269     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   1270   }
   1271 
   1272   RetOps[0] = Chain;  // Update chain.
   1273 
   1274   // Add the flag if we have it.
   1275   if (Flag.getNode())
   1276     RetOps.push_back(Flag);
   1277 
   1278   return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
   1279                      &RetOps[0], RetOps.size());
   1280 }
   1281 
   1282 //===----------------------------------------------------------------------===//
   1283 //  Other Lowering Code
   1284 //===----------------------------------------------------------------------===//
   1285 
   1286 MachineBasicBlock *
   1287 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
   1288                                                  MachineBasicBlock *BB) const {
   1289   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
   1290   DebugLoc dl = MI->getDebugLoc();
   1291   assert((MI->getOpcode() == XCore::SELECT_CC) &&
   1292          "Unexpected instr type to insert");
   1293 
   1294   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
   1295   // control-flow pattern.  The incoming instruction knows the destination vreg
   1296   // to set, the condition code register to branch on, the true/false values to
   1297   // select between, and a branch opcode to use.
   1298   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   1299   MachineFunction::iterator It = BB;
   1300   ++It;
   1301 
   1302   //  thisMBB:
   1303   //  ...
   1304   //   TrueVal = ...
   1305   //   cmpTY ccX, r1, r2
   1306   //   bCC copy1MBB
   1307   //   fallthrough --> copy0MBB
   1308   MachineBasicBlock *thisMBB = BB;
   1309   MachineFunction *F = BB->getParent();
   1310   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
   1311   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
   1312   F->insert(It, copy0MBB);
   1313   F->insert(It, sinkMBB);
   1314 
   1315   // Transfer the remainder of BB and its successor edges to sinkMBB.
   1316   sinkMBB->splice(sinkMBB->begin(), BB,
   1317                   llvm::next(MachineBasicBlock::iterator(MI)),
   1318                   BB->end());
   1319   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
   1320 
   1321   // Next, add the true and fallthrough blocks as its successors.
   1322   BB->addSuccessor(copy0MBB);
   1323   BB->addSuccessor(sinkMBB);
   1324 
   1325   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
   1326     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
   1327 
   1328   //  copy0MBB:
   1329   //   %FalseValue = ...
   1330   //   # fallthrough to sinkMBB
   1331   BB = copy0MBB;
   1332 
   1333   // Update machine-CFG edges
   1334   BB->addSuccessor(sinkMBB);
   1335 
   1336   //  sinkMBB:
   1337   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
   1338   //  ...
   1339   BB = sinkMBB;
   1340   BuildMI(*BB, BB->begin(), dl,
   1341           TII.get(XCore::PHI), MI->getOperand(0).getReg())
   1342     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
   1343     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
   1344 
   1345   MI->eraseFromParent();   // The pseudo instruction is gone now.
   1346   return BB;
   1347 }
   1348 
   1349 //===----------------------------------------------------------------------===//
   1350 // Target Optimization Hooks
   1351 //===----------------------------------------------------------------------===//
   1352 
   1353 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
   1354                                              DAGCombinerInfo &DCI) const {
   1355   SelectionDAG &DAG = DCI.DAG;
   1356   DebugLoc dl = N->getDebugLoc();
   1357   switch (N->getOpcode()) {
   1358   default: break;
   1359   case XCoreISD::LADD: {
   1360     SDValue N0 = N->getOperand(0);
   1361     SDValue N1 = N->getOperand(1);
   1362     SDValue N2 = N->getOperand(2);
   1363     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1364     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1365     EVT VT = N0.getValueType();
   1366 
   1367     // canonicalize constant to RHS
   1368     if (N0C && !N1C)
   1369       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
   1370 
   1371     // fold (ladd 0, 0, x) -> 0, x & 1
   1372     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
   1373       SDValue Carry = DAG.getConstant(0, VT);
   1374       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
   1375                                    DAG.getConstant(1, VT));
   1376       SDValue Ops[] = { Result, Carry };
   1377       return DAG.getMergeValues(Ops, 2, dl);
   1378     }
   1379 
   1380     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
   1381     // low bit set
   1382     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
   1383       APInt KnownZero, KnownOne;
   1384       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
   1385                                          VT.getSizeInBits() - 1);
   1386       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
   1387       if ((KnownZero & Mask) == Mask) {
   1388         SDValue Carry = DAG.getConstant(0, VT);
   1389         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
   1390         SDValue Ops[] = { Result, Carry };
   1391         return DAG.getMergeValues(Ops, 2, dl);
   1392       }
   1393     }
   1394   }
   1395   break;
   1396   case XCoreISD::LSUB: {
   1397     SDValue N0 = N->getOperand(0);
   1398     SDValue N1 = N->getOperand(1);
   1399     SDValue N2 = N->getOperand(2);
   1400     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1401     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1402     EVT VT = N0.getValueType();
   1403 
   1404     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
   1405     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
   1406       APInt KnownZero, KnownOne;
   1407       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
   1408                                          VT.getSizeInBits() - 1);
   1409       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
   1410       if ((KnownZero & Mask) == Mask) {
   1411         SDValue Borrow = N2;
   1412         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
   1413                                      DAG.getConstant(0, VT), N2);
   1414         SDValue Ops[] = { Result, Borrow };
   1415         return DAG.getMergeValues(Ops, 2, dl);
   1416       }
   1417     }
   1418 
   1419     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
   1420     // low bit set
   1421     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
   1422       APInt KnownZero, KnownOne;
   1423       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
   1424                                          VT.getSizeInBits() - 1);
   1425       DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
   1426       if ((KnownZero & Mask) == Mask) {
   1427         SDValue Borrow = DAG.getConstant(0, VT);
   1428         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
   1429         SDValue Ops[] = { Result, Borrow };
   1430         return DAG.getMergeValues(Ops, 2, dl);
   1431       }
   1432     }
   1433   }
   1434   break;
   1435   case XCoreISD::LMUL: {
   1436     SDValue N0 = N->getOperand(0);
   1437     SDValue N1 = N->getOperand(1);
   1438     SDValue N2 = N->getOperand(2);
   1439     SDValue N3 = N->getOperand(3);
   1440     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1441     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1442     EVT VT = N0.getValueType();
   1443     // Canonicalize multiplicative constant to RHS. If both multiplicative
   1444     // operands are constant canonicalize smallest to RHS.
   1445     if ((N0C && !N1C) ||
   1446         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
   1447       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
   1448                          N1, N0, N2, N3);
   1449 
   1450     // lmul(x, 0, a, b)
   1451     if (N1C && N1C->isNullValue()) {
   1452       // If the high result is unused fold to add(a, b)
   1453       if (N->hasNUsesOfValue(0, 0)) {
   1454         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
   1455         SDValue Ops[] = { Lo, Lo };
   1456         return DAG.getMergeValues(Ops, 2, dl);
   1457       }
   1458       // Otherwise fold to ladd(a, b, 0)
   1459       SDValue Result =
   1460         DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
   1461       SDValue Carry(Result.getNode(), 1);
   1462       SDValue Ops[] = { Carry, Result };
   1463       return DAG.getMergeValues(Ops, 2, dl);
   1464     }
   1465   }
   1466   break;
   1467   case ISD::ADD: {
   1468     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
   1469     // lmul(x, y, a, b). The high result of lmul will be ignored.
   1470     // This is only profitable if the intermediate results are unused
   1471     // elsewhere.
   1472     SDValue Mul0, Mul1, Addend0, Addend1;
   1473     if (N->getValueType(0) == MVT::i32 &&
   1474         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
   1475       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
   1476                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
   1477                                     Mul1, Addend0, Addend1);
   1478       SDValue Result(Ignored.getNode(), 1);
   1479       return Result;
   1480     }
   1481     APInt HighMask = APInt::getHighBitsSet(64, 32);
   1482     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
   1483     // lmul(x, y, a, b) if all operands are zero-extended. We do this
   1484     // before type legalization as it is messy to match the operands after
   1485     // that.
   1486     if (N->getValueType(0) == MVT::i64 &&
   1487         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
   1488         DAG.MaskedValueIsZero(Mul0, HighMask) &&
   1489         DAG.MaskedValueIsZero(Mul1, HighMask) &&
   1490         DAG.MaskedValueIsZero(Addend0, HighMask) &&
   1491         DAG.MaskedValueIsZero(Addend1, HighMask)) {
   1492       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   1493                                   Mul0, DAG.getConstant(0, MVT::i32));
   1494       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   1495                                   Mul1, DAG.getConstant(0, MVT::i32));
   1496       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   1497                                      Addend0, DAG.getConstant(0, MVT::i32));
   1498       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   1499                                      Addend1, DAG.getConstant(0, MVT::i32));
   1500       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
   1501                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
   1502                                Addend0L, Addend1L);
   1503       SDValue Lo(Hi.getNode(), 1);
   1504       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
   1505     }
   1506   }
   1507   break;
   1508   case ISD::STORE: {
   1509     // Replace unaligned store of unaligned load with memmove.
   1510     StoreSDNode *ST  = cast<StoreSDNode>(N);
   1511     if (!DCI.isBeforeLegalize() ||
   1512         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
   1513         ST->isVolatile() || ST->isIndexed()) {
   1514       break;
   1515     }
   1516     SDValue Chain = ST->getChain();
   1517 
   1518     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
   1519     if (StoreBits % 8) {
   1520       break;
   1521     }
   1522     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
   1523         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
   1524     unsigned Alignment = ST->getAlignment();
   1525     if (Alignment >= ABIAlignment) {
   1526       break;
   1527     }
   1528 
   1529     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
   1530       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
   1531         LD->getAlignment() == Alignment &&
   1532         !LD->isVolatile() && !LD->isIndexed() &&
   1533         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
   1534         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
   1535                               LD->getBasePtr(),
   1536                               DAG.getConstant(StoreBits/8, MVT::i32),
   1537                               Alignment, false, ST->getPointerInfo(),
   1538                               LD->getPointerInfo());
   1539       }
   1540     }
   1541     break;
   1542   }
   1543   }
   1544   return SDValue();
   1545 }
   1546 
   1547 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
   1548                                                          APInt &KnownZero,
   1549                                                          APInt &KnownOne,
   1550                                                          const SelectionDAG &DAG,
   1551                                                          unsigned Depth) const {
   1552   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
   1553   switch (Op.getOpcode()) {
   1554   default: break;
   1555   case XCoreISD::LADD:
   1556   case XCoreISD::LSUB:
   1557     if (Op.getResNo() == 1) {
   1558       // Top bits of carry / borrow are clear.
   1559       KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
   1560                                         KnownZero.getBitWidth() - 1);
   1561     }
   1562     break;
   1563   }
   1564 }
   1565 
   1566 //===----------------------------------------------------------------------===//
   1567 //  Addressing mode description hooks
   1568 //===----------------------------------------------------------------------===//
   1569 
   1570 static inline bool isImmUs(int64_t val)
   1571 {
   1572   return (val >= 0 && val <= 11);
   1573 }
   1574 
   1575 static inline bool isImmUs2(int64_t val)
   1576 {
   1577   return (val%2 == 0 && isImmUs(val/2));
   1578 }
   1579 
   1580 static inline bool isImmUs4(int64_t val)
   1581 {
   1582   return (val%4 == 0 && isImmUs(val/4));
   1583 }
   1584 
   1585 /// isLegalAddressingMode - Return true if the addressing mode represented
   1586 /// by AM is legal for this target, for a load/store of the specified type.
   1587 bool
   1588 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
   1589                                               Type *Ty) const {
   1590   if (Ty->getTypeID() == Type::VoidTyID)
   1591     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
   1592 
   1593   const DataLayout *TD = TM.getDataLayout();
   1594   unsigned Size = TD->getTypeAllocSize(Ty);
   1595   if (AM.BaseGV) {
   1596     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
   1597                  AM.BaseOffs%4 == 0;
   1598   }
   1599 
   1600   switch (Size) {
   1601   case 1:
   1602     // reg + imm
   1603     if (AM.Scale == 0) {
   1604       return isImmUs(AM.BaseOffs);
   1605     }
   1606     // reg + reg
   1607     return AM.Scale == 1 && AM.BaseOffs == 0;
   1608   case 2:
   1609   case 3:
   1610     // reg + imm
   1611     if (AM.Scale == 0) {
   1612       return isImmUs2(AM.BaseOffs);
   1613     }
   1614     // reg + reg<<1
   1615     return AM.Scale == 2 && AM.BaseOffs == 0;
   1616   default:
   1617     // reg + imm
   1618     if (AM.Scale == 0) {
   1619       return isImmUs4(AM.BaseOffs);
   1620     }
   1621     // reg + reg<<2
   1622     return AM.Scale == 4 && AM.BaseOffs == 0;
   1623   }
   1624 }
   1625 
   1626 //===----------------------------------------------------------------------===//
   1627 //                           XCore Inline Assembly Support
   1628 //===----------------------------------------------------------------------===//
   1629 
   1630 std::pair<unsigned, const TargetRegisterClass*>
   1631 XCoreTargetLowering::
   1632 getRegForInlineAsmConstraint(const std::string &Constraint,
   1633                              EVT VT) const {
   1634   if (Constraint.size() == 1) {
   1635     switch (Constraint[0]) {
   1636     default : break;
   1637     case 'r':
   1638       return std::make_pair(0U, &XCore::GRRegsRegClass);
   1639     }
   1640   }
   1641   // Use the default implementation in TargetLowering to convert the register
   1642   // constraint into a member of a register class.
   1643   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
   1644 }
   1645