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 #include "MSP430ISelLowering.h"
15 #include "MSP430.h"
16 #include "MSP430MachineFunctionInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "msp430-lower"
40 
41 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
42                                            const MSP430Subtarget &STI)
43     : TargetLowering(TM) {
44 
45   // Set up the register classes.
46   addRegisterClass(MVT::i8,  &MSP430::GR8RegClass);
47   addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
48 
49   // Compute derived properties from the register classes
50   computeRegisterProperties(STI.getRegisterInfo());
51 
52   // Provide all sorts of operation actions
53   setStackPointerRegisterToSaveRestore(MSP430::SP);
54   setBooleanContents(ZeroOrOneBooleanContent);
55   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
56 
57   // We have post-incremented loads / stores.
58   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
59   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
60 
61   for (MVT VT : MVT::integer_valuetypes()) {
62     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
63     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
64     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
65     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8,  Expand);
66     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
67   }
68 
69   // We don't have any truncstores
70   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
71 
72   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
73   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
74   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
75   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
76   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
77   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
78   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
79   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
80   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
81   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
82   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
83   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
84   setOperationAction(ISD::BlockAddress,     MVT::i16,   Custom);
85   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
86   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
87   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
88   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
89   setOperationAction(ISD::SETCC,            MVT::i8,    Custom);
90   setOperationAction(ISD::SETCC,            MVT::i16,   Custom);
91   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
92   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
93   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
94   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
95   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
96   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
97   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
98 
99   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
100   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
101   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
102   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
103   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
104   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
105 
106   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
107   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
108   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
109   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
110   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
111   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
112 
113   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
114 
115   // FIXME: Implement efficiently multiplication by a constant
116   setOperationAction(ISD::MUL,              MVT::i8,    Promote);
117   setOperationAction(ISD::MULHS,            MVT::i8,    Promote);
118   setOperationAction(ISD::MULHU,            MVT::i8,    Promote);
119   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Promote);
120   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Promote);
121   setOperationAction(ISD::MUL,              MVT::i16,   LibCall);
122   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
123   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
124   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
125   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
126 
127   setOperationAction(ISD::UDIV,             MVT::i8,    Promote);
128   setOperationAction(ISD::UDIVREM,          MVT::i8,    Promote);
129   setOperationAction(ISD::UREM,             MVT::i8,    Promote);
130   setOperationAction(ISD::SDIV,             MVT::i8,    Promote);
131   setOperationAction(ISD::SDIVREM,          MVT::i8,    Promote);
132   setOperationAction(ISD::SREM,             MVT::i8,    Promote);
133   setOperationAction(ISD::UDIV,             MVT::i16,   LibCall);
134   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
135   setOperationAction(ISD::UREM,             MVT::i16,   LibCall);
136   setOperationAction(ISD::SDIV,             MVT::i16,   LibCall);
137   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
138   setOperationAction(ISD::SREM,             MVT::i16,   LibCall);
139 
140   // varargs support
141   setOperationAction(ISD::VASTART,          MVT::Other, Custom);
142   setOperationAction(ISD::VAARG,            MVT::Other, Expand);
143   setOperationAction(ISD::VAEND,            MVT::Other, Expand);
144   setOperationAction(ISD::VACOPY,           MVT::Other, Expand);
145   setOperationAction(ISD::JumpTable,        MVT::i16,   Custom);
146 
147   // EABI Libcalls - EABI Section 6.2
148   const struct {
149     const RTLIB::Libcall Op;
150     const char * const Name;
151     const ISD::CondCode Cond;
152   } LibraryCalls[] = {
153     // Floating point conversions - EABI Table 6
154     { RTLIB::FPROUND_F64_F32,   "__mspabi_cvtdf",   ISD::SETCC_INVALID },
155     { RTLIB::FPEXT_F32_F64,     "__mspabi_cvtfd",   ISD::SETCC_INVALID },
156     // The following is NOT implemented in libgcc
157     //{ RTLIB::FPTOSINT_F64_I16,  "__mspabi_fixdi", ISD::SETCC_INVALID },
158     { RTLIB::FPTOSINT_F64_I32,  "__mspabi_fixdli",  ISD::SETCC_INVALID },
159     { RTLIB::FPTOSINT_F64_I64,  "__mspabi_fixdlli", ISD::SETCC_INVALID },
160     // The following is NOT implemented in libgcc
161     //{ RTLIB::FPTOUINT_F64_I16,  "__mspabi_fixdu", ISD::SETCC_INVALID },
162     { RTLIB::FPTOUINT_F64_I32,  "__mspabi_fixdul",  ISD::SETCC_INVALID },
163     { RTLIB::FPTOUINT_F64_I64,  "__mspabi_fixdull", ISD::SETCC_INVALID },
164     // The following is NOT implemented in libgcc
165     //{ RTLIB::FPTOSINT_F32_I16,  "__mspabi_fixfi", ISD::SETCC_INVALID },
166     { RTLIB::FPTOSINT_F32_I32,  "__mspabi_fixfli",  ISD::SETCC_INVALID },
167     { RTLIB::FPTOSINT_F32_I64,  "__mspabi_fixflli", ISD::SETCC_INVALID },
168     // The following is NOT implemented in libgcc
169     //{ RTLIB::FPTOUINT_F32_I16,  "__mspabi_fixfu", ISD::SETCC_INVALID },
170     { RTLIB::FPTOUINT_F32_I32,  "__mspabi_fixful",  ISD::SETCC_INVALID },
171     { RTLIB::FPTOUINT_F32_I64,  "__mspabi_fixfull", ISD::SETCC_INVALID },
172     // TODO The following IS implemented in libgcc
173     //{ RTLIB::SINTTOFP_I16_F64,  "__mspabi_fltid", ISD::SETCC_INVALID },
174     { RTLIB::SINTTOFP_I32_F64,  "__mspabi_fltlid",  ISD::SETCC_INVALID },
175     // TODO The following IS implemented in libgcc but is not in the EABI
176     { RTLIB::SINTTOFP_I64_F64,  "__mspabi_fltllid", ISD::SETCC_INVALID },
177     // TODO The following IS implemented in libgcc
178     //{ RTLIB::UINTTOFP_I16_F64,  "__mspabi_fltud", ISD::SETCC_INVALID },
179     { RTLIB::UINTTOFP_I32_F64,  "__mspabi_fltuld",  ISD::SETCC_INVALID },
180     // The following IS implemented in libgcc but is not in the EABI
181     { RTLIB::UINTTOFP_I64_F64,  "__mspabi_fltulld", ISD::SETCC_INVALID },
182     // TODO The following IS implemented in libgcc
183     //{ RTLIB::SINTTOFP_I16_F32,  "__mspabi_fltif", ISD::SETCC_INVALID },
184     { RTLIB::SINTTOFP_I32_F32,  "__mspabi_fltlif",  ISD::SETCC_INVALID },
185     // TODO The following IS implemented in libgcc but is not in the EABI
186     { RTLIB::SINTTOFP_I64_F32,  "__mspabi_fltllif", ISD::SETCC_INVALID },
187     // TODO The following IS implemented in libgcc
188     //{ RTLIB::UINTTOFP_I16_F32,  "__mspabi_fltuf", ISD::SETCC_INVALID },
189     { RTLIB::UINTTOFP_I32_F32,  "__mspabi_fltulf",  ISD::SETCC_INVALID },
190     // The following IS implemented in libgcc but is not in the EABI
191     { RTLIB::UINTTOFP_I64_F32,  "__mspabi_fltullf", ISD::SETCC_INVALID },
192 
193     // Floating point comparisons - EABI Table 7
194     { RTLIB::OEQ_F64, "__mspabi_cmpd", ISD::SETEQ },
195     { RTLIB::UNE_F64, "__mspabi_cmpd", ISD::SETNE },
196     { RTLIB::OGE_F64, "__mspabi_cmpd", ISD::SETGE },
197     { RTLIB::OLT_F64, "__mspabi_cmpd", ISD::SETLT },
198     { RTLIB::OLE_F64, "__mspabi_cmpd", ISD::SETLE },
199     { RTLIB::OGT_F64, "__mspabi_cmpd", ISD::SETGT },
200     { RTLIB::OEQ_F32, "__mspabi_cmpf", ISD::SETEQ },
201     { RTLIB::UNE_F32, "__mspabi_cmpf", ISD::SETNE },
202     { RTLIB::OGE_F32, "__mspabi_cmpf", ISD::SETGE },
203     { RTLIB::OLT_F32, "__mspabi_cmpf", ISD::SETLT },
204     { RTLIB::OLE_F32, "__mspabi_cmpf", ISD::SETLE },
205     { RTLIB::OGT_F32, "__mspabi_cmpf", ISD::SETGT },
206 
207     // Floating point arithmetic - EABI Table 8
208     { RTLIB::ADD_F64,  "__mspabi_addd", ISD::SETCC_INVALID },
209     { RTLIB::ADD_F32,  "__mspabi_addf", ISD::SETCC_INVALID },
210     { RTLIB::DIV_F64,  "__mspabi_divd", ISD::SETCC_INVALID },
211     { RTLIB::DIV_F32,  "__mspabi_divf", ISD::SETCC_INVALID },
212     { RTLIB::MUL_F64,  "__mspabi_mpyd", ISD::SETCC_INVALID },
213     { RTLIB::MUL_F32,  "__mspabi_mpyf", ISD::SETCC_INVALID },
214     { RTLIB::SUB_F64,  "__mspabi_subd", ISD::SETCC_INVALID },
215     { RTLIB::SUB_F32,  "__mspabi_subf", ISD::SETCC_INVALID },
216     // The following are NOT implemented in libgcc
217     // { RTLIB::NEG_F64,  "__mspabi_negd", ISD::SETCC_INVALID },
218     // { RTLIB::NEG_F32,  "__mspabi_negf", ISD::SETCC_INVALID },
219 
220     // Universal Integer Operations - EABI Table 9
221     { RTLIB::SDIV_I16,   "__mspabi_divi", ISD::SETCC_INVALID },
222     { RTLIB::SDIV_I32,   "__mspabi_divli", ISD::SETCC_INVALID },
223     { RTLIB::SDIV_I64,   "__mspabi_divlli", ISD::SETCC_INVALID },
224     { RTLIB::UDIV_I16,   "__mspabi_divu", ISD::SETCC_INVALID },
225     { RTLIB::UDIV_I32,   "__mspabi_divul", ISD::SETCC_INVALID },
226     { RTLIB::UDIV_I64,   "__mspabi_divull", ISD::SETCC_INVALID },
227     { RTLIB::SREM_I16,   "__mspabi_remi", ISD::SETCC_INVALID },
228     { RTLIB::SREM_I32,   "__mspabi_remli", ISD::SETCC_INVALID },
229     { RTLIB::SREM_I64,   "__mspabi_remlli", ISD::SETCC_INVALID },
230     { RTLIB::UREM_I16,   "__mspabi_remu", ISD::SETCC_INVALID },
231     { RTLIB::UREM_I32,   "__mspabi_remul", ISD::SETCC_INVALID },
232     { RTLIB::UREM_I64,   "__mspabi_remull", ISD::SETCC_INVALID },
233 
234     // Bitwise Operations - EABI Table 10
235     // TODO: __mspabi_[srli/srai/slli] ARE implemented in libgcc
236     { RTLIB::SRL_I32,    "__mspabi_srll", ISD::SETCC_INVALID },
237     { RTLIB::SRA_I32,    "__mspabi_sral", ISD::SETCC_INVALID },
238     { RTLIB::SHL_I32,    "__mspabi_slll", ISD::SETCC_INVALID },
239     // __mspabi_[srlll/srall/sllll/rlli/rlll] are NOT implemented in libgcc
240 
241   };
242 
243   for (const auto &LC : LibraryCalls) {
244     setLibcallName(LC.Op, LC.Name);
245     if (LC.Cond != ISD::SETCC_INVALID)
246       setCmpLibcallCC(LC.Op, LC.Cond);
247   }
248 
249   if (STI.hasHWMult16()) {
250     const struct {
251       const RTLIB::Libcall Op;
252       const char * const Name;
253     } LibraryCalls[] = {
254       // Integer Multiply - EABI Table 9
255       { RTLIB::MUL_I16,   "__mspabi_mpyi_hw" },
256       { RTLIB::MUL_I32,   "__mspabi_mpyl_hw" },
257       { RTLIB::MUL_I64,   "__mspabi_mpyll_hw" },
258       // TODO The __mspabi_mpysl*_hw functions ARE implemented in libgcc
259       // TODO The __mspabi_mpyul*_hw functions ARE implemented in libgcc
260     };
261     for (const auto &LC : LibraryCalls) {
262       setLibcallName(LC.Op, LC.Name);
263     }
264   } else if (STI.hasHWMult32()) {
265     const struct {
266       const RTLIB::Libcall Op;
267       const char * const Name;
268     } LibraryCalls[] = {
269       // Integer Multiply - EABI Table 9
270       { RTLIB::MUL_I16,   "__mspabi_mpyi_hw" },
271       { RTLIB::MUL_I32,   "__mspabi_mpyl_hw32" },
272       { RTLIB::MUL_I64,   "__mspabi_mpyll_hw32" },
273       // TODO The __mspabi_mpysl*_hw32 functions ARE implemented in libgcc
274       // TODO The __mspabi_mpyul*_hw32 functions ARE implemented in libgcc
275     };
276     for (const auto &LC : LibraryCalls) {
277       setLibcallName(LC.Op, LC.Name);
278     }
279   } else if (STI.hasHWMultF5()) {
280     const struct {
281       const RTLIB::Libcall Op;
282       const char * const Name;
283     } LibraryCalls[] = {
284       // Integer Multiply - EABI Table 9
285       { RTLIB::MUL_I16,   "__mspabi_mpyi_f5hw" },
286       { RTLIB::MUL_I32,   "__mspabi_mpyl_f5hw" },
287       { RTLIB::MUL_I64,   "__mspabi_mpyll_f5hw" },
288       // TODO The __mspabi_mpysl*_f5hw functions ARE implemented in libgcc
289       // TODO The __mspabi_mpyul*_f5hw functions ARE implemented in libgcc
290     };
291     for (const auto &LC : LibraryCalls) {
292       setLibcallName(LC.Op, LC.Name);
293     }
294   } else { // NoHWMult
295     const struct {
296       const RTLIB::Libcall Op;
297       const char * const Name;
298     } LibraryCalls[] = {
299       // Integer Multiply - EABI Table 9
300       { RTLIB::MUL_I16,   "__mspabi_mpyi" },
301       { RTLIB::MUL_I32,   "__mspabi_mpyl" },
302       { RTLIB::MUL_I64,   "__mspabi_mpyll" },
303       // The __mspabi_mpysl* functions are NOT implemented in libgcc
304       // The __mspabi_mpyul* functions are NOT implemented in libgcc
305     };
306     for (const auto &LC : LibraryCalls) {
307       setLibcallName(LC.Op, LC.Name);
308     }
309     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::MSP430_BUILTIN);
310   }
311 
312   // Several of the runtime library functions use a special calling conv
313   setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::MSP430_BUILTIN);
314   setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::MSP430_BUILTIN);
315   setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::MSP430_BUILTIN);
316   setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::MSP430_BUILTIN);
317   setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::MSP430_BUILTIN);
318   setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::MSP430_BUILTIN);
319   setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::MSP430_BUILTIN);
320   setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::MSP430_BUILTIN);
321   setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::MSP430_BUILTIN);
322   setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::MSP430_BUILTIN);
323   setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::MSP430_BUILTIN);
324   setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::MSP430_BUILTIN);
325   setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::MSP430_BUILTIN);
326   setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::MSP430_BUILTIN);
327   // TODO: __mspabi_srall, __mspabi_srlll, __mspabi_sllll
328 
329   setMinFunctionAlignment(1);
330   setPrefFunctionAlignment(1);
331 }
332 
333 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
334                                              SelectionDAG &DAG) const {
335   switch (Op.getOpcode()) {
336   case ISD::SHL: // FALLTHROUGH
337   case ISD::SRL:
338   case ISD::SRA:              return LowerShifts(Op, DAG);
339   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
340   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
341   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
342   case ISD::SETCC:            return LowerSETCC(Op, DAG);
343   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
344   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
345   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
346   case ISD::RETURNADDR:       return LowerRETURNADDR(Op, DAG);
347   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
348   case ISD::VASTART:          return LowerVASTART(Op, DAG);
349   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
350   default:
351     llvm_unreachable("unimplemented operand");
352   }
353 }
354 
355 //===----------------------------------------------------------------------===//
356 //                       MSP430 Inline Assembly Support
357 //===----------------------------------------------------------------------===//
358 
359 /// getConstraintType - Given a constraint letter, return the type of
360 /// constraint it is for this target.
361 TargetLowering::ConstraintType
362 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
363   if (Constraint.size() == 1) {
364     switch (Constraint[0]) {
365     case 'r':
366       return C_RegisterClass;
367     default:
368       break;
369     }
370   }
371   return TargetLowering::getConstraintType(Constraint);
372 }
373 
374 std::pair<unsigned, const TargetRegisterClass *>
375 MSP430TargetLowering::getRegForInlineAsmConstraint(
376     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
377   if (Constraint.size() == 1) {
378     // GCC Constraint Letters
379     switch (Constraint[0]) {
380     default: break;
381     case 'r':   // GENERAL_REGS
382       if (VT == MVT::i8)
383         return std::make_pair(0U, &MSP430::GR8RegClass);
384 
385       return std::make_pair(0U, &MSP430::GR16RegClass);
386     }
387   }
388 
389   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
390 }
391 
392 //===----------------------------------------------------------------------===//
393 //                      Calling Convention Implementation
394 //===----------------------------------------------------------------------===//
395 
396 #include "MSP430GenCallingConv.inc"
397 
398 /// For each argument in a function store the number of pieces it is composed
399 /// of.
400 template<typename ArgT>
401 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
402                               SmallVectorImpl<unsigned> &Out) {
403   unsigned CurrentArgIndex;
404 
405   if (Args.empty())
406     return;
407 
408   CurrentArgIndex = Args[0].OrigArgIndex;
409   Out.push_back(0);
410 
411   for (auto &Arg : Args) {
412     if (CurrentArgIndex == Arg.OrigArgIndex) {
413       Out.back() += 1;
414     } else {
415       Out.push_back(1);
416       CurrentArgIndex = Arg.OrigArgIndex;
417     }
418   }
419 }
420 
421 static void AnalyzeVarArgs(CCState &State,
422                            const SmallVectorImpl<ISD::OutputArg> &Outs) {
423   State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
424 }
425 
426 static void AnalyzeVarArgs(CCState &State,
427                            const SmallVectorImpl<ISD::InputArg> &Ins) {
428   State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
429 }
430 
431 /// Analyze incoming and outgoing function arguments. We need custom C++ code
432 /// to handle special constraints in the ABI like reversing the order of the
433 /// pieces of splitted arguments. In addition, all pieces of a certain argument
434 /// have to be passed either using registers or the stack but never mixing both.
435 template<typename ArgT>
436 static void AnalyzeArguments(CCState &State,
437                              SmallVectorImpl<CCValAssign> &ArgLocs,
438                              const SmallVectorImpl<ArgT> &Args) {
439   static const MCPhysReg CRegList[] = {
440     MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
441   };
442   static const unsigned CNbRegs = array_lengthof(CRegList);
443   static const MCPhysReg BuiltinRegList[] = {
444     MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11,
445     MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
446   };
447   static const unsigned BuiltinNbRegs = array_lengthof(BuiltinRegList);
448 
449   ArrayRef<MCPhysReg> RegList;
450   unsigned NbRegs;
451 
452   bool Builtin = (State.getCallingConv() == CallingConv::MSP430_BUILTIN);
453   if (Builtin) {
454     RegList = BuiltinRegList;
455     NbRegs = BuiltinNbRegs;
456   } else {
457     RegList = CRegList;
458     NbRegs = CNbRegs;
459   }
460 
461   if (State.isVarArg()) {
462     AnalyzeVarArgs(State, Args);
463     return;
464   }
465 
466   SmallVector<unsigned, 4> ArgsParts;
467   ParseFunctionArgs(Args, ArgsParts);
468 
469   if (Builtin) {
470     assert(ArgsParts.size() == 2 &&
471         "Builtin calling convention requires two arguments");
472   }
473 
474   unsigned RegsLeft = NbRegs;
475   bool UsedStack = false;
476   unsigned ValNo = 0;
477 
478   for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
479     MVT ArgVT = Args[ValNo].VT;
480     ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
481     MVT LocVT = ArgVT;
482     CCValAssign::LocInfo LocInfo = CCValAssign::Full;
483 
484     // Promote i8 to i16
485     if (LocVT == MVT::i8) {
486       LocVT = MVT::i16;
487       if (ArgFlags.isSExt())
488           LocInfo = CCValAssign::SExt;
489       else if (ArgFlags.isZExt())
490           LocInfo = CCValAssign::ZExt;
491       else
492           LocInfo = CCValAssign::AExt;
493     }
494 
495     // Handle byval arguments
496     if (ArgFlags.isByVal()) {
497       State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
498       continue;
499     }
500 
501     unsigned Parts = ArgsParts[i];
502 
503     if (Builtin) {
504       assert(Parts == 4 &&
505           "Builtin calling convention requires 64-bit arguments");
506     }
507 
508     if (!UsedStack && Parts == 2 && RegsLeft == 1) {
509       // Special case for 32-bit register split, see EABI section 3.3.3
510       unsigned Reg = State.AllocateReg(RegList);
511       State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
512       RegsLeft -= 1;
513 
514       UsedStack = true;
515       CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
516     } else if (Parts <= RegsLeft) {
517       for (unsigned j = 0; j < Parts; j++) {
518         unsigned Reg = State.AllocateReg(RegList);
519         State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
520         RegsLeft--;
521       }
522     } else {
523       UsedStack = true;
524       for (unsigned j = 0; j < Parts; j++)
525         CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
526     }
527   }
528 }
529 
530 static void AnalyzeRetResult(CCState &State,
531                              const SmallVectorImpl<ISD::InputArg> &Ins) {
532   State.AnalyzeCallResult(Ins, RetCC_MSP430);
533 }
534 
535 static void AnalyzeRetResult(CCState &State,
536                              const SmallVectorImpl<ISD::OutputArg> &Outs) {
537   State.AnalyzeReturn(Outs, RetCC_MSP430);
538 }
539 
540 template<typename ArgT>
541 static void AnalyzeReturnValues(CCState &State,
542                                 SmallVectorImpl<CCValAssign> &RVLocs,
543                                 const SmallVectorImpl<ArgT> &Args) {
544   AnalyzeRetResult(State, Args);
545 }
546 
547 SDValue MSP430TargetLowering::LowerFormalArguments(
548     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
549     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
550     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
551 
552   switch (CallConv) {
553   default:
554     report_fatal_error("Unsupported calling convention");
555   case CallingConv::C:
556   case CallingConv::Fast:
557     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
558   case CallingConv::MSP430_INTR:
559     if (Ins.empty())
560       return Chain;
561     report_fatal_error("ISRs cannot have arguments");
562   }
563 }
564 
565 SDValue
566 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
567                                 SmallVectorImpl<SDValue> &InVals) const {
568   SelectionDAG &DAG                     = CLI.DAG;
569   SDLoc &dl                             = CLI.DL;
570   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
571   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
572   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
573   SDValue Chain                         = CLI.Chain;
574   SDValue Callee                        = CLI.Callee;
575   bool &isTailCall                      = CLI.IsTailCall;
576   CallingConv::ID CallConv              = CLI.CallConv;
577   bool isVarArg                         = CLI.IsVarArg;
578 
579   // MSP430 target does not yet support tail call optimization.
580   isTailCall = false;
581 
582   switch (CallConv) {
583   default:
584     report_fatal_error("Unsupported calling convention");
585   case CallingConv::MSP430_BUILTIN:
586   case CallingConv::Fast:
587   case CallingConv::C:
588     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
589                           Outs, OutVals, Ins, dl, DAG, InVals);
590   case CallingConv::MSP430_INTR:
591     report_fatal_error("ISRs cannot be called directly");
592   }
593 }
594 
595 /// LowerCCCArguments - transform physical registers into virtual registers and
596 /// generate load operations for arguments places on the stack.
597 // FIXME: struct return stuff
598 SDValue MSP430TargetLowering::LowerCCCArguments(
599     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
600     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
601     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
602   MachineFunction &MF = DAG.getMachineFunction();
603   MachineFrameInfo &MFI = MF.getFrameInfo();
604   MachineRegisterInfo &RegInfo = MF.getRegInfo();
605   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
606 
607   // Assign locations to all of the incoming arguments.
608   SmallVector<CCValAssign, 16> ArgLocs;
609   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
610                  *DAG.getContext());
611   AnalyzeArguments(CCInfo, ArgLocs, Ins);
612 
613   // Create frame index for the start of the first vararg value
614   if (isVarArg) {
615     unsigned Offset = CCInfo.getNextStackOffset();
616     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, Offset, true));
617   }
618 
619   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
620     CCValAssign &VA = ArgLocs[i];
621     if (VA.isRegLoc()) {
622       // Arguments passed in registers
623       EVT RegVT = VA.getLocVT();
624       switch (RegVT.getSimpleVT().SimpleTy) {
625       default:
626         {
627 #ifndef NDEBUG
628           errs() << "LowerFormalArguments Unhandled argument type: "
629                << RegVT.getEVTString() << "\n";
630 #endif
631           llvm_unreachable(nullptr);
632         }
633       case MVT::i16:
634         unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
635         RegInfo.addLiveIn(VA.getLocReg(), VReg);
636         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
637 
638         // If this is an 8-bit value, it is really passed promoted to 16
639         // bits. Insert an assert[sz]ext to capture this, then truncate to the
640         // right size.
641         if (VA.getLocInfo() == CCValAssign::SExt)
642           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
643                                  DAG.getValueType(VA.getValVT()));
644         else if (VA.getLocInfo() == CCValAssign::ZExt)
645           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
646                                  DAG.getValueType(VA.getValVT()));
647 
648         if (VA.getLocInfo() != CCValAssign::Full)
649           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
650 
651         InVals.push_back(ArgValue);
652       }
653     } else {
654       // Sanity check
655       assert(VA.isMemLoc());
656 
657       SDValue InVal;
658       ISD::ArgFlagsTy Flags = Ins[i].Flags;
659 
660       if (Flags.isByVal()) {
661         int FI = MFI.CreateFixedObject(Flags.getByValSize(),
662                                        VA.getLocMemOffset(), true);
663         InVal = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
664       } else {
665         // Load the argument to a virtual register
666         unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
667         if (ObjSize > 2) {
668             errs() << "LowerFormalArguments Unhandled argument type: "
669                 << EVT(VA.getLocVT()).getEVTString()
670                 << "\n";
671         }
672         // Create the frame index object for this incoming parameter...
673         int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
674 
675         // Create the SelectionDAG nodes corresponding to a load
676         //from this parameter
677         SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
678         InVal = DAG.getLoad(
679             VA.getLocVT(), dl, Chain, FIN,
680             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
681       }
682 
683       InVals.push_back(InVal);
684     }
685   }
686 
687   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
688     if (Ins[i].Flags.isSRet()) {
689       unsigned Reg = FuncInfo->getSRetReturnReg();
690       if (!Reg) {
691         Reg = MF.getRegInfo().createVirtualRegister(
692             getRegClassFor(MVT::i16));
693         FuncInfo->setSRetReturnReg(Reg);
694       }
695       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
696       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
697     }
698   }
699 
700   return Chain;
701 }
702 
703 bool
704 MSP430TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
705                                      MachineFunction &MF,
706                                      bool IsVarArg,
707                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
708                                      LLVMContext &Context) const {
709   SmallVector<CCValAssign, 16> RVLocs;
710   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
711   return CCInfo.CheckReturn(Outs, RetCC_MSP430);
712 }
713 
714 SDValue
715 MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
716                                   bool isVarArg,
717                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
718                                   const SmallVectorImpl<SDValue> &OutVals,
719                                   const SDLoc &dl, SelectionDAG &DAG) const {
720 
721   MachineFunction &MF = DAG.getMachineFunction();
722 
723   // CCValAssign - represent the assignment of the return value to a location
724   SmallVector<CCValAssign, 16> RVLocs;
725 
726   // ISRs cannot return any value.
727   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
728     report_fatal_error("ISRs cannot return any value");
729 
730   // CCState - Info about the registers and stack slot.
731   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
732                  *DAG.getContext());
733 
734   // Analize return values.
735   AnalyzeReturnValues(CCInfo, RVLocs, Outs);
736 
737   SDValue Flag;
738   SmallVector<SDValue, 4> RetOps(1, Chain);
739 
740   // Copy the result values into the output registers.
741   for (unsigned i = 0; i != RVLocs.size(); ++i) {
742     CCValAssign &VA = RVLocs[i];
743     assert(VA.isRegLoc() && "Can only return in registers!");
744 
745     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
746                              OutVals[i], Flag);
747 
748     // Guarantee that all emitted copies are stuck together,
749     // avoiding something bad.
750     Flag = Chain.getValue(1);
751     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
752   }
753 
754   if (MF.getFunction().hasStructRetAttr()) {
755     MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
756     unsigned Reg = FuncInfo->getSRetReturnReg();
757 
758     if (!Reg)
759       llvm_unreachable("sret virtual register not created in entry block");
760 
761     SDValue Val =
762       DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy(DAG.getDataLayout()));
763     unsigned R12 = MSP430::R12;
764 
765     Chain = DAG.getCopyToReg(Chain, dl, R12, Val, Flag);
766     Flag = Chain.getValue(1);
767     RetOps.push_back(DAG.getRegister(R12, getPointerTy(DAG.getDataLayout())));
768   }
769 
770   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
771                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
772 
773   RetOps[0] = Chain;  // Update chain.
774 
775   // Add the flag if we have it.
776   if (Flag.getNode())
777     RetOps.push_back(Flag);
778 
779   return DAG.getNode(Opc, dl, MVT::Other, RetOps);
780 }
781 
782 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
783 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
784 SDValue MSP430TargetLowering::LowerCCCCallTo(
785     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
786     bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
787     const SmallVectorImpl<SDValue> &OutVals,
788     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
789     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
790   // Analyze operands of the call, assigning locations to each operand.
791   SmallVector<CCValAssign, 16> ArgLocs;
792   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
793                  *DAG.getContext());
794   AnalyzeArguments(CCInfo, ArgLocs, Outs);
795 
796   // Get a count of how many bytes are to be pushed on the stack.
797   unsigned NumBytes = CCInfo.getNextStackOffset();
798   auto PtrVT = getPointerTy(DAG.getDataLayout());
799 
800   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
801 
802   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
803   SmallVector<SDValue, 12> MemOpChains;
804   SDValue StackPtr;
805 
806   // Walk the register/memloc assignments, inserting copies/loads.
807   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
808     CCValAssign &VA = ArgLocs[i];
809 
810     SDValue Arg = OutVals[i];
811 
812     // Promote the value if needed.
813     switch (VA.getLocInfo()) {
814       default: llvm_unreachable("Unknown loc info!");
815       case CCValAssign::Full: break;
816       case CCValAssign::SExt:
817         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
818         break;
819       case CCValAssign::ZExt:
820         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
821         break;
822       case CCValAssign::AExt:
823         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
824         break;
825     }
826 
827     // Arguments that can be passed on register must be kept at RegsToPass
828     // vector
829     if (VA.isRegLoc()) {
830       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
831     } else {
832       assert(VA.isMemLoc());
833 
834       if (!StackPtr.getNode())
835         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, PtrVT);
836 
837       SDValue PtrOff =
838           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
839                       DAG.getIntPtrConstant(VA.getLocMemOffset(), dl));
840 
841       SDValue MemOp;
842       ISD::ArgFlagsTy Flags = Outs[i].Flags;
843 
844       if (Flags.isByVal()) {
845         SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
846         MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
847                               Flags.getByValAlign(),
848                               /*isVolatile*/false,
849                               /*AlwaysInline=*/true,
850                               /*isTailCall=*/false,
851                               MachinePointerInfo(),
852                               MachinePointerInfo());
853       } else {
854         MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
855       }
856 
857       MemOpChains.push_back(MemOp);
858     }
859   }
860 
861   // Transform all store nodes into one single node because all store nodes are
862   // independent of each other.
863   if (!MemOpChains.empty())
864     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
865 
866   // Build a sequence of copy-to-reg nodes chained together with token chain and
867   // flag operands which copy the outgoing args into registers.  The InFlag in
868   // necessary since all emitted instructions must be stuck together.
869   SDValue InFlag;
870   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
871     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
872                              RegsToPass[i].second, InFlag);
873     InFlag = Chain.getValue(1);
874   }
875 
876   // If the callee is a GlobalAddress node (quite common, every direct call is)
877   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
878   // Likewise ExternalSymbol -> TargetExternalSymbol.
879   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
880     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
881   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
882     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
883 
884   // Returns a chain & a flag for retval copy to use.
885   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
886   SmallVector<SDValue, 8> Ops;
887   Ops.push_back(Chain);
888   Ops.push_back(Callee);
889 
890   // Add argument registers to the end of the list so that they are
891   // known live into the call.
892   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
893     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
894                                   RegsToPass[i].second.getValueType()));
895 
896   if (InFlag.getNode())
897     Ops.push_back(InFlag);
898 
899   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
900   InFlag = Chain.getValue(1);
901 
902   // Create the CALLSEQ_END node.
903   Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
904                              DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
905   InFlag = Chain.getValue(1);
906 
907   // Handle result values, copying them out of physregs into vregs that we
908   // return.
909   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
910                          DAG, InVals);
911 }
912 
913 /// LowerCallResult - Lower the result values of a call into the
914 /// appropriate copies out of appropriate physical registers.
915 ///
916 SDValue MSP430TargetLowering::LowerCallResult(
917     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
918     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
919     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
920 
921   // Assign locations to each value returned by this call.
922   SmallVector<CCValAssign, 16> RVLocs;
923   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
924                  *DAG.getContext());
925 
926   AnalyzeReturnValues(CCInfo, RVLocs, Ins);
927 
928   // Copy all of the result registers out of their specified physreg.
929   for (unsigned i = 0; i != RVLocs.size(); ++i) {
930     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
931                                RVLocs[i].getValVT(), InFlag).getValue(1);
932     InFlag = Chain.getValue(2);
933     InVals.push_back(Chain.getValue(0));
934   }
935 
936   return Chain;
937 }
938 
939 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
940                                           SelectionDAG &DAG) const {
941   unsigned Opc = Op.getOpcode();
942   SDNode* N = Op.getNode();
943   EVT VT = Op.getValueType();
944   SDLoc dl(N);
945 
946   // Expand non-constant shifts to loops:
947   if (!isa<ConstantSDNode>(N->getOperand(1)))
948     return Op;
949 
950   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
951 
952   // Expand the stuff into sequence of shifts.
953   SDValue Victim = N->getOperand(0);
954 
955   if ((Opc == ISD::SRA || Opc == ISD::SRL) && ShiftAmount >= 8) {
956     // foo >> (8 + N) => sxt(swpb(foo)) >> N
957     assert(VT == MVT::i16 && "Can not shift i8 by 8 and more");
958     Victim = DAG.getNode(ISD::BSWAP, dl, VT, Victim);
959     if (Opc == ISD::SRA)
960       Victim = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Victim,
961                            DAG.getValueType(MVT::i8));
962     else
963       Victim = DAG.getZeroExtendInReg(Victim, dl, MVT::i8);
964     ShiftAmount -= 8;
965   }
966 
967   if (Opc == ISD::SRL && ShiftAmount) {
968     // Emit a special goodness here:
969     // srl A, 1 => clrc; rrc A
970     Victim = DAG.getNode(MSP430ISD::RRCL, dl, VT, Victim);
971     ShiftAmount -= 1;
972   }
973 
974   while (ShiftAmount--)
975     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
976                          dl, VT, Victim);
977 
978   return Victim;
979 }
980 
981 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
982                                                  SelectionDAG &DAG) const {
983   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
984   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
985   auto PtrVT = getPointerTy(DAG.getDataLayout());
986 
987   // Create the TargetGlobalAddress node, folding in the constant offset.
988   SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), PtrVT, Offset);
989   return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op), PtrVT, Result);
990 }
991 
992 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
993                                                   SelectionDAG &DAG) const {
994   SDLoc dl(Op);
995   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
996   auto PtrVT = getPointerTy(DAG.getDataLayout());
997   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT);
998 
999   return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
1000 }
1001 
1002 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
1003                                                 SelectionDAG &DAG) const {
1004   SDLoc dl(Op);
1005   auto PtrVT = getPointerTy(DAG.getDataLayout());
1006   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1007   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
1008 
1009   return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
1010 }
1011 
1012 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
1013                        ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
1014   // FIXME: Handle bittests someday
1015   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
1016 
1017   // FIXME: Handle jump negative someday
1018   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
1019   switch (CC) {
1020   default: llvm_unreachable("Invalid integer condition!");
1021   case ISD::SETEQ:
1022     TCC = MSP430CC::COND_E;     // aka COND_Z
1023     // Minor optimization: if LHS is a constant, swap operands, then the
1024     // constant can be folded into comparison.
1025     if (LHS.getOpcode() == ISD::Constant)
1026       std::swap(LHS, RHS);
1027     break;
1028   case ISD::SETNE:
1029     TCC = MSP430CC::COND_NE;    // aka COND_NZ
1030     // Minor optimization: if LHS is a constant, swap operands, then the
1031     // constant can be folded into comparison.
1032     if (LHS.getOpcode() == ISD::Constant)
1033       std::swap(LHS, RHS);
1034     break;
1035   case ISD::SETULE:
1036     std::swap(LHS, RHS);
1037     LLVM_FALLTHROUGH;
1038   case ISD::SETUGE:
1039     // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
1040     // fold constant into instruction.
1041     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1042       LHS = RHS;
1043       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1044       TCC = MSP430CC::COND_LO;
1045       break;
1046     }
1047     TCC = MSP430CC::COND_HS;    // aka COND_C
1048     break;
1049   case ISD::SETUGT:
1050     std::swap(LHS, RHS);
1051     LLVM_FALLTHROUGH;
1052   case ISD::SETULT:
1053     // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
1054     // fold constant into instruction.
1055     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1056       LHS = RHS;
1057       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1058       TCC = MSP430CC::COND_HS;
1059       break;
1060     }
1061     TCC = MSP430CC::COND_LO;    // aka COND_NC
1062     break;
1063   case ISD::SETLE:
1064     std::swap(LHS, RHS);
1065     LLVM_FALLTHROUGH;
1066   case ISD::SETGE:
1067     // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
1068     // fold constant into instruction.
1069     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1070       LHS = RHS;
1071       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1072       TCC = MSP430CC::COND_L;
1073       break;
1074     }
1075     TCC = MSP430CC::COND_GE;
1076     break;
1077   case ISD::SETGT:
1078     std::swap(LHS, RHS);
1079     LLVM_FALLTHROUGH;
1080   case ISD::SETLT:
1081     // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
1082     // fold constant into instruction.
1083     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1084       LHS = RHS;
1085       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1086       TCC = MSP430CC::COND_GE;
1087       break;
1088     }
1089     TCC = MSP430CC::COND_L;
1090     break;
1091   }
1092 
1093   TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
1094   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
1095 }
1096 
1097 
1098 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1099   SDValue Chain = Op.getOperand(0);
1100   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1101   SDValue LHS   = Op.getOperand(2);
1102   SDValue RHS   = Op.getOperand(3);
1103   SDValue Dest  = Op.getOperand(4);
1104   SDLoc dl  (Op);
1105 
1106   SDValue TargetCC;
1107   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1108 
1109   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
1110                      Chain, Dest, TargetCC, Flag);
1111 }
1112 
1113 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1114   SDValue LHS   = Op.getOperand(0);
1115   SDValue RHS   = Op.getOperand(1);
1116   SDLoc dl  (Op);
1117 
1118   // If we are doing an AND and testing against zero, then the CMP
1119   // will not be generated.  The AND (or BIT) will generate the condition codes,
1120   // but they are different from CMP.
1121   // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
1122   // lowering & isel wouldn't diverge.
1123   bool andCC = false;
1124   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1125     if (RHSC->isNullValue() && LHS.hasOneUse() &&
1126         (LHS.getOpcode() == ISD::AND ||
1127          (LHS.getOpcode() == ISD::TRUNCATE &&
1128           LHS.getOperand(0).getOpcode() == ISD::AND))) {
1129       andCC = true;
1130     }
1131   }
1132   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1133   SDValue TargetCC;
1134   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1135 
1136   // Get the condition codes directly from the status register, if its easy.
1137   // Otherwise a branch will be generated.  Note that the AND and BIT
1138   // instructions generate different flags than CMP, the carry bit can be used
1139   // for NE/EQ.
1140   bool Invert = false;
1141   bool Shift = false;
1142   bool Convert = true;
1143   switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
1144    default:
1145     Convert = false;
1146     break;
1147    case MSP430CC::COND_HS:
1148      // Res = SR & 1, no processing is required
1149      break;
1150    case MSP430CC::COND_LO:
1151      // Res = ~(SR & 1)
1152      Invert = true;
1153      break;
1154    case MSP430CC::COND_NE:
1155      if (andCC) {
1156        // C = ~Z, thus Res = SR & 1, no processing is required
1157      } else {
1158        // Res = ~((SR >> 1) & 1)
1159        Shift = true;
1160        Invert = true;
1161      }
1162      break;
1163    case MSP430CC::COND_E:
1164      Shift = true;
1165      // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
1166      // Res = (SR >> 1) & 1 is 1 word shorter.
1167      break;
1168   }
1169   EVT VT = Op.getValueType();
1170   SDValue One  = DAG.getConstant(1, dl, VT);
1171   if (Convert) {
1172     SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
1173                                     MVT::i16, Flag);
1174     if (Shift)
1175       // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
1176       SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
1177     SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
1178     if (Invert)
1179       SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
1180     return SR;
1181   } else {
1182     SDValue Zero = DAG.getConstant(0, dl, VT);
1183     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1184     SDValue Ops[] = {One, Zero, TargetCC, Flag};
1185     return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1186   }
1187 }
1188 
1189 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
1190                                              SelectionDAG &DAG) const {
1191   SDValue LHS    = Op.getOperand(0);
1192   SDValue RHS    = Op.getOperand(1);
1193   SDValue TrueV  = Op.getOperand(2);
1194   SDValue FalseV = Op.getOperand(3);
1195   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1196   SDLoc dl   (Op);
1197 
1198   SDValue TargetCC;
1199   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1200 
1201   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1202   SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1203 
1204   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1205 }
1206 
1207 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1208                                                SelectionDAG &DAG) const {
1209   SDValue Val = Op.getOperand(0);
1210   EVT VT      = Op.getValueType();
1211   SDLoc dl(Op);
1212 
1213   assert(VT == MVT::i16 && "Only support i16 for now!");
1214 
1215   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1216                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1217                      DAG.getValueType(Val.getValueType()));
1218 }
1219 
1220 SDValue
1221 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1222   MachineFunction &MF = DAG.getMachineFunction();
1223   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1224   int ReturnAddrIndex = FuncInfo->getRAIndex();
1225   auto PtrVT = getPointerTy(MF.getDataLayout());
1226 
1227   if (ReturnAddrIndex == 0) {
1228     // Set up a frame object for the return address.
1229     uint64_t SlotSize = MF.getDataLayout().getPointerSize();
1230     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize, -SlotSize,
1231                                                            true);
1232     FuncInfo->setRAIndex(ReturnAddrIndex);
1233   }
1234 
1235   return DAG.getFrameIndex(ReturnAddrIndex, PtrVT);
1236 }
1237 
1238 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1239                                               SelectionDAG &DAG) const {
1240   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1241   MFI.setReturnAddressIsTaken(true);
1242 
1243   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1244     return SDValue();
1245 
1246   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1247   SDLoc dl(Op);
1248   auto PtrVT = getPointerTy(DAG.getDataLayout());
1249 
1250   if (Depth > 0) {
1251     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1252     SDValue Offset =
1253         DAG.getConstant(DAG.getDataLayout().getPointerSize(), dl, MVT::i16);
1254     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1255                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
1256                        MachinePointerInfo());
1257   }
1258 
1259   // Just load the return address.
1260   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1261   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
1262                      MachinePointerInfo());
1263 }
1264 
1265 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1266                                              SelectionDAG &DAG) const {
1267   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1268   MFI.setFrameAddressIsTaken(true);
1269 
1270   EVT VT = Op.getValueType();
1271   SDLoc dl(Op);  // FIXME probably not meaningful
1272   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1273   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1274                                          MSP430::FP, VT);
1275   while (Depth--)
1276     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1277                             MachinePointerInfo());
1278   return FrameAddr;
1279 }
1280 
1281 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1282                                            SelectionDAG &DAG) const {
1283   MachineFunction &MF = DAG.getMachineFunction();
1284   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1285   auto PtrVT = getPointerTy(DAG.getDataLayout());
1286 
1287   // Frame index of first vararg argument
1288   SDValue FrameIndex =
1289       DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1290   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1291 
1292   // Create a store of the frame index to the location operand
1293   return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex, Op.getOperand(1),
1294                       MachinePointerInfo(SV));
1295 }
1296 
1297 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1298                                              SelectionDAG &DAG) const {
1299     JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1300     auto PtrVT = getPointerTy(DAG.getDataLayout());
1301     SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1302     return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT), PtrVT, Result);
1303 }
1304 
1305 /// getPostIndexedAddressParts - returns true by value, base pointer and
1306 /// offset pointer and addressing mode by reference if this node can be
1307 /// combined with a load / store to form a post-indexed load / store.
1308 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1309                                                       SDValue &Base,
1310                                                       SDValue &Offset,
1311                                                       ISD::MemIndexedMode &AM,
1312                                                       SelectionDAG &DAG) const {
1313 
1314   LoadSDNode *LD = cast<LoadSDNode>(N);
1315   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1316     return false;
1317 
1318   EVT VT = LD->getMemoryVT();
1319   if (VT != MVT::i8 && VT != MVT::i16)
1320     return false;
1321 
1322   if (Op->getOpcode() != ISD::ADD)
1323     return false;
1324 
1325   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1326     uint64_t RHSC = RHS->getZExtValue();
1327     if ((VT == MVT::i16 && RHSC != 2) ||
1328         (VT == MVT::i8 && RHSC != 1))
1329       return false;
1330 
1331     Base = Op->getOperand(0);
1332     Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1333     AM = ISD::POST_INC;
1334     return true;
1335   }
1336 
1337   return false;
1338 }
1339 
1340 
1341 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1342   switch ((MSP430ISD::NodeType)Opcode) {
1343   case MSP430ISD::FIRST_NUMBER:       break;
1344   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
1345   case MSP430ISD::RETI_FLAG:          return "MSP430ISD::RETI_FLAG";
1346   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
1347   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
1348   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
1349   case MSP430ISD::RRCL:               return "MSP430ISD::RRCL";
1350   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
1351   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
1352   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
1353   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
1354   case MSP430ISD::SETCC:              return "MSP430ISD::SETCC";
1355   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
1356   case MSP430ISD::DADD:               return "MSP430ISD::DADD";
1357   }
1358   return nullptr;
1359 }
1360 
1361 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1362                                           Type *Ty2) const {
1363   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1364     return false;
1365 
1366   return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1367 }
1368 
1369 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1370   if (!VT1.isInteger() || !VT2.isInteger())
1371     return false;
1372 
1373   return (VT1.getSizeInBits() > VT2.getSizeInBits());
1374 }
1375 
1376 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1377   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1378   return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1379 }
1380 
1381 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1382   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1383   return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1384 }
1385 
1386 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1387   return isZExtFree(Val.getValueType(), VT2);
1388 }
1389 
1390 //===----------------------------------------------------------------------===//
1391 //  Other Lowering Code
1392 //===----------------------------------------------------------------------===//
1393 
1394 MachineBasicBlock *
1395 MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1396                                      MachineBasicBlock *BB) const {
1397   MachineFunction *F = BB->getParent();
1398   MachineRegisterInfo &RI = F->getRegInfo();
1399   DebugLoc dl = MI.getDebugLoc();
1400   const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1401 
1402   unsigned Opc;
1403   bool ClearCarry = false;
1404   const TargetRegisterClass * RC;
1405   switch (MI.getOpcode()) {
1406   default: llvm_unreachable("Invalid shift opcode!");
1407   case MSP430::Shl8:
1408     Opc = MSP430::ADD8rr;
1409     RC = &MSP430::GR8RegClass;
1410     break;
1411   case MSP430::Shl16:
1412     Opc = MSP430::ADD16rr;
1413     RC = &MSP430::GR16RegClass;
1414     break;
1415   case MSP430::Sra8:
1416     Opc = MSP430::RRA8r;
1417     RC = &MSP430::GR8RegClass;
1418     break;
1419   case MSP430::Sra16:
1420     Opc = MSP430::RRA16r;
1421     RC = &MSP430::GR16RegClass;
1422     break;
1423   case MSP430::Srl8:
1424     ClearCarry = true;
1425     Opc = MSP430::RRC8r;
1426     RC = &MSP430::GR8RegClass;
1427     break;
1428   case MSP430::Srl16:
1429     ClearCarry = true;
1430     Opc = MSP430::RRC16r;
1431     RC = &MSP430::GR16RegClass;
1432     break;
1433   case MSP430::Rrcl8:
1434   case MSP430::Rrcl16: {
1435     BuildMI(*BB, MI, dl, TII.get(MSP430::BIC16rc), MSP430::SR)
1436       .addReg(MSP430::SR).addImm(1);
1437     unsigned SrcReg = MI.getOperand(1).getReg();
1438     unsigned DstReg = MI.getOperand(0).getReg();
1439     unsigned RrcOpc = MI.getOpcode() == MSP430::Rrcl16
1440                     ? MSP430::RRC16r : MSP430::RRC8r;
1441     BuildMI(*BB, MI, dl, TII.get(RrcOpc), DstReg)
1442       .addReg(SrcReg);
1443     MI.eraseFromParent(); // The pseudo instruction is gone now.
1444     return BB;
1445   }
1446   }
1447 
1448   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1449   MachineFunction::iterator I = ++BB->getIterator();
1450 
1451   // Create loop block
1452   MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1453   MachineBasicBlock *RemBB  = F->CreateMachineBasicBlock(LLVM_BB);
1454 
1455   F->insert(I, LoopBB);
1456   F->insert(I, RemBB);
1457 
1458   // Update machine-CFG edges by transferring all successors of the current
1459   // block to the block containing instructions after shift.
1460   RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1461                 BB->end());
1462   RemBB->transferSuccessorsAndUpdatePHIs(BB);
1463 
1464   // Add edges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1465   BB->addSuccessor(LoopBB);
1466   BB->addSuccessor(RemBB);
1467   LoopBB->addSuccessor(RemBB);
1468   LoopBB->addSuccessor(LoopBB);
1469 
1470   unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1471   unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1472   unsigned ShiftReg = RI.createVirtualRegister(RC);
1473   unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1474   unsigned ShiftAmtSrcReg = MI.getOperand(2).getReg();
1475   unsigned SrcReg = MI.getOperand(1).getReg();
1476   unsigned DstReg = MI.getOperand(0).getReg();
1477 
1478   // BB:
1479   // cmp 0, N
1480   // je RemBB
1481   BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1482     .addReg(ShiftAmtSrcReg).addImm(0);
1483   BuildMI(BB, dl, TII.get(MSP430::JCC))
1484     .addMBB(RemBB)
1485     .addImm(MSP430CC::COND_E);
1486 
1487   // LoopBB:
1488   // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1489   // ShiftAmt = phi [%N, BB],      [%ShiftAmt2, LoopBB]
1490   // ShiftReg2 = shift ShiftReg
1491   // ShiftAmt2 = ShiftAmt - 1;
1492   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1493     .addReg(SrcReg).addMBB(BB)
1494     .addReg(ShiftReg2).addMBB(LoopBB);
1495   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1496     .addReg(ShiftAmtSrcReg).addMBB(BB)
1497     .addReg(ShiftAmtReg2).addMBB(LoopBB);
1498   if (ClearCarry)
1499     BuildMI(LoopBB, dl, TII.get(MSP430::BIC16rc), MSP430::SR)
1500       .addReg(MSP430::SR).addImm(1);
1501   if (Opc == MSP430::ADD8rr || Opc == MSP430::ADD16rr)
1502     BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1503       .addReg(ShiftReg)
1504       .addReg(ShiftReg);
1505   else
1506     BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1507       .addReg(ShiftReg);
1508   BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1509     .addReg(ShiftAmtReg).addImm(1);
1510   BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1511     .addMBB(LoopBB)
1512     .addImm(MSP430CC::COND_NE);
1513 
1514   // RemBB:
1515   // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1516   BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1517     .addReg(SrcReg).addMBB(BB)
1518     .addReg(ShiftReg2).addMBB(LoopBB);
1519 
1520   MI.eraseFromParent(); // The pseudo instruction is gone now.
1521   return RemBB;
1522 }
1523 
1524 MachineBasicBlock *
1525 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1526                                                   MachineBasicBlock *BB) const {
1527   unsigned Opc = MI.getOpcode();
1528 
1529   if (Opc == MSP430::Shl8  || Opc == MSP430::Shl16 ||
1530       Opc == MSP430::Sra8  || Opc == MSP430::Sra16 ||
1531       Opc == MSP430::Srl8  || Opc == MSP430::Srl16 ||
1532       Opc == MSP430::Rrcl8 || Opc == MSP430::Rrcl16)
1533     return EmitShiftInstr(MI, BB);
1534 
1535   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1536   DebugLoc dl = MI.getDebugLoc();
1537 
1538   assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1539          "Unexpected instr type to insert");
1540 
1541   // To "insert" a SELECT instruction, we actually have to insert the diamond
1542   // control-flow pattern.  The incoming instruction knows the destination vreg
1543   // to set, the condition code register to branch on, the true/false values to
1544   // select between, and a branch opcode to use.
1545   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1546   MachineFunction::iterator I = ++BB->getIterator();
1547 
1548   //  thisMBB:
1549   //  ...
1550   //   TrueVal = ...
1551   //   cmpTY ccX, r1, r2
1552   //   jCC copy1MBB
1553   //   fallthrough --> copy0MBB
1554   MachineBasicBlock *thisMBB = BB;
1555   MachineFunction *F = BB->getParent();
1556   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1557   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1558   F->insert(I, copy0MBB);
1559   F->insert(I, copy1MBB);
1560   // Update machine-CFG edges by transferring all successors of the current
1561   // block to the new block which will contain the Phi node for the select.
1562   copy1MBB->splice(copy1MBB->begin(), BB,
1563                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
1564   copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1565   // Next, add the true and fallthrough blocks as its successors.
1566   BB->addSuccessor(copy0MBB);
1567   BB->addSuccessor(copy1MBB);
1568 
1569   BuildMI(BB, dl, TII.get(MSP430::JCC))
1570       .addMBB(copy1MBB)
1571       .addImm(MI.getOperand(3).getImm());
1572 
1573   //  copy0MBB:
1574   //   %FalseValue = ...
1575   //   # fallthrough to copy1MBB
1576   BB = copy0MBB;
1577 
1578   // Update machine-CFG edges
1579   BB->addSuccessor(copy1MBB);
1580 
1581   //  copy1MBB:
1582   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1583   //  ...
1584   BB = copy1MBB;
1585   BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI), MI.getOperand(0).getReg())
1586       .addReg(MI.getOperand(2).getReg())
1587       .addMBB(copy0MBB)
1588       .addReg(MI.getOperand(1).getReg())
1589       .addMBB(thisMBB);
1590 
1591   MI.eraseFromParent(); // The pseudo instruction is gone now.
1592   return BB;
1593 }
1594