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