1 //===-- MSP430ISelLowering.cpp - MSP430 DAG Lowering Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MSP430TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "MSP430ISelLowering.h"
16 #include "MSP430MachineFunctionInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
39 #define DEBUG_TYPE "msp430-lower"
48 static cl::opt<HWMultUseMode>
49 HWMultMode("mhwmult", cl::Hidden,
50 cl::desc("Hardware multiplier use mode"),
53 clEnumValN(NoHWMult, "none",
54 "Do not use hardware multiplier"),
55 clEnumValN(HWMult16, "16bit",
56 "Use 16-bit hardware multiplier"),
57 clEnumValN(HWMult32, "32bit",
58 "Use 32-bit hardware multiplier"),
59 clEnumValN(HWMultF5, "f5series",
60 "Use F5 series hardware multiplier")));
62 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
63 const MSP430Subtarget &STI)
64 : TargetLowering(TM) {
66 // Set up the register classes.
67 addRegisterClass(MVT::i8, &MSP430::GR8RegClass);
68 addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
70 // Compute derived properties from the register classes
71 computeRegisterProperties(STI.getRegisterInfo());
73 // Provide all sorts of operation actions
74 setStackPointerRegisterToSaveRestore(MSP430::SP);
75 setBooleanContents(ZeroOrOneBooleanContent);
76 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
78 // We have post-incremented loads / stores.
79 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
80 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
82 for (MVT VT : MVT::integer_valuetypes()) {
83 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
84 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
85 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
86 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
87 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
90 // We don't have any truncstores
91 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
93 setOperationAction(ISD::SRA, MVT::i8, Custom);
94 setOperationAction(ISD::SHL, MVT::i8, Custom);
95 setOperationAction(ISD::SRL, MVT::i8, Custom);
96 setOperationAction(ISD::SRA, MVT::i16, Custom);
97 setOperationAction(ISD::SHL, MVT::i16, Custom);
98 setOperationAction(ISD::SRL, MVT::i16, Custom);
99 setOperationAction(ISD::ROTL, MVT::i8, Expand);
100 setOperationAction(ISD::ROTR, MVT::i8, Expand);
101 setOperationAction(ISD::ROTL, MVT::i16, Expand);
102 setOperationAction(ISD::ROTR, MVT::i16, Expand);
103 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
104 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
105 setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
106 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
107 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
108 setOperationAction(ISD::BR_CC, MVT::i16, Custom);
109 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
110 setOperationAction(ISD::SETCC, MVT::i8, Custom);
111 setOperationAction(ISD::SETCC, MVT::i16, Custom);
112 setOperationAction(ISD::SELECT, MVT::i8, Expand);
113 setOperationAction(ISD::SELECT, MVT::i16, Expand);
114 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
115 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
116 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom);
117 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
118 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
120 setOperationAction(ISD::CTTZ, MVT::i8, Expand);
121 setOperationAction(ISD::CTTZ, MVT::i16, Expand);
122 setOperationAction(ISD::CTLZ, MVT::i8, Expand);
123 setOperationAction(ISD::CTLZ, MVT::i16, Expand);
124 setOperationAction(ISD::CTPOP, MVT::i8, Expand);
125 setOperationAction(ISD::CTPOP, MVT::i16, Expand);
127 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
128 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
129 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
130 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
131 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
132 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
134 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
136 // FIXME: Implement efficiently multiplication by a constant
137 setOperationAction(ISD::MUL, MVT::i8, Promote);
138 setOperationAction(ISD::MULHS, MVT::i8, Promote);
139 setOperationAction(ISD::MULHU, MVT::i8, Promote);
140 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Promote);
141 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Promote);
142 setOperationAction(ISD::MUL, MVT::i16, LibCall);
143 setOperationAction(ISD::MULHS, MVT::i16, Expand);
144 setOperationAction(ISD::MULHU, MVT::i16, Expand);
145 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
146 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
148 setOperationAction(ISD::UDIV, MVT::i8, Promote);
149 setOperationAction(ISD::UDIVREM, MVT::i8, Promote);
150 setOperationAction(ISD::UREM, MVT::i8, Promote);
151 setOperationAction(ISD::SDIV, MVT::i8, Promote);
152 setOperationAction(ISD::SDIVREM, MVT::i8, Promote);
153 setOperationAction(ISD::SREM, MVT::i8, Promote);
154 setOperationAction(ISD::UDIV, MVT::i16, LibCall);
155 setOperationAction(ISD::UDIVREM, MVT::i16, Expand);
156 setOperationAction(ISD::UREM, MVT::i16, LibCall);
157 setOperationAction(ISD::SDIV, MVT::i16, LibCall);
158 setOperationAction(ISD::SDIVREM, MVT::i16, Expand);
159 setOperationAction(ISD::SREM, MVT::i16, LibCall);
162 setOperationAction(ISD::VASTART, MVT::Other, Custom);
163 setOperationAction(ISD::VAARG, MVT::Other, Expand);
164 setOperationAction(ISD::VAEND, MVT::Other, Expand);
165 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
166 setOperationAction(ISD::JumpTable, MVT::i16, Custom);
168 // EABI Libcalls - EABI Section 6.2
170 const RTLIB::Libcall Op;
171 const char * const Name;
172 const ISD::CondCode Cond;
174 // Floating point conversions - EABI Table 6
175 { RTLIB::FPROUND_F64_F32, "__mspabi_cvtdf", ISD::SETCC_INVALID },
176 { RTLIB::FPEXT_F32_F64, "__mspabi_cvtfd", ISD::SETCC_INVALID },
177 // The following is NOT implemented in libgcc
178 //{ RTLIB::FPTOSINT_F64_I16, "__mspabi_fixdi", ISD::SETCC_INVALID },
179 { RTLIB::FPTOSINT_F64_I32, "__mspabi_fixdli", ISD::SETCC_INVALID },
180 { RTLIB::FPTOSINT_F64_I64, "__mspabi_fixdlli", ISD::SETCC_INVALID },
181 // The following is NOT implemented in libgcc
182 //{ RTLIB::FPTOUINT_F64_I16, "__mspabi_fixdu", ISD::SETCC_INVALID },
183 { RTLIB::FPTOUINT_F64_I32, "__mspabi_fixdul", ISD::SETCC_INVALID },
184 { RTLIB::FPTOUINT_F64_I64, "__mspabi_fixdull", ISD::SETCC_INVALID },
185 // The following is NOT implemented in libgcc
186 //{ RTLIB::FPTOSINT_F32_I16, "__mspabi_fixfi", ISD::SETCC_INVALID },
187 { RTLIB::FPTOSINT_F32_I32, "__mspabi_fixfli", ISD::SETCC_INVALID },
188 { RTLIB::FPTOSINT_F32_I64, "__mspabi_fixflli", ISD::SETCC_INVALID },
189 // The following is NOT implemented in libgcc
190 //{ RTLIB::FPTOUINT_F32_I16, "__mspabi_fixfu", ISD::SETCC_INVALID },
191 { RTLIB::FPTOUINT_F32_I32, "__mspabi_fixful", ISD::SETCC_INVALID },
192 { RTLIB::FPTOUINT_F32_I64, "__mspabi_fixfull", ISD::SETCC_INVALID },
193 // TODO The following IS implemented in libgcc
194 //{ RTLIB::SINTTOFP_I16_F64, "__mspabi_fltid", ISD::SETCC_INVALID },
195 { RTLIB::SINTTOFP_I32_F64, "__mspabi_fltlid", ISD::SETCC_INVALID },
196 // TODO The following IS implemented in libgcc but is not in the EABI
197 { RTLIB::SINTTOFP_I64_F64, "__mspabi_fltllid", ISD::SETCC_INVALID },
198 // TODO The following IS implemented in libgcc
199 //{ RTLIB::UINTTOFP_I16_F64, "__mspabi_fltud", ISD::SETCC_INVALID },
200 { RTLIB::UINTTOFP_I32_F64, "__mspabi_fltuld", ISD::SETCC_INVALID },
201 // The following IS implemented in libgcc but is not in the EABI
202 { RTLIB::UINTTOFP_I64_F64, "__mspabi_fltulld", ISD::SETCC_INVALID },
203 // TODO The following IS implemented in libgcc
204 //{ RTLIB::SINTTOFP_I16_F32, "__mspabi_fltif", ISD::SETCC_INVALID },
205 { RTLIB::SINTTOFP_I32_F32, "__mspabi_fltlif", ISD::SETCC_INVALID },
206 // TODO The following IS implemented in libgcc but is not in the EABI
207 { RTLIB::SINTTOFP_I64_F32, "__mspabi_fltllif", ISD::SETCC_INVALID },
208 // TODO The following IS implemented in libgcc
209 //{ RTLIB::UINTTOFP_I16_F32, "__mspabi_fltuf", ISD::SETCC_INVALID },
210 { RTLIB::UINTTOFP_I32_F32, "__mspabi_fltulf", ISD::SETCC_INVALID },
211 // The following IS implemented in libgcc but is not in the EABI
212 { RTLIB::UINTTOFP_I64_F32, "__mspabi_fltullf", ISD::SETCC_INVALID },
214 // Floating point comparisons - EABI Table 7
215 { RTLIB::OEQ_F64, "__mspabi_cmpd", ISD::SETEQ },
216 { RTLIB::UNE_F64, "__mspabi_cmpd", ISD::SETNE },
217 { RTLIB::OGE_F64, "__mspabi_cmpd", ISD::SETGE },
218 { RTLIB::OLT_F64, "__mspabi_cmpd", ISD::SETLT },
219 { RTLIB::OLE_F64, "__mspabi_cmpd", ISD::SETLE },
220 { RTLIB::OGT_F64, "__mspabi_cmpd", ISD::SETGT },
221 { RTLIB::OEQ_F32, "__mspabi_cmpf", ISD::SETEQ },
222 { RTLIB::UNE_F32, "__mspabi_cmpf", ISD::SETNE },
223 { RTLIB::OGE_F32, "__mspabi_cmpf", ISD::SETGE },
224 { RTLIB::OLT_F32, "__mspabi_cmpf", ISD::SETLT },
225 { RTLIB::OLE_F32, "__mspabi_cmpf", ISD::SETLE },
226 { RTLIB::OGT_F32, "__mspabi_cmpf", ISD::SETGT },
228 // Floating point arithmetic - EABI Table 8
229 { RTLIB::ADD_F64, "__mspabi_addd", ISD::SETCC_INVALID },
230 { RTLIB::ADD_F32, "__mspabi_addf", ISD::SETCC_INVALID },
231 { RTLIB::DIV_F64, "__mspabi_divd", ISD::SETCC_INVALID },
232 { RTLIB::DIV_F32, "__mspabi_divf", ISD::SETCC_INVALID },
233 { RTLIB::MUL_F64, "__mspabi_mpyd", ISD::SETCC_INVALID },
234 { RTLIB::MUL_F32, "__mspabi_mpyf", ISD::SETCC_INVALID },
235 { RTLIB::SUB_F64, "__mspabi_subd", ISD::SETCC_INVALID },
236 { RTLIB::SUB_F32, "__mspabi_subf", ISD::SETCC_INVALID },
237 // The following are NOT implemented in libgcc
238 // { RTLIB::NEG_F64, "__mspabi_negd", ISD::SETCC_INVALID },
239 // { RTLIB::NEG_F32, "__mspabi_negf", ISD::SETCC_INVALID },
241 // TODO: SLL/SRA/SRL are in libgcc, RLL isn't
243 // Universal Integer Operations - EABI Table 9
244 { RTLIB::SDIV_I16, "__mspabi_divi", ISD::SETCC_INVALID },
245 { RTLIB::SDIV_I32, "__mspabi_divli", ISD::SETCC_INVALID },
246 { RTLIB::SDIV_I64, "__mspabi_divlli", ISD::SETCC_INVALID },
247 { RTLIB::UDIV_I16, "__mspabi_divu", ISD::SETCC_INVALID },
248 { RTLIB::UDIV_I32, "__mspabi_divul", ISD::SETCC_INVALID },
249 { RTLIB::UDIV_I64, "__mspabi_divull", ISD::SETCC_INVALID },
250 { RTLIB::SREM_I16, "__mspabi_remi", ISD::SETCC_INVALID },
251 { RTLIB::SREM_I32, "__mspabi_remli", ISD::SETCC_INVALID },
252 { RTLIB::SREM_I64, "__mspabi_remlli", ISD::SETCC_INVALID },
253 { RTLIB::UREM_I16, "__mspabi_remu", ISD::SETCC_INVALID },
254 { RTLIB::UREM_I32, "__mspabi_remul", ISD::SETCC_INVALID },
255 { RTLIB::UREM_I64, "__mspabi_remull", ISD::SETCC_INVALID },
259 for (const auto &LC : LibraryCalls) {
260 setLibcallName(LC.Op, LC.Name);
261 if (LC.Cond != ISD::SETCC_INVALID)
262 setCmpLibcallCC(LC.Op, LC.Cond);
265 if (HWMultMode == HWMult16) {
267 const RTLIB::Libcall Op;
268 const char * const Name;
270 // Integer Multiply - EABI Table 9
271 { RTLIB::MUL_I16, "__mspabi_mpyi_hw" },
272 { RTLIB::MUL_I32, "__mspabi_mpyl_hw" },
273 { RTLIB::MUL_I64, "__mspabi_mpyll_hw" },
274 // TODO The __mspabi_mpysl*_hw functions ARE implemented in libgcc
275 // TODO The __mspabi_mpyul*_hw functions ARE implemented in libgcc
277 for (const auto &LC : LibraryCalls) {
278 setLibcallName(LC.Op, LC.Name);
280 } else if (HWMultMode == HWMult32) {
282 const RTLIB::Libcall Op;
283 const char * const Name;
285 // Integer Multiply - EABI Table 9
286 { RTLIB::MUL_I16, "__mspabi_mpyi_hw" },
287 { RTLIB::MUL_I32, "__mspabi_mpyl_hw32" },
288 { RTLIB::MUL_I64, "__mspabi_mpyll_hw32" },
289 // TODO The __mspabi_mpysl*_hw32 functions ARE implemented in libgcc
290 // TODO The __mspabi_mpyul*_hw32 functions ARE implemented in libgcc
292 for (const auto &LC : LibraryCalls) {
293 setLibcallName(LC.Op, LC.Name);
295 } else if (HWMultMode == HWMultF5) {
297 const RTLIB::Libcall Op;
298 const char * const Name;
300 // Integer Multiply - EABI Table 9
301 { RTLIB::MUL_I16, "__mspabi_mpyi_f5hw" },
302 { RTLIB::MUL_I32, "__mspabi_mpyl_f5hw" },
303 { RTLIB::MUL_I64, "__mspabi_mpyll_f5hw" },
304 // TODO The __mspabi_mpysl*_f5hw functions ARE implemented in libgcc
305 // TODO The __mspabi_mpyul*_f5hw functions ARE implemented in libgcc
307 for (const auto &LC : LibraryCalls) {
308 setLibcallName(LC.Op, LC.Name);
312 const RTLIB::Libcall Op;
313 const char * const Name;
315 // Integer Multiply - EABI Table 9
316 { RTLIB::MUL_I16, "__mspabi_mpyi" },
317 { RTLIB::MUL_I32, "__mspabi_mpyl" },
318 { RTLIB::MUL_I64, "__mspabi_mpyll" },
319 // The __mspabi_mpysl* functions are NOT implemented in libgcc
320 // The __mspabi_mpyul* functions are NOT implemented in libgcc
322 for (const auto &LC : LibraryCalls) {
323 setLibcallName(LC.Op, LC.Name);
325 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::MSP430_BUILTIN);
328 // Several of the runtime library functions use a special calling conv
329 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::MSP430_BUILTIN);
330 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::MSP430_BUILTIN);
331 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::MSP430_BUILTIN);
332 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::MSP430_BUILTIN);
333 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::MSP430_BUILTIN);
334 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::MSP430_BUILTIN);
335 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::MSP430_BUILTIN);
336 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::MSP430_BUILTIN);
337 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::MSP430_BUILTIN);
338 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::MSP430_BUILTIN);
339 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::MSP430_BUILTIN);
340 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::MSP430_BUILTIN);
341 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::MSP430_BUILTIN);
342 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::MSP430_BUILTIN);
343 // TODO: __mspabi_srall, __mspabi_srlll, __mspabi_sllll
345 setMinFunctionAlignment(1);
346 setPrefFunctionAlignment(2);
349 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
350 SelectionDAG &DAG) const {
351 switch (Op.getOpcode()) {
352 case ISD::SHL: // FALLTHROUGH
354 case ISD::SRA: return LowerShifts(Op, DAG);
355 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
356 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
357 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
358 case ISD::SETCC: return LowerSETCC(Op, DAG);
359 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
360 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
361 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
362 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
363 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
364 case ISD::VASTART: return LowerVASTART(Op, DAG);
365 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
367 llvm_unreachable("unimplemented operand");
371 //===----------------------------------------------------------------------===//
372 // MSP430 Inline Assembly Support
373 //===----------------------------------------------------------------------===//
375 /// getConstraintType - Given a constraint letter, return the type of
376 /// constraint it is for this target.
377 TargetLowering::ConstraintType
378 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
379 if (Constraint.size() == 1) {
380 switch (Constraint[0]) {
382 return C_RegisterClass;
387 return TargetLowering::getConstraintType(Constraint);
390 std::pair<unsigned, const TargetRegisterClass *>
391 MSP430TargetLowering::getRegForInlineAsmConstraint(
392 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
393 if (Constraint.size() == 1) {
394 // GCC Constraint Letters
395 switch (Constraint[0]) {
397 case 'r': // GENERAL_REGS
399 return std::make_pair(0U, &MSP430::GR8RegClass);
401 return std::make_pair(0U, &MSP430::GR16RegClass);
405 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
408 //===----------------------------------------------------------------------===//
409 // Calling Convention Implementation
410 //===----------------------------------------------------------------------===//
412 #include "MSP430GenCallingConv.inc"
414 /// For each argument in a function store the number of pieces it is composed
416 template<typename ArgT>
417 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
418 SmallVectorImpl<unsigned> &Out) {
419 unsigned CurrentArgIndex;
424 CurrentArgIndex = Args[0].OrigArgIndex;
427 for (auto &Arg : Args) {
428 if (CurrentArgIndex == Arg.OrigArgIndex) {
432 CurrentArgIndex = Arg.OrigArgIndex;
437 static void AnalyzeVarArgs(CCState &State,
438 const SmallVectorImpl<ISD::OutputArg> &Outs) {
439 State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
442 static void AnalyzeVarArgs(CCState &State,
443 const SmallVectorImpl<ISD::InputArg> &Ins) {
444 State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
447 /// Analyze incoming and outgoing function arguments. We need custom C++ code
448 /// to handle special constraints in the ABI like reversing the order of the
449 /// pieces of splitted arguments. In addition, all pieces of a certain argument
450 /// have to be passed either using registers or the stack but never mixing both.
451 template<typename ArgT>
452 static void AnalyzeArguments(CCState &State,
453 SmallVectorImpl<CCValAssign> &ArgLocs,
454 const SmallVectorImpl<ArgT> &Args) {
455 static const MCPhysReg CRegList[] = {
456 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
458 static const unsigned CNbRegs = array_lengthof(CRegList);
459 static const MCPhysReg BuiltinRegList[] = {
460 MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11,
461 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
463 static const unsigned BuiltinNbRegs = array_lengthof(BuiltinRegList);
465 ArrayRef<MCPhysReg> RegList;
468 bool Builtin = (State.getCallingConv() == CallingConv::MSP430_BUILTIN);
470 RegList = BuiltinRegList;
471 NbRegs = BuiltinNbRegs;
477 if (State.isVarArg()) {
478 AnalyzeVarArgs(State, Args);
482 SmallVector<unsigned, 4> ArgsParts;
483 ParseFunctionArgs(Args, ArgsParts);
486 assert(ArgsParts.size() == 2 &&
487 "Builtin calling convention requires two arguments");
490 unsigned RegsLeft = NbRegs;
491 bool UsedStack = false;
494 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
495 MVT ArgVT = Args[ValNo].VT;
496 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
498 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
501 if (LocVT == MVT::i8) {
503 if (ArgFlags.isSExt())
504 LocInfo = CCValAssign::SExt;
505 else if (ArgFlags.isZExt())
506 LocInfo = CCValAssign::ZExt;
508 LocInfo = CCValAssign::AExt;
511 // Handle byval arguments
512 if (ArgFlags.isByVal()) {
513 State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
517 unsigned Parts = ArgsParts[i];
521 "Builtin calling convention requires 64-bit arguments");
524 if (!UsedStack && Parts == 2 && RegsLeft == 1) {
525 // Special case for 32-bit register split, see EABI section 3.3.3
526 unsigned Reg = State.AllocateReg(RegList);
527 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
531 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
532 } else if (Parts <= RegsLeft) {
533 for (unsigned j = 0; j < Parts; j++) {
534 unsigned Reg = State.AllocateReg(RegList);
535 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
540 for (unsigned j = 0; j < Parts; j++)
541 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
546 static void AnalyzeRetResult(CCState &State,
547 const SmallVectorImpl<ISD::InputArg> &Ins) {
548 State.AnalyzeCallResult(Ins, RetCC_MSP430);
551 static void AnalyzeRetResult(CCState &State,
552 const SmallVectorImpl<ISD::OutputArg> &Outs) {
553 State.AnalyzeReturn(Outs, RetCC_MSP430);
556 template<typename ArgT>
557 static void AnalyzeReturnValues(CCState &State,
558 SmallVectorImpl<CCValAssign> &RVLocs,
559 const SmallVectorImpl<ArgT> &Args) {
560 AnalyzeRetResult(State, Args);
563 SDValue MSP430TargetLowering::LowerFormalArguments(
564 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
565 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
566 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
570 llvm_unreachable("Unsupported calling convention");
572 case CallingConv::Fast:
573 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
574 case CallingConv::MSP430_INTR:
577 report_fatal_error("ISRs cannot have arguments");
582 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
583 SmallVectorImpl<SDValue> &InVals) const {
584 SelectionDAG &DAG = CLI.DAG;
586 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
587 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
588 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
589 SDValue Chain = CLI.Chain;
590 SDValue Callee = CLI.Callee;
591 bool &isTailCall = CLI.IsTailCall;
592 CallingConv::ID CallConv = CLI.CallConv;
593 bool isVarArg = CLI.IsVarArg;
595 // MSP430 target does not yet support tail call optimization.
600 llvm_unreachable("Unsupported calling convention");
601 case CallingConv::MSP430_BUILTIN:
602 case CallingConv::Fast:
604 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
605 Outs, OutVals, Ins, dl, DAG, InVals);
606 case CallingConv::MSP430_INTR:
607 report_fatal_error("ISRs cannot be called directly");
611 /// LowerCCCArguments - transform physical registers into virtual registers and
612 /// generate load operations for arguments places on the stack.
613 // FIXME: struct return stuff
614 SDValue MSP430TargetLowering::LowerCCCArguments(
615 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
616 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
617 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
618 MachineFunction &MF = DAG.getMachineFunction();
619 MachineFrameInfo &MFI = MF.getFrameInfo();
620 MachineRegisterInfo &RegInfo = MF.getRegInfo();
621 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
623 // Assign locations to all of the incoming arguments.
624 SmallVector<CCValAssign, 16> ArgLocs;
625 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
627 AnalyzeArguments(CCInfo, ArgLocs, Ins);
629 // Create frame index for the start of the first vararg value
631 unsigned Offset = CCInfo.getNextStackOffset();
632 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, Offset, true));
635 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
636 CCValAssign &VA = ArgLocs[i];
638 // Arguments passed in registers
639 EVT RegVT = VA.getLocVT();
640 switch (RegVT.getSimpleVT().SimpleTy) {
644 errs() << "LowerFormalArguments Unhandled argument type: "
645 << RegVT.getEVTString() << "\n";
647 llvm_unreachable(nullptr);
650 unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
651 RegInfo.addLiveIn(VA.getLocReg(), VReg);
652 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
654 // If this is an 8-bit value, it is really passed promoted to 16
655 // bits. Insert an assert[sz]ext to capture this, then truncate to the
657 if (VA.getLocInfo() == CCValAssign::SExt)
658 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
659 DAG.getValueType(VA.getValVT()));
660 else if (VA.getLocInfo() == CCValAssign::ZExt)
661 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
662 DAG.getValueType(VA.getValVT()));
664 if (VA.getLocInfo() != CCValAssign::Full)
665 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
667 InVals.push_back(ArgValue);
671 assert(VA.isMemLoc());
674 ISD::ArgFlagsTy Flags = Ins[i].Flags;
676 if (Flags.isByVal()) {
677 int FI = MFI.CreateFixedObject(Flags.getByValSize(),
678 VA.getLocMemOffset(), true);
679 InVal = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
681 // Load the argument to a virtual register
682 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
684 errs() << "LowerFormalArguments Unhandled argument type: "
685 << EVT(VA.getLocVT()).getEVTString()
688 // Create the frame index object for this incoming parameter...
689 int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
691 // Create the SelectionDAG nodes corresponding to a load
692 //from this parameter
693 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
695 VA.getLocVT(), dl, Chain, FIN,
696 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
699 InVals.push_back(InVal);
703 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
704 if (Ins[i].Flags.isSRet()) {
705 unsigned Reg = FuncInfo->getSRetReturnReg();
707 Reg = MF.getRegInfo().createVirtualRegister(
708 getRegClassFor(MVT::i16));
709 FuncInfo->setSRetReturnReg(Reg);
711 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
712 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
720 MSP430TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
723 const SmallVectorImpl<ISD::OutputArg> &Outs,
724 LLVMContext &Context) const {
725 SmallVector<CCValAssign, 16> RVLocs;
726 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
727 return CCInfo.CheckReturn(Outs, RetCC_MSP430);
731 MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
733 const SmallVectorImpl<ISD::OutputArg> &Outs,
734 const SmallVectorImpl<SDValue> &OutVals,
735 const SDLoc &dl, SelectionDAG &DAG) const {
737 MachineFunction &MF = DAG.getMachineFunction();
739 // CCValAssign - represent the assignment of the return value to a location
740 SmallVector<CCValAssign, 16> RVLocs;
742 // ISRs cannot return any value.
743 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
744 report_fatal_error("ISRs cannot return any value");
746 // CCState - Info about the registers and stack slot.
747 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
750 // Analize return values.
751 AnalyzeReturnValues(CCInfo, RVLocs, Outs);
754 SmallVector<SDValue, 4> RetOps(1, Chain);
756 // Copy the result values into the output registers.
757 for (unsigned i = 0; i != RVLocs.size(); ++i) {
758 CCValAssign &VA = RVLocs[i];
759 assert(VA.isRegLoc() && "Can only return in registers!");
761 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
764 // Guarantee that all emitted copies are stuck together,
765 // avoiding something bad.
766 Flag = Chain.getValue(1);
767 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
770 if (MF.getFunction()->hasStructRetAttr()) {
771 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
772 unsigned Reg = FuncInfo->getSRetReturnReg();
775 llvm_unreachable("sret virtual register not created in entry block");
778 DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy(DAG.getDataLayout()));
779 unsigned R12 = MSP430::R12;
781 Chain = DAG.getCopyToReg(Chain, dl, R12, Val, Flag);
782 Flag = Chain.getValue(1);
783 RetOps.push_back(DAG.getRegister(R12, getPointerTy(DAG.getDataLayout())));
786 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
787 MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
789 RetOps[0] = Chain; // Update chain.
791 // Add the flag if we have it.
793 RetOps.push_back(Flag);
795 return DAG.getNode(Opc, dl, MVT::Other, RetOps);
798 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
799 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
800 SDValue MSP430TargetLowering::LowerCCCCallTo(
801 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
802 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
803 const SmallVectorImpl<SDValue> &OutVals,
804 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
805 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
806 // Analyze operands of the call, assigning locations to each operand.
807 SmallVector<CCValAssign, 16> ArgLocs;
808 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
810 AnalyzeArguments(CCInfo, ArgLocs, Outs);
812 // Get a count of how many bytes are to be pushed on the stack.
813 unsigned NumBytes = CCInfo.getNextStackOffset();
814 auto PtrVT = getPointerTy(DAG.getDataLayout());
816 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
818 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
819 SmallVector<SDValue, 12> MemOpChains;
822 // Walk the register/memloc assignments, inserting copies/loads.
823 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
824 CCValAssign &VA = ArgLocs[i];
826 SDValue Arg = OutVals[i];
828 // Promote the value if needed.
829 switch (VA.getLocInfo()) {
830 default: llvm_unreachable("Unknown loc info!");
831 case CCValAssign::Full: break;
832 case CCValAssign::SExt:
833 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
835 case CCValAssign::ZExt:
836 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
838 case CCValAssign::AExt:
839 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
843 // Arguments that can be passed on register must be kept at RegsToPass
846 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
848 assert(VA.isMemLoc());
850 if (!StackPtr.getNode())
851 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, PtrVT);
854 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
855 DAG.getIntPtrConstant(VA.getLocMemOffset(), dl));
858 ISD::ArgFlagsTy Flags = Outs[i].Flags;
860 if (Flags.isByVal()) {
861 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
862 MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
863 Flags.getByValAlign(),
865 /*AlwaysInline=*/true,
866 /*isTailCall=*/false,
867 MachinePointerInfo(),
868 MachinePointerInfo());
870 MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
873 MemOpChains.push_back(MemOp);
877 // Transform all store nodes into one single node because all store nodes are
878 // independent of each other.
879 if (!MemOpChains.empty())
880 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
882 // Build a sequence of copy-to-reg nodes chained together with token chain and
883 // flag operands which copy the outgoing args into registers. The InFlag in
884 // necessary since all emitted instructions must be stuck together.
886 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
887 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
888 RegsToPass[i].second, InFlag);
889 InFlag = Chain.getValue(1);
892 // If the callee is a GlobalAddress node (quite common, every direct call is)
893 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
894 // Likewise ExternalSymbol -> TargetExternalSymbol.
895 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
896 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
897 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
898 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
900 // Returns a chain & a flag for retval copy to use.
901 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
902 SmallVector<SDValue, 8> Ops;
903 Ops.push_back(Chain);
904 Ops.push_back(Callee);
906 // Add argument registers to the end of the list so that they are
907 // known live into the call.
908 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
909 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
910 RegsToPass[i].second.getValueType()));
912 if (InFlag.getNode())
913 Ops.push_back(InFlag);
915 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
916 InFlag = Chain.getValue(1);
918 // Create the CALLSEQ_END node.
919 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
920 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
921 InFlag = Chain.getValue(1);
923 // Handle result values, copying them out of physregs into vregs that we
925 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
929 /// LowerCallResult - Lower the result values of a call into the
930 /// appropriate copies out of appropriate physical registers.
932 SDValue MSP430TargetLowering::LowerCallResult(
933 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
934 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
935 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
937 // Assign locations to each value returned by this call.
938 SmallVector<CCValAssign, 16> RVLocs;
939 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
942 AnalyzeReturnValues(CCInfo, RVLocs, Ins);
944 // Copy all of the result registers out of their specified physreg.
945 for (unsigned i = 0; i != RVLocs.size(); ++i) {
946 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
947 RVLocs[i].getValVT(), InFlag).getValue(1);
948 InFlag = Chain.getValue(2);
949 InVals.push_back(Chain.getValue(0));
955 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
956 SelectionDAG &DAG) const {
957 unsigned Opc = Op.getOpcode();
958 SDNode* N = Op.getNode();
959 EVT VT = Op.getValueType();
962 // Expand non-constant shifts to loops:
963 if (!isa<ConstantSDNode>(N->getOperand(1)))
965 default: llvm_unreachable("Invalid shift opcode!");
967 return DAG.getNode(MSP430ISD::SHL, dl,
968 VT, N->getOperand(0), N->getOperand(1));
970 return DAG.getNode(MSP430ISD::SRA, dl,
971 VT, N->getOperand(0), N->getOperand(1));
973 return DAG.getNode(MSP430ISD::SRL, dl,
974 VT, N->getOperand(0), N->getOperand(1));
977 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
979 // Expand the stuff into sequence of shifts.
980 // FIXME: for some shift amounts this might be done better!
981 // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
982 SDValue Victim = N->getOperand(0);
984 if (Opc == ISD::SRL && ShiftAmount) {
985 // Emit a special goodness here:
986 // srl A, 1 => clrc; rrc A
987 Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
991 while (ShiftAmount--)
992 Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
998 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
999 SelectionDAG &DAG) const {
1000 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1001 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1002 auto PtrVT = getPointerTy(DAG.getDataLayout());
1004 // Create the TargetGlobalAddress node, folding in the constant offset.
1005 SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), PtrVT, Offset);
1006 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op), PtrVT, Result);
1009 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
1010 SelectionDAG &DAG) const {
1012 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
1013 auto PtrVT = getPointerTy(DAG.getDataLayout());
1014 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT);
1016 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
1019 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
1020 SelectionDAG &DAG) const {
1022 auto PtrVT = getPointerTy(DAG.getDataLayout());
1023 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1024 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
1026 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
1029 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
1030 ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
1031 // FIXME: Handle bittests someday
1032 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
1034 // FIXME: Handle jump negative someday
1035 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
1037 default: llvm_unreachable("Invalid integer condition!");
1039 TCC = MSP430CC::COND_E; // aka COND_Z
1040 // Minor optimization: if LHS is a constant, swap operands, then the
1041 // constant can be folded into comparison.
1042 if (LHS.getOpcode() == ISD::Constant)
1043 std::swap(LHS, RHS);
1046 TCC = MSP430CC::COND_NE; // aka COND_NZ
1047 // Minor optimization: if LHS is a constant, swap operands, then the
1048 // constant can be folded into comparison.
1049 if (LHS.getOpcode() == ISD::Constant)
1050 std::swap(LHS, RHS);
1053 std::swap(LHS, RHS);
1056 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
1057 // fold constant into instruction.
1058 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1060 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1061 TCC = MSP430CC::COND_LO;
1064 TCC = MSP430CC::COND_HS; // aka COND_C
1067 std::swap(LHS, RHS);
1070 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
1071 // fold constant into instruction.
1072 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1074 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1075 TCC = MSP430CC::COND_HS;
1078 TCC = MSP430CC::COND_LO; // aka COND_NC
1081 std::swap(LHS, RHS);
1084 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
1085 // fold constant into instruction.
1086 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1088 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1089 TCC = MSP430CC::COND_L;
1092 TCC = MSP430CC::COND_GE;
1095 std::swap(LHS, RHS);
1098 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
1099 // fold constant into instruction.
1100 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
1102 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
1103 TCC = MSP430CC::COND_GE;
1106 TCC = MSP430CC::COND_L;
1110 TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
1111 return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
1115 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1116 SDValue Chain = Op.getOperand(0);
1117 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1118 SDValue LHS = Op.getOperand(2);
1119 SDValue RHS = Op.getOperand(3);
1120 SDValue Dest = Op.getOperand(4);
1124 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1126 return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
1127 Chain, Dest, TargetCC, Flag);
1130 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1131 SDValue LHS = Op.getOperand(0);
1132 SDValue RHS = Op.getOperand(1);
1135 // If we are doing an AND and testing against zero, then the CMP
1136 // will not be generated. The AND (or BIT) will generate the condition codes,
1137 // but they are different from CMP.
1138 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
1139 // lowering & isel wouldn't diverge.
1141 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1142 if (RHSC->isNullValue() && LHS.hasOneUse() &&
1143 (LHS.getOpcode() == ISD::AND ||
1144 (LHS.getOpcode() == ISD::TRUNCATE &&
1145 LHS.getOperand(0).getOpcode() == ISD::AND))) {
1149 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1151 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1153 // Get the condition codes directly from the status register, if its easy.
1154 // Otherwise a branch will be generated. Note that the AND and BIT
1155 // instructions generate different flags than CMP, the carry bit can be used
1157 bool Invert = false;
1159 bool Convert = true;
1160 switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
1164 case MSP430CC::COND_HS:
1165 // Res = SR & 1, no processing is required
1167 case MSP430CC::COND_LO:
1171 case MSP430CC::COND_NE:
1173 // C = ~Z, thus Res = SR & 1, no processing is required
1175 // Res = ~((SR >> 1) & 1)
1180 case MSP430CC::COND_E:
1182 // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
1183 // Res = (SR >> 1) & 1 is 1 word shorter.
1186 EVT VT = Op.getValueType();
1187 SDValue One = DAG.getConstant(1, dl, VT);
1189 SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
1192 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
1193 SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
1194 SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
1196 SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
1199 SDValue Zero = DAG.getConstant(0, dl, VT);
1200 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1201 SDValue Ops[] = {One, Zero, TargetCC, Flag};
1202 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1206 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
1207 SelectionDAG &DAG) const {
1208 SDValue LHS = Op.getOperand(0);
1209 SDValue RHS = Op.getOperand(1);
1210 SDValue TrueV = Op.getOperand(2);
1211 SDValue FalseV = Op.getOperand(3);
1212 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1216 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1218 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1219 SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1221 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1224 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1225 SelectionDAG &DAG) const {
1226 SDValue Val = Op.getOperand(0);
1227 EVT VT = Op.getValueType();
1230 assert(VT == MVT::i16 && "Only support i16 for now!");
1232 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1233 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1234 DAG.getValueType(Val.getValueType()));
1238 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1239 MachineFunction &MF = DAG.getMachineFunction();
1240 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1241 int ReturnAddrIndex = FuncInfo->getRAIndex();
1242 auto PtrVT = getPointerTy(MF.getDataLayout());
1244 if (ReturnAddrIndex == 0) {
1245 // Set up a frame object for the return address.
1246 uint64_t SlotSize = MF.getDataLayout().getPointerSize();
1247 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize, -SlotSize,
1249 FuncInfo->setRAIndex(ReturnAddrIndex);
1252 return DAG.getFrameIndex(ReturnAddrIndex, PtrVT);
1255 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1256 SelectionDAG &DAG) const {
1257 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1258 MFI.setReturnAddressIsTaken(true);
1260 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1263 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1265 auto PtrVT = getPointerTy(DAG.getDataLayout());
1268 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1270 DAG.getConstant(DAG.getDataLayout().getPointerSize(), dl, MVT::i16);
1271 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1272 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
1273 MachinePointerInfo());
1276 // Just load the return address.
1277 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1278 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
1279 MachinePointerInfo());
1282 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1283 SelectionDAG &DAG) const {
1284 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1285 MFI.setFrameAddressIsTaken(true);
1287 EVT VT = Op.getValueType();
1288 SDLoc dl(Op); // FIXME probably not meaningful
1289 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1290 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1293 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1294 MachinePointerInfo());
1298 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1299 SelectionDAG &DAG) const {
1300 MachineFunction &MF = DAG.getMachineFunction();
1301 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1302 auto PtrVT = getPointerTy(DAG.getDataLayout());
1304 // Frame index of first vararg argument
1305 SDValue FrameIndex =
1306 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1307 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1309 // Create a store of the frame index to the location operand
1310 return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex, Op.getOperand(1),
1311 MachinePointerInfo(SV));
1314 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1315 SelectionDAG &DAG) const {
1316 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1317 auto PtrVT = getPointerTy(DAG.getDataLayout());
1318 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1319 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT), PtrVT, Result);
1322 /// getPostIndexedAddressParts - returns true by value, base pointer and
1323 /// offset pointer and addressing mode by reference if this node can be
1324 /// combined with a load / store to form a post-indexed load / store.
1325 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1328 ISD::MemIndexedMode &AM,
1329 SelectionDAG &DAG) const {
1331 LoadSDNode *LD = cast<LoadSDNode>(N);
1332 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1335 EVT VT = LD->getMemoryVT();
1336 if (VT != MVT::i8 && VT != MVT::i16)
1339 if (Op->getOpcode() != ISD::ADD)
1342 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1343 uint64_t RHSC = RHS->getZExtValue();
1344 if ((VT == MVT::i16 && RHSC != 2) ||
1345 (VT == MVT::i8 && RHSC != 1))
1348 Base = Op->getOperand(0);
1349 Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1358 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1359 switch ((MSP430ISD::NodeType)Opcode) {
1360 case MSP430ISD::FIRST_NUMBER: break;
1361 case MSP430ISD::RET_FLAG: return "MSP430ISD::RET_FLAG";
1362 case MSP430ISD::RETI_FLAG: return "MSP430ISD::RETI_FLAG";
1363 case MSP430ISD::RRA: return "MSP430ISD::RRA";
1364 case MSP430ISD::RLA: return "MSP430ISD::RLA";
1365 case MSP430ISD::RRC: return "MSP430ISD::RRC";
1366 case MSP430ISD::CALL: return "MSP430ISD::CALL";
1367 case MSP430ISD::Wrapper: return "MSP430ISD::Wrapper";
1368 case MSP430ISD::BR_CC: return "MSP430ISD::BR_CC";
1369 case MSP430ISD::CMP: return "MSP430ISD::CMP";
1370 case MSP430ISD::SETCC: return "MSP430ISD::SETCC";
1371 case MSP430ISD::SELECT_CC: return "MSP430ISD::SELECT_CC";
1372 case MSP430ISD::SHL: return "MSP430ISD::SHL";
1373 case MSP430ISD::SRA: return "MSP430ISD::SRA";
1374 case MSP430ISD::SRL: return "MSP430ISD::SRL";
1379 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1381 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1384 return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1387 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1388 if (!VT1.isInteger() || !VT2.isInteger())
1391 return (VT1.getSizeInBits() > VT2.getSizeInBits());
1394 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1395 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1396 return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1399 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1400 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1401 return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1404 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1405 return isZExtFree(Val.getValueType(), VT2);
1408 //===----------------------------------------------------------------------===//
1409 // Other Lowering Code
1410 //===----------------------------------------------------------------------===//
1413 MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1414 MachineBasicBlock *BB) const {
1415 MachineFunction *F = BB->getParent();
1416 MachineRegisterInfo &RI = F->getRegInfo();
1417 DebugLoc dl = MI.getDebugLoc();
1418 const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1421 const TargetRegisterClass * RC;
1422 switch (MI.getOpcode()) {
1423 default: llvm_unreachable("Invalid shift opcode!");
1425 Opc = MSP430::SHL8r1;
1426 RC = &MSP430::GR8RegClass;
1429 Opc = MSP430::SHL16r1;
1430 RC = &MSP430::GR16RegClass;
1433 Opc = MSP430::SAR8r1;
1434 RC = &MSP430::GR8RegClass;
1437 Opc = MSP430::SAR16r1;
1438 RC = &MSP430::GR16RegClass;
1441 Opc = MSP430::SAR8r1c;
1442 RC = &MSP430::GR8RegClass;
1445 Opc = MSP430::SAR16r1c;
1446 RC = &MSP430::GR16RegClass;
1450 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1451 MachineFunction::iterator I = ++BB->getIterator();
1453 // Create loop block
1454 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1455 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1457 F->insert(I, LoopBB);
1458 F->insert(I, RemBB);
1460 // Update machine-CFG edges by transferring all successors of the current
1461 // block to the block containing instructions after shift.
1462 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1464 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1466 // Add edges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1467 BB->addSuccessor(LoopBB);
1468 BB->addSuccessor(RemBB);
1469 LoopBB->addSuccessor(RemBB);
1470 LoopBB->addSuccessor(LoopBB);
1472 unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1473 unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1474 unsigned ShiftReg = RI.createVirtualRegister(RC);
1475 unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1476 unsigned ShiftAmtSrcReg = MI.getOperand(2).getReg();
1477 unsigned SrcReg = MI.getOperand(1).getReg();
1478 unsigned DstReg = MI.getOperand(0).getReg();
1483 BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1484 .addReg(ShiftAmtSrcReg).addImm(0);
1485 BuildMI(BB, dl, TII.get(MSP430::JCC))
1487 .addImm(MSP430CC::COND_E);
1490 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1491 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1492 // ShiftReg2 = shift ShiftReg
1493 // ShiftAmt2 = ShiftAmt - 1;
1494 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1495 .addReg(SrcReg).addMBB(BB)
1496 .addReg(ShiftReg2).addMBB(LoopBB);
1497 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1498 .addReg(ShiftAmtSrcReg).addMBB(BB)
1499 .addReg(ShiftAmtReg2).addMBB(LoopBB);
1500 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1502 BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1503 .addReg(ShiftAmtReg).addImm(1);
1504 BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1506 .addImm(MSP430CC::COND_NE);
1509 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1510 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1511 .addReg(SrcReg).addMBB(BB)
1512 .addReg(ShiftReg2).addMBB(LoopBB);
1514 MI.eraseFromParent(); // The pseudo instruction is gone now.
1519 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1520 MachineBasicBlock *BB) const {
1521 unsigned Opc = MI.getOpcode();
1523 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1524 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1525 Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1526 return EmitShiftInstr(MI, BB);
1528 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1529 DebugLoc dl = MI.getDebugLoc();
1531 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1532 "Unexpected instr type to insert");
1534 // To "insert" a SELECT instruction, we actually have to insert the diamond
1535 // control-flow pattern. The incoming instruction knows the destination vreg
1536 // to set, the condition code register to branch on, the true/false values to
1537 // select between, and a branch opcode to use.
1538 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1539 MachineFunction::iterator I = ++BB->getIterator();
1544 // cmpTY ccX, r1, r2
1546 // fallthrough --> copy0MBB
1547 MachineBasicBlock *thisMBB = BB;
1548 MachineFunction *F = BB->getParent();
1549 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1550 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1551 F->insert(I, copy0MBB);
1552 F->insert(I, copy1MBB);
1553 // Update machine-CFG edges by transferring all successors of the current
1554 // block to the new block which will contain the Phi node for the select.
1555 copy1MBB->splice(copy1MBB->begin(), BB,
1556 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1557 copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1558 // Next, add the true and fallthrough blocks as its successors.
1559 BB->addSuccessor(copy0MBB);
1560 BB->addSuccessor(copy1MBB);
1562 BuildMI(BB, dl, TII.get(MSP430::JCC))
1564 .addImm(MI.getOperand(3).getImm());
1567 // %FalseValue = ...
1568 // # fallthrough to copy1MBB
1571 // Update machine-CFG edges
1572 BB->addSuccessor(copy1MBB);
1575 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1578 BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI), MI.getOperand(0).getReg())
1579 .addReg(MI.getOperand(2).getReg())
1581 .addReg(MI.getOperand(1).getReg())
1584 MI.eraseFromParent(); // The pseudo instruction is gone now.