Home | History | Annotate | Download | only in MSP430
      1 //===-- MSP430ISelLowering.cpp - MSP430 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 MSP430TargetLowering class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #define DEBUG_TYPE "msp430-lower"
     15 
     16 #include "MSP430ISelLowering.h"
     17 #include "MSP430.h"
     18 #include "MSP430MachineFunctionInfo.h"
     19 #include "MSP430Subtarget.h"
     20 #include "MSP430TargetMachine.h"
     21 #include "llvm/CodeGen/CallingConvLower.h"
     22 #include "llvm/CodeGen/MachineFrameInfo.h"
     23 #include "llvm/CodeGen/MachineFunction.h"
     24 #include "llvm/CodeGen/MachineInstrBuilder.h"
     25 #include "llvm/CodeGen/MachineRegisterInfo.h"
     26 #include "llvm/CodeGen/SelectionDAGISel.h"
     27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
     28 #include "llvm/CodeGen/ValueTypes.h"
     29 #include "llvm/IR/CallingConv.h"
     30 #include "llvm/IR/DerivedTypes.h"
     31 #include "llvm/IR/Function.h"
     32 #include "llvm/IR/GlobalAlias.h"
     33 #include "llvm/IR/GlobalVariable.h"
     34 #include "llvm/IR/Intrinsics.h"
     35 #include "llvm/Support/CommandLine.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 typedef enum {
     42   NoHWMult,
     43   HWMultIntr,
     44   HWMultNoIntr
     45 } HWMultUseMode;
     46 
     47 static cl::opt<HWMultUseMode>
     48 HWMultMode("msp430-hwmult-mode",
     49            cl::desc("Hardware multiplier use mode"),
     50            cl::init(HWMultNoIntr),
     51            cl::values(
     52              clEnumValN(NoHWMult, "no",
     53                 "Do not use hardware multiplier"),
     54              clEnumValN(HWMultIntr, "interrupts",
     55                 "Assume hardware multiplier can be used inside interrupts"),
     56              clEnumValN(HWMultNoIntr, "use",
     57                 "Assume hardware multiplier cannot be used inside interrupts"),
     58              clEnumValEnd));
     59 
     60 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
     61   TargetLowering(tm, new TargetLoweringObjectFileELF()),
     62   Subtarget(*tm.getSubtargetImpl()) {
     63 
     64   TD = getDataLayout();
     65 
     66   // Set up the register classes.
     67   addRegisterClass(MVT::i8,  &MSP430::GR8RegClass);
     68   addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
     69 
     70   // Compute derived properties from the register classes
     71   computeRegisterProperties();
     72 
     73   // Provide all sorts of operation actions
     74 
     75   // Division is expensive
     76   setIntDivIsCheap(false);
     77 
     78   setStackPointerRegisterToSaveRestore(MSP430::SPW);
     79   setBooleanContents(ZeroOrOneBooleanContent);
     80   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
     81 
     82   // We have post-incremented loads / stores.
     83   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
     84   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
     85 
     86   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
     87   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
     88   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
     89   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
     90   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
     91 
     92   // We don't have any truncstores
     93   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
     94 
     95   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
     96   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
     97   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
     98   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
     99   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
    100   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
    101   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
    102   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
    103   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
    104   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
    105   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
    106   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
    107   setOperationAction(ISD::BlockAddress,     MVT::i16,   Custom);
    108   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
    109   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
    110   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
    111   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
    112   setOperationAction(ISD::SETCC,            MVT::i8,    Custom);
    113   setOperationAction(ISD::SETCC,            MVT::i16,   Custom);
    114   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
    115   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
    116   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
    117   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
    118   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
    119   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
    120   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
    121 
    122   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
    123   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
    124   setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i8,    Expand);
    125   setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i16,   Expand);
    126   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
    127   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
    128   setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i8,    Expand);
    129   setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i16,   Expand);
    130   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
    131   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
    132 
    133   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
    134   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
    135   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
    136   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
    137   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
    138   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
    139 
    140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
    141 
    142   // FIXME: Implement efficiently multiplication by a constant
    143   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
    144   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
    145   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
    146   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
    147   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
    148   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
    149   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
    150   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
    151   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
    152   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
    153 
    154   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
    155   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
    156   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
    157   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
    158   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
    159   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
    160   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
    161   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
    162   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
    163   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
    164   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
    165   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
    166 
    167   // varargs support
    168   setOperationAction(ISD::VASTART,          MVT::Other, Custom);
    169   setOperationAction(ISD::VAARG,            MVT::Other, Expand);
    170   setOperationAction(ISD::VAEND,            MVT::Other, Expand);
    171   setOperationAction(ISD::VACOPY,           MVT::Other, Expand);
    172 
    173   // Libcalls names.
    174   if (HWMultMode == HWMultIntr) {
    175     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
    176     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
    177   } else if (HWMultMode == HWMultNoIntr) {
    178     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
    179     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
    180   }
    181 
    182   setMinFunctionAlignment(1);
    183   setPrefFunctionAlignment(2);
    184 }
    185 
    186 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
    187                                              SelectionDAG &DAG) const {
    188   switch (Op.getOpcode()) {
    189   case ISD::SHL: // FALLTHROUGH
    190   case ISD::SRL:
    191   case ISD::SRA:              return LowerShifts(Op, DAG);
    192   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
    193   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
    194   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
    195   case ISD::SETCC:            return LowerSETCC(Op, DAG);
    196   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
    197   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
    198   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
    199   case ISD::RETURNADDR:       return LowerRETURNADDR(Op, DAG);
    200   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
    201   case ISD::VASTART:          return LowerVASTART(Op, DAG);
    202   default:
    203     llvm_unreachable("unimplemented operand");
    204   }
    205 }
    206 
    207 //===----------------------------------------------------------------------===//
    208 //                       MSP430 Inline Assembly Support
    209 //===----------------------------------------------------------------------===//
    210 
    211 /// getConstraintType - Given a constraint letter, return the type of
    212 /// constraint it is for this target.
    213 TargetLowering::ConstraintType
    214 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
    215   if (Constraint.size() == 1) {
    216     switch (Constraint[0]) {
    217     case 'r':
    218       return C_RegisterClass;
    219     default:
    220       break;
    221     }
    222   }
    223   return TargetLowering::getConstraintType(Constraint);
    224 }
    225 
    226 std::pair<unsigned, const TargetRegisterClass*>
    227 MSP430TargetLowering::
    228 getRegForInlineAsmConstraint(const std::string &Constraint,
    229                              EVT VT) const {
    230   if (Constraint.size() == 1) {
    231     // GCC Constraint Letters
    232     switch (Constraint[0]) {
    233     default: break;
    234     case 'r':   // GENERAL_REGS
    235       if (VT == MVT::i8)
    236         return std::make_pair(0U, &MSP430::GR8RegClass);
    237 
    238       return std::make_pair(0U, &MSP430::GR16RegClass);
    239     }
    240   }
    241 
    242   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
    243 }
    244 
    245 //===----------------------------------------------------------------------===//
    246 //                      Calling Convention Implementation
    247 //===----------------------------------------------------------------------===//
    248 
    249 #include "MSP430GenCallingConv.inc"
    250 
    251 SDValue
    252 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
    253                                            CallingConv::ID CallConv,
    254                                            bool isVarArg,
    255                                            const SmallVectorImpl<ISD::InputArg>
    256                                              &Ins,
    257                                            DebugLoc dl,
    258                                            SelectionDAG &DAG,
    259                                            SmallVectorImpl<SDValue> &InVals)
    260                                              const {
    261 
    262   switch (CallConv) {
    263   default:
    264     llvm_unreachable("Unsupported calling convention");
    265   case CallingConv::C:
    266   case CallingConv::Fast:
    267     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
    268   case CallingConv::MSP430_INTR:
    269     if (Ins.empty())
    270       return Chain;
    271     report_fatal_error("ISRs cannot have arguments");
    272   }
    273 }
    274 
    275 SDValue
    276 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
    277                                 SmallVectorImpl<SDValue> &InVals) const {
    278   SelectionDAG &DAG                     = CLI.DAG;
    279   DebugLoc &dl                          = CLI.DL;
    280   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
    281   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
    282   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
    283   SDValue Chain                         = CLI.Chain;
    284   SDValue Callee                        = CLI.Callee;
    285   bool &isTailCall                      = CLI.IsTailCall;
    286   CallingConv::ID CallConv              = CLI.CallConv;
    287   bool isVarArg                         = CLI.IsVarArg;
    288 
    289   // MSP430 target does not yet support tail call optimization.
    290   isTailCall = false;
    291 
    292   switch (CallConv) {
    293   default:
    294     llvm_unreachable("Unsupported calling convention");
    295   case CallingConv::Fast:
    296   case CallingConv::C:
    297     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
    298                           Outs, OutVals, Ins, dl, DAG, InVals);
    299   case CallingConv::MSP430_INTR:
    300     report_fatal_error("ISRs cannot be called directly");
    301   }
    302 }
    303 
    304 /// LowerCCCArguments - transform physical registers into virtual registers and
    305 /// generate load operations for arguments places on the stack.
    306 // FIXME: struct return stuff
    307 SDValue
    308 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
    309                                         CallingConv::ID CallConv,
    310                                         bool isVarArg,
    311                                         const SmallVectorImpl<ISD::InputArg>
    312                                           &Ins,
    313                                         DebugLoc dl,
    314                                         SelectionDAG &DAG,
    315                                         SmallVectorImpl<SDValue> &InVals)
    316                                           const {
    317   MachineFunction &MF = DAG.getMachineFunction();
    318   MachineFrameInfo *MFI = MF.getFrameInfo();
    319   MachineRegisterInfo &RegInfo = MF.getRegInfo();
    320   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
    321 
    322   // Assign locations to all of the incoming arguments.
    323   SmallVector<CCValAssign, 16> ArgLocs;
    324   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    325                  getTargetMachine(), ArgLocs, *DAG.getContext());
    326   CCInfo.AnalyzeFormalArguments(Ins, CC_MSP430);
    327 
    328   // Create frame index for the start of the first vararg value
    329   if (isVarArg) {
    330     unsigned Offset = CCInfo.getNextStackOffset();
    331     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, Offset, true));
    332   }
    333 
    334   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    335     CCValAssign &VA = ArgLocs[i];
    336     if (VA.isRegLoc()) {
    337       // Arguments passed in registers
    338       EVT RegVT = VA.getLocVT();
    339       switch (RegVT.getSimpleVT().SimpleTy) {
    340       default:
    341         {
    342 #ifndef NDEBUG
    343           errs() << "LowerFormalArguments Unhandled argument type: "
    344                << RegVT.getSimpleVT().SimpleTy << "\n";
    345 #endif
    346           llvm_unreachable(0);
    347         }
    348       case MVT::i16:
    349         unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
    350         RegInfo.addLiveIn(VA.getLocReg(), VReg);
    351         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
    352 
    353         // If this is an 8-bit value, it is really passed promoted to 16
    354         // bits. Insert an assert[sz]ext to capture this, then truncate to the
    355         // right size.
    356         if (VA.getLocInfo() == CCValAssign::SExt)
    357           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
    358                                  DAG.getValueType(VA.getValVT()));
    359         else if (VA.getLocInfo() == CCValAssign::ZExt)
    360           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
    361                                  DAG.getValueType(VA.getValVT()));
    362 
    363         if (VA.getLocInfo() != CCValAssign::Full)
    364           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
    365 
    366         InVals.push_back(ArgValue);
    367       }
    368     } else {
    369       // Sanity check
    370       assert(VA.isMemLoc());
    371 
    372       SDValue InVal;
    373       ISD::ArgFlagsTy Flags = Ins[i].Flags;
    374 
    375       if (Flags.isByVal()) {
    376         int FI = MFI->CreateFixedObject(Flags.getByValSize(),
    377                                         VA.getLocMemOffset(), true);
    378         InVal = DAG.getFrameIndex(FI, getPointerTy());
    379       } else {
    380         // Load the argument to a virtual register
    381         unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
    382         if (ObjSize > 2) {
    383             errs() << "LowerFormalArguments Unhandled argument type: "
    384                 << EVT(VA.getLocVT()).getEVTString()
    385                 << "\n";
    386         }
    387         // Create the frame index object for this incoming parameter...
    388         int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
    389 
    390         // Create the SelectionDAG nodes corresponding to a load
    391         //from this parameter
    392         SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
    393         InVal = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
    394                             MachinePointerInfo::getFixedStack(FI),
    395                             false, false, false, 0);
    396       }
    397 
    398       InVals.push_back(InVal);
    399     }
    400   }
    401 
    402   return Chain;
    403 }
    404 
    405 SDValue
    406 MSP430TargetLowering::LowerReturn(SDValue Chain,
    407                                   CallingConv::ID CallConv, bool isVarArg,
    408                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
    409                                   const SmallVectorImpl<SDValue> &OutVals,
    410                                   DebugLoc dl, SelectionDAG &DAG) const {
    411 
    412   // CCValAssign - represent the assignment of the return value to a location
    413   SmallVector<CCValAssign, 16> RVLocs;
    414 
    415   // ISRs cannot return any value.
    416   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
    417     report_fatal_error("ISRs cannot return any value");
    418 
    419   // CCState - Info about the registers and stack slot.
    420   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    421                  getTargetMachine(), RVLocs, *DAG.getContext());
    422 
    423   // Analize return values.
    424   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
    425 
    426   SDValue Flag;
    427   SmallVector<SDValue, 4> RetOps(1, Chain);
    428 
    429   // Copy the result values into the output registers.
    430   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    431     CCValAssign &VA = RVLocs[i];
    432     assert(VA.isRegLoc() && "Can only return in registers!");
    433 
    434     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
    435                              OutVals[i], Flag);
    436 
    437     // Guarantee that all emitted copies are stuck together,
    438     // avoiding something bad.
    439     Flag = Chain.getValue(1);
    440     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    441   }
    442 
    443   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
    444                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
    445 
    446   RetOps[0] = Chain;  // Update chain.
    447 
    448   // Add the flag if we have it.
    449   if (Flag.getNode())
    450     RetOps.push_back(Flag);
    451 
    452   return DAG.getNode(Opc, dl, MVT::Other, &RetOps[0], RetOps.size());
    453 }
    454 
    455 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
    456 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
    457 /// TODO: sret.
    458 SDValue
    459 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
    460                                      CallingConv::ID CallConv, bool isVarArg,
    461                                      bool isTailCall,
    462                                      const SmallVectorImpl<ISD::OutputArg>
    463                                        &Outs,
    464                                      const SmallVectorImpl<SDValue> &OutVals,
    465                                      const SmallVectorImpl<ISD::InputArg> &Ins,
    466                                      DebugLoc dl, SelectionDAG &DAG,
    467                                      SmallVectorImpl<SDValue> &InVals) const {
    468   // Analyze operands of the call, assigning locations to each operand.
    469   SmallVector<CCValAssign, 16> ArgLocs;
    470   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    471                  getTargetMachine(), ArgLocs, *DAG.getContext());
    472 
    473   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
    474 
    475   // Get a count of how many bytes are to be pushed on the stack.
    476   unsigned NumBytes = CCInfo.getNextStackOffset();
    477 
    478   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
    479                                                       getPointerTy(), true));
    480 
    481   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
    482   SmallVector<SDValue, 12> MemOpChains;
    483   SDValue StackPtr;
    484 
    485   // Walk the register/memloc assignments, inserting copies/loads.
    486   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    487     CCValAssign &VA = ArgLocs[i];
    488 
    489     SDValue Arg = OutVals[i];
    490 
    491     // Promote the value if needed.
    492     switch (VA.getLocInfo()) {
    493       default: llvm_unreachable("Unknown loc info!");
    494       case CCValAssign::Full: break;
    495       case CCValAssign::SExt:
    496         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
    497         break;
    498       case CCValAssign::ZExt:
    499         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
    500         break;
    501       case CCValAssign::AExt:
    502         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
    503         break;
    504     }
    505 
    506     // Arguments that can be passed on register must be kept at RegsToPass
    507     // vector
    508     if (VA.isRegLoc()) {
    509       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
    510     } else {
    511       assert(VA.isMemLoc());
    512 
    513       if (StackPtr.getNode() == 0)
    514         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
    515 
    516       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
    517                                    StackPtr,
    518                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
    519 
    520       SDValue MemOp;
    521       ISD::ArgFlagsTy Flags = Outs[i].Flags;
    522 
    523       if (Flags.isByVal()) {
    524         SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i16);
    525         MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
    526                               Flags.getByValAlign(),
    527                               /*isVolatile*/false,
    528                               /*AlwaysInline=*/true,
    529                               MachinePointerInfo(),
    530                               MachinePointerInfo());
    531       } else {
    532         MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(),
    533                              false, false, 0);
    534       }
    535 
    536       MemOpChains.push_back(MemOp);
    537     }
    538   }
    539 
    540   // Transform all store nodes into one single node because all store nodes are
    541   // independent of each other.
    542   if (!MemOpChains.empty())
    543     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    544                         &MemOpChains[0], MemOpChains.size());
    545 
    546   // Build a sequence of copy-to-reg nodes chained together with token chain and
    547   // flag operands which copy the outgoing args into registers.  The InFlag in
    548   // necessary since all emitted instructions must be stuck together.
    549   SDValue InFlag;
    550   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
    551     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
    552                              RegsToPass[i].second, InFlag);
    553     InFlag = Chain.getValue(1);
    554   }
    555 
    556   // If the callee is a GlobalAddress node (quite common, every direct call is)
    557   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
    558   // Likewise ExternalSymbol -> TargetExternalSymbol.
    559   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
    560     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
    561   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
    562     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
    563 
    564   // Returns a chain & a flag for retval copy to use.
    565   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    566   SmallVector<SDValue, 8> Ops;
    567   Ops.push_back(Chain);
    568   Ops.push_back(Callee);
    569 
    570   // Add argument registers to the end of the list so that they are
    571   // known live into the call.
    572   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
    573     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
    574                                   RegsToPass[i].second.getValueType()));
    575 
    576   if (InFlag.getNode())
    577     Ops.push_back(InFlag);
    578 
    579   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
    580   InFlag = Chain.getValue(1);
    581 
    582   // Create the CALLSEQ_END node.
    583   Chain = DAG.getCALLSEQ_END(Chain,
    584                              DAG.getConstant(NumBytes, getPointerTy(), true),
    585                              DAG.getConstant(0, getPointerTy(), true),
    586                              InFlag);
    587   InFlag = Chain.getValue(1);
    588 
    589   // Handle result values, copying them out of physregs into vregs that we
    590   // return.
    591   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
    592                          DAG, InVals);
    593 }
    594 
    595 /// LowerCallResult - Lower the result values of a call into the
    596 /// appropriate copies out of appropriate physical registers.
    597 ///
    598 SDValue
    599 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
    600                                       CallingConv::ID CallConv, bool isVarArg,
    601                                       const SmallVectorImpl<ISD::InputArg> &Ins,
    602                                       DebugLoc dl, SelectionDAG &DAG,
    603                                       SmallVectorImpl<SDValue> &InVals) const {
    604 
    605   // Assign locations to each value returned by this call.
    606   SmallVector<CCValAssign, 16> RVLocs;
    607   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    608                  getTargetMachine(), RVLocs, *DAG.getContext());
    609 
    610   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
    611 
    612   // Copy all of the result registers out of their specified physreg.
    613   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    614     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
    615                                RVLocs[i].getValVT(), InFlag).getValue(1);
    616     InFlag = Chain.getValue(2);
    617     InVals.push_back(Chain.getValue(0));
    618   }
    619 
    620   return Chain;
    621 }
    622 
    623 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
    624                                           SelectionDAG &DAG) const {
    625   unsigned Opc = Op.getOpcode();
    626   SDNode* N = Op.getNode();
    627   EVT VT = Op.getValueType();
    628   DebugLoc dl = N->getDebugLoc();
    629 
    630   // Expand non-constant shifts to loops:
    631   if (!isa<ConstantSDNode>(N->getOperand(1)))
    632     switch (Opc) {
    633     default: llvm_unreachable("Invalid shift opcode!");
    634     case ISD::SHL:
    635       return DAG.getNode(MSP430ISD::SHL, dl,
    636                          VT, N->getOperand(0), N->getOperand(1));
    637     case ISD::SRA:
    638       return DAG.getNode(MSP430ISD::SRA, dl,
    639                          VT, N->getOperand(0), N->getOperand(1));
    640     case ISD::SRL:
    641       return DAG.getNode(MSP430ISD::SRL, dl,
    642                          VT, N->getOperand(0), N->getOperand(1));
    643     }
    644 
    645   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
    646 
    647   // Expand the stuff into sequence of shifts.
    648   // FIXME: for some shift amounts this might be done better!
    649   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
    650   SDValue Victim = N->getOperand(0);
    651 
    652   if (Opc == ISD::SRL && ShiftAmount) {
    653     // Emit a special goodness here:
    654     // srl A, 1 => clrc; rrc A
    655     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
    656     ShiftAmount -= 1;
    657   }
    658 
    659   while (ShiftAmount--)
    660     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
    661                          dl, VT, Victim);
    662 
    663   return Victim;
    664 }
    665 
    666 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
    667                                                  SelectionDAG &DAG) const {
    668   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    669   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
    670 
    671   // Create the TargetGlobalAddress node, folding in the constant offset.
    672   SDValue Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
    673                                               getPointerTy(), Offset);
    674   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
    675                      getPointerTy(), Result);
    676 }
    677 
    678 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
    679                                                   SelectionDAG &DAG) const {
    680   DebugLoc dl = Op.getDebugLoc();
    681   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
    682   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
    683 
    684   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
    685 }
    686 
    687 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
    688                                                 SelectionDAG &DAG) const {
    689   DebugLoc dl = Op.getDebugLoc();
    690   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
    691   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
    692 
    693   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
    694 }
    695 
    696 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
    697                        ISD::CondCode CC,
    698                        DebugLoc dl, SelectionDAG &DAG) {
    699   // FIXME: Handle bittests someday
    700   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
    701 
    702   // FIXME: Handle jump negative someday
    703   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
    704   switch (CC) {
    705   default: llvm_unreachable("Invalid integer condition!");
    706   case ISD::SETEQ:
    707     TCC = MSP430CC::COND_E;     // aka COND_Z
    708     // Minor optimization: if LHS is a constant, swap operands, then the
    709     // constant can be folded into comparison.
    710     if (LHS.getOpcode() == ISD::Constant)
    711       std::swap(LHS, RHS);
    712     break;
    713   case ISD::SETNE:
    714     TCC = MSP430CC::COND_NE;    // aka COND_NZ
    715     // Minor optimization: if LHS is a constant, swap operands, then the
    716     // constant can be folded into comparison.
    717     if (LHS.getOpcode() == ISD::Constant)
    718       std::swap(LHS, RHS);
    719     break;
    720   case ISD::SETULE:
    721     std::swap(LHS, RHS);        // FALLTHROUGH
    722   case ISD::SETUGE:
    723     // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
    724     // fold constant into instruction.
    725     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
    726       LHS = RHS;
    727       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
    728       TCC = MSP430CC::COND_LO;
    729       break;
    730     }
    731     TCC = MSP430CC::COND_HS;    // aka COND_C
    732     break;
    733   case ISD::SETUGT:
    734     std::swap(LHS, RHS);        // FALLTHROUGH
    735   case ISD::SETULT:
    736     // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
    737     // fold constant into instruction.
    738     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
    739       LHS = RHS;
    740       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
    741       TCC = MSP430CC::COND_HS;
    742       break;
    743     }
    744     TCC = MSP430CC::COND_LO;    // aka COND_NC
    745     break;
    746   case ISD::SETLE:
    747     std::swap(LHS, RHS);        // FALLTHROUGH
    748   case ISD::SETGE:
    749     // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
    750     // fold constant into instruction.
    751     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
    752       LHS = RHS;
    753       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
    754       TCC = MSP430CC::COND_L;
    755       break;
    756     }
    757     TCC = MSP430CC::COND_GE;
    758     break;
    759   case ISD::SETGT:
    760     std::swap(LHS, RHS);        // FALLTHROUGH
    761   case ISD::SETLT:
    762     // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
    763     // fold constant into instruction.
    764     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
    765       LHS = RHS;
    766       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
    767       TCC = MSP430CC::COND_GE;
    768       break;
    769     }
    770     TCC = MSP430CC::COND_L;
    771     break;
    772   }
    773 
    774   TargetCC = DAG.getConstant(TCC, MVT::i8);
    775   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
    776 }
    777 
    778 
    779 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
    780   SDValue Chain = Op.getOperand(0);
    781   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
    782   SDValue LHS   = Op.getOperand(2);
    783   SDValue RHS   = Op.getOperand(3);
    784   SDValue Dest  = Op.getOperand(4);
    785   DebugLoc dl   = Op.getDebugLoc();
    786 
    787   SDValue TargetCC;
    788   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
    789 
    790   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
    791                      Chain, Dest, TargetCC, Flag);
    792 }
    793 
    794 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
    795   SDValue LHS   = Op.getOperand(0);
    796   SDValue RHS   = Op.getOperand(1);
    797   DebugLoc dl   = Op.getDebugLoc();
    798 
    799   // If we are doing an AND and testing against zero, then the CMP
    800   // will not be generated.  The AND (or BIT) will generate the condition codes,
    801   // but they are different from CMP.
    802   // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
    803   // lowering & isel wouldn't diverge.
    804   bool andCC = false;
    805   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
    806     if (RHSC->isNullValue() && LHS.hasOneUse() &&
    807         (LHS.getOpcode() == ISD::AND ||
    808          (LHS.getOpcode() == ISD::TRUNCATE &&
    809           LHS.getOperand(0).getOpcode() == ISD::AND))) {
    810       andCC = true;
    811     }
    812   }
    813   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    814   SDValue TargetCC;
    815   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
    816 
    817   // Get the condition codes directly from the status register, if its easy.
    818   // Otherwise a branch will be generated.  Note that the AND and BIT
    819   // instructions generate different flags than CMP, the carry bit can be used
    820   // for NE/EQ.
    821   bool Invert = false;
    822   bool Shift = false;
    823   bool Convert = true;
    824   switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
    825    default:
    826     Convert = false;
    827     break;
    828    case MSP430CC::COND_HS:
    829      // Res = SRW & 1, no processing is required
    830      break;
    831    case MSP430CC::COND_LO:
    832      // Res = ~(SRW & 1)
    833      Invert = true;
    834      break;
    835    case MSP430CC::COND_NE:
    836      if (andCC) {
    837        // C = ~Z, thus Res = SRW & 1, no processing is required
    838      } else {
    839        // Res = ~((SRW >> 1) & 1)
    840        Shift = true;
    841        Invert = true;
    842      }
    843      break;
    844    case MSP430CC::COND_E:
    845      Shift = true;
    846      // C = ~Z for AND instruction, thus we can put Res = ~(SRW & 1), however,
    847      // Res = (SRW >> 1) & 1 is 1 word shorter.
    848      break;
    849   }
    850   EVT VT = Op.getValueType();
    851   SDValue One  = DAG.getConstant(1, VT);
    852   if (Convert) {
    853     SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SRW,
    854                                     MVT::i16, Flag);
    855     if (Shift)
    856       // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
    857       SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
    858     SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
    859     if (Invert)
    860       SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
    861     return SR;
    862   } else {
    863     SDValue Zero = DAG.getConstant(0, VT);
    864     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
    865     SmallVector<SDValue, 4> Ops;
    866     Ops.push_back(One);
    867     Ops.push_back(Zero);
    868     Ops.push_back(TargetCC);
    869     Ops.push_back(Flag);
    870     return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
    871   }
    872 }
    873 
    874 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
    875                                              SelectionDAG &DAG) const {
    876   SDValue LHS    = Op.getOperand(0);
    877   SDValue RHS    = Op.getOperand(1);
    878   SDValue TrueV  = Op.getOperand(2);
    879   SDValue FalseV = Op.getOperand(3);
    880   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    881   DebugLoc dl    = Op.getDebugLoc();
    882 
    883   SDValue TargetCC;
    884   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
    885 
    886   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
    887   SmallVector<SDValue, 4> Ops;
    888   Ops.push_back(TrueV);
    889   Ops.push_back(FalseV);
    890   Ops.push_back(TargetCC);
    891   Ops.push_back(Flag);
    892 
    893   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
    894 }
    895 
    896 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
    897                                                SelectionDAG &DAG) const {
    898   SDValue Val = Op.getOperand(0);
    899   EVT VT      = Op.getValueType();
    900   DebugLoc dl = Op.getDebugLoc();
    901 
    902   assert(VT == MVT::i16 && "Only support i16 for now!");
    903 
    904   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
    905                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
    906                      DAG.getValueType(Val.getValueType()));
    907 }
    908 
    909 SDValue
    910 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
    911   MachineFunction &MF = DAG.getMachineFunction();
    912   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
    913   int ReturnAddrIndex = FuncInfo->getRAIndex();
    914 
    915   if (ReturnAddrIndex == 0) {
    916     // Set up a frame object for the return address.
    917     uint64_t SlotSize = TD->getPointerSize();
    918     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
    919                                                            true);
    920     FuncInfo->setRAIndex(ReturnAddrIndex);
    921   }
    922 
    923   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
    924 }
    925 
    926 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
    927                                               SelectionDAG &DAG) const {
    928   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
    929   MFI->setReturnAddressIsTaken(true);
    930 
    931   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    932   DebugLoc dl = Op.getDebugLoc();
    933 
    934   if (Depth > 0) {
    935     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
    936     SDValue Offset =
    937       DAG.getConstant(TD->getPointerSize(), MVT::i16);
    938     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
    939                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
    940                                    FrameAddr, Offset),
    941                        MachinePointerInfo(), false, false, false, 0);
    942   }
    943 
    944   // Just load the return address.
    945   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
    946   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
    947                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
    948 }
    949 
    950 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
    951                                              SelectionDAG &DAG) const {
    952   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
    953   MFI->setFrameAddressIsTaken(true);
    954 
    955   EVT VT = Op.getValueType();
    956   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
    957   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    958   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
    959                                          MSP430::FPW, VT);
    960   while (Depth--)
    961     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
    962                             MachinePointerInfo(),
    963                             false, false, false, 0);
    964   return FrameAddr;
    965 }
    966 
    967 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
    968                                            SelectionDAG &DAG) const {
    969   MachineFunction &MF = DAG.getMachineFunction();
    970   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
    971 
    972   // Frame index of first vararg argument
    973   SDValue FrameIndex = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
    974                                          getPointerTy());
    975   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    976 
    977   // Create a store of the frame index to the location operand
    978   return DAG.getStore(Op.getOperand(0), Op.getDebugLoc(), FrameIndex,
    979                       Op.getOperand(1), MachinePointerInfo(SV),
    980                       false, false, 0);
    981 }
    982 
    983 /// getPostIndexedAddressParts - returns true by value, base pointer and
    984 /// offset pointer and addressing mode by reference if this node can be
    985 /// combined with a load / store to form a post-indexed load / store.
    986 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
    987                                                       SDValue &Base,
    988                                                       SDValue &Offset,
    989                                                       ISD::MemIndexedMode &AM,
    990                                                       SelectionDAG &DAG) const {
    991 
    992   LoadSDNode *LD = cast<LoadSDNode>(N);
    993   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
    994     return false;
    995 
    996   EVT VT = LD->getMemoryVT();
    997   if (VT != MVT::i8 && VT != MVT::i16)
    998     return false;
    999 
   1000   if (Op->getOpcode() != ISD::ADD)
   1001     return false;
   1002 
   1003   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
   1004     uint64_t RHSC = RHS->getZExtValue();
   1005     if ((VT == MVT::i16 && RHSC != 2) ||
   1006         (VT == MVT::i8 && RHSC != 1))
   1007       return false;
   1008 
   1009     Base = Op->getOperand(0);
   1010     Offset = DAG.getConstant(RHSC, VT);
   1011     AM = ISD::POST_INC;
   1012     return true;
   1013   }
   1014 
   1015   return false;
   1016 }
   1017 
   1018 
   1019 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
   1020   switch (Opcode) {
   1021   default: return NULL;
   1022   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
   1023   case MSP430ISD::RETI_FLAG:          return "MSP430ISD::RETI_FLAG";
   1024   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
   1025   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
   1026   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
   1027   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
   1028   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
   1029   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
   1030   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
   1031   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
   1032   case MSP430ISD::SHL:                return "MSP430ISD::SHL";
   1033   case MSP430ISD::SRA:                return "MSP430ISD::SRA";
   1034   }
   1035 }
   1036 
   1037 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
   1038                                           Type *Ty2) const {
   1039   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
   1040     return false;
   1041 
   1042   return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
   1043 }
   1044 
   1045 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
   1046   if (!VT1.isInteger() || !VT2.isInteger())
   1047     return false;
   1048 
   1049   return (VT1.getSizeInBits() > VT2.getSizeInBits());
   1050 }
   1051 
   1052 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
   1053   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
   1054   return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
   1055 }
   1056 
   1057 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
   1058   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
   1059   return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
   1060 }
   1061 
   1062 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
   1063   return isZExtFree(Val.getValueType(), VT2);
   1064 }
   1065 
   1066 //===----------------------------------------------------------------------===//
   1067 //  Other Lowering Code
   1068 //===----------------------------------------------------------------------===//
   1069 
   1070 MachineBasicBlock*
   1071 MSP430TargetLowering::EmitShiftInstr(MachineInstr *MI,
   1072                                      MachineBasicBlock *BB) const {
   1073   MachineFunction *F = BB->getParent();
   1074   MachineRegisterInfo &RI = F->getRegInfo();
   1075   DebugLoc dl = MI->getDebugLoc();
   1076   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
   1077 
   1078   unsigned Opc;
   1079   const TargetRegisterClass * RC;
   1080   switch (MI->getOpcode()) {
   1081   default: llvm_unreachable("Invalid shift opcode!");
   1082   case MSP430::Shl8:
   1083    Opc = MSP430::SHL8r1;
   1084    RC = &MSP430::GR8RegClass;
   1085    break;
   1086   case MSP430::Shl16:
   1087    Opc = MSP430::SHL16r1;
   1088    RC = &MSP430::GR16RegClass;
   1089    break;
   1090   case MSP430::Sra8:
   1091    Opc = MSP430::SAR8r1;
   1092    RC = &MSP430::GR8RegClass;
   1093    break;
   1094   case MSP430::Sra16:
   1095    Opc = MSP430::SAR16r1;
   1096    RC = &MSP430::GR16RegClass;
   1097    break;
   1098   case MSP430::Srl8:
   1099    Opc = MSP430::SAR8r1c;
   1100    RC = &MSP430::GR8RegClass;
   1101    break;
   1102   case MSP430::Srl16:
   1103    Opc = MSP430::SAR16r1c;
   1104    RC = &MSP430::GR16RegClass;
   1105    break;
   1106   }
   1107 
   1108   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   1109   MachineFunction::iterator I = BB;
   1110   ++I;
   1111 
   1112   // Create loop block
   1113   MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
   1114   MachineBasicBlock *RemBB  = F->CreateMachineBasicBlock(LLVM_BB);
   1115 
   1116   F->insert(I, LoopBB);
   1117   F->insert(I, RemBB);
   1118 
   1119   // Update machine-CFG edges by transferring all successors of the current
   1120   // block to the block containing instructions after shift.
   1121   RemBB->splice(RemBB->begin(), BB,
   1122                 llvm::next(MachineBasicBlock::iterator(MI)),
   1123                 BB->end());
   1124   RemBB->transferSuccessorsAndUpdatePHIs(BB);
   1125 
   1126   // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
   1127   BB->addSuccessor(LoopBB);
   1128   BB->addSuccessor(RemBB);
   1129   LoopBB->addSuccessor(RemBB);
   1130   LoopBB->addSuccessor(LoopBB);
   1131 
   1132   unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
   1133   unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
   1134   unsigned ShiftReg = RI.createVirtualRegister(RC);
   1135   unsigned ShiftReg2 = RI.createVirtualRegister(RC);
   1136   unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg();
   1137   unsigned SrcReg = MI->getOperand(1).getReg();
   1138   unsigned DstReg = MI->getOperand(0).getReg();
   1139 
   1140   // BB:
   1141   // cmp 0, N
   1142   // je RemBB
   1143   BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
   1144     .addReg(ShiftAmtSrcReg).addImm(0);
   1145   BuildMI(BB, dl, TII.get(MSP430::JCC))
   1146     .addMBB(RemBB)
   1147     .addImm(MSP430CC::COND_E);
   1148 
   1149   // LoopBB:
   1150   // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
   1151   // ShiftAmt = phi [%N, BB],      [%ShiftAmt2, LoopBB]
   1152   // ShiftReg2 = shift ShiftReg
   1153   // ShiftAmt2 = ShiftAmt - 1;
   1154   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
   1155     .addReg(SrcReg).addMBB(BB)
   1156     .addReg(ShiftReg2).addMBB(LoopBB);
   1157   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
   1158     .addReg(ShiftAmtSrcReg).addMBB(BB)
   1159     .addReg(ShiftAmtReg2).addMBB(LoopBB);
   1160   BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
   1161     .addReg(ShiftReg);
   1162   BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
   1163     .addReg(ShiftAmtReg).addImm(1);
   1164   BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
   1165     .addMBB(LoopBB)
   1166     .addImm(MSP430CC::COND_NE);
   1167 
   1168   // RemBB:
   1169   // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
   1170   BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
   1171     .addReg(SrcReg).addMBB(BB)
   1172     .addReg(ShiftReg2).addMBB(LoopBB);
   1173 
   1174   MI->eraseFromParent();   // The pseudo instruction is gone now.
   1175   return RemBB;
   1176 }
   1177 
   1178 MachineBasicBlock*
   1179 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
   1180                                                   MachineBasicBlock *BB) const {
   1181   unsigned Opc = MI->getOpcode();
   1182 
   1183   if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
   1184       Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
   1185       Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
   1186     return EmitShiftInstr(MI, BB);
   1187 
   1188   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
   1189   DebugLoc dl = MI->getDebugLoc();
   1190 
   1191   assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
   1192          "Unexpected instr type to insert");
   1193 
   1194   // To "insert" a SELECT instruction, we actually have to insert the diamond
   1195   // control-flow pattern.  The incoming instruction knows the destination vreg
   1196   // to set, the condition code register to branch on, the true/false values to
   1197   // select between, and a branch opcode to use.
   1198   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   1199   MachineFunction::iterator I = BB;
   1200   ++I;
   1201 
   1202   //  thisMBB:
   1203   //  ...
   1204   //   TrueVal = ...
   1205   //   cmpTY ccX, r1, r2
   1206   //   jCC copy1MBB
   1207   //   fallthrough --> copy0MBB
   1208   MachineBasicBlock *thisMBB = BB;
   1209   MachineFunction *F = BB->getParent();
   1210   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
   1211   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
   1212   F->insert(I, copy0MBB);
   1213   F->insert(I, copy1MBB);
   1214   // Update machine-CFG edges by transferring all successors of the current
   1215   // block to the new block which will contain the Phi node for the select.
   1216   copy1MBB->splice(copy1MBB->begin(), BB,
   1217                    llvm::next(MachineBasicBlock::iterator(MI)),
   1218                    BB->end());
   1219   copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
   1220   // Next, add the true and fallthrough blocks as its successors.
   1221   BB->addSuccessor(copy0MBB);
   1222   BB->addSuccessor(copy1MBB);
   1223 
   1224   BuildMI(BB, dl, TII.get(MSP430::JCC))
   1225     .addMBB(copy1MBB)
   1226     .addImm(MI->getOperand(3).getImm());
   1227 
   1228   //  copy0MBB:
   1229   //   %FalseValue = ...
   1230   //   # fallthrough to copy1MBB
   1231   BB = copy0MBB;
   1232 
   1233   // Update machine-CFG edges
   1234   BB->addSuccessor(copy1MBB);
   1235 
   1236   //  copy1MBB:
   1237   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
   1238   //  ...
   1239   BB = copy1MBB;
   1240   BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI),
   1241           MI->getOperand(0).getReg())
   1242     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
   1243     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
   1244 
   1245   MI->eraseFromParent();   // The pseudo instruction is gone now.
   1246   return BB;
   1247 }
   1248