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