1//===- MSP430AsmParser.cpp - Parse MSP430 assembly to MCInst instructions -===//
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#include "MCTargetDesc/MSP430MCTargetDesc.h"
10#include "MSP430.h"
11#include "TargetInfo/MSP430TargetInfo.h"
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/MC/MCContext.h"
15#include "llvm/MC/MCExpr.h"
16#include "llvm/MC/MCInst.h"
17#include "llvm/MC/MCInstrInfo.h"
18#include "llvm/MC/MCParser/AsmLexer.h"
19#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20#include "llvm/MC/MCParser/MCTargetAsmParser.h"
21#include "llvm/MC/MCRegisterInfo.h"
22#include "llvm/MC/MCStreamer.h"
23#include "llvm/MC/MCSubtargetInfo.h"
24#include "llvm/MC/MCSymbol.h"
25#include "llvm/MC/MCValue.h"
26#include "llvm/MC/TargetRegistry.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/Debug.h"
29
30#define DEBUG_TYPE "msp430-asm-parser"
31
32using namespace llvm;
33
34namespace {
35
36/// Parses MSP430 assembly from a stream.
37class MSP430AsmParser : public MCTargetAsmParser {
38 MCAsmParser &Parser;
39 const MCRegisterInfo *MRI;
40
41 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
42 OperandVector &Operands, MCStreamer &Out,
43 uint64_t &ErrorInfo,
44 bool MatchingInlineAsm) override;
45
46 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
47 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
48 SMLoc &EndLoc) override;
49
50 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
51 SMLoc NameLoc, OperandVector &Operands) override;
52
53 ParseStatus parseDirective(AsmToken DirectiveID) override;
54 bool ParseDirectiveRefSym(AsmToken DirectiveID);
55
56 bool parseJccInstruction(ParseInstructionInfo &Info, StringRef Name,
57 SMLoc NameLoc, OperandVector &Operands);
58
59 bool ParseOperand(OperandVector &Operands);
60
61 bool ParseLiteralValues(unsigned Size, SMLoc L);
62
63 MCAsmParser &getParser() const { return Parser; }
64 AsmLexer &getLexer() const { return Parser.getLexer(); }
65
66 /// @name Auto-generated Matcher Functions
67 /// {
68
69#define GET_ASSEMBLER_HEADER
70#include "MSP430GenAsmMatcher.inc"
71
72 /// }
73
74public:
75 MSP430AsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
76 const MCInstrInfo &MII)
77 : MCTargetAsmParser(STI, MII), Parser(Parser) {
78 MCAsmParserExtension::Initialize(Parser);
79 MRI = getContext().getRegisterInfo();
80
81 setAvailableFeatures(ComputeAvailableFeatures(FB: STI.getFeatureBits()));
82 }
83};
84
85/// A parsed MSP430 assembly operand.
86class MSP430Operand : public MCParsedAsmOperand {
87 typedef MCParsedAsmOperand Base;
88
89 enum KindTy {
90 k_Imm,
91 k_Reg,
92 k_Tok,
93 k_Mem,
94 k_IndReg,
95 k_PostIndReg
96 } Kind;
97
98 struct Memory {
99 MCRegister Reg;
100 const MCExpr *Offset;
101 };
102 union {
103 const MCExpr *Imm;
104 MCRegister Reg;
105 StringRef Tok;
106 Memory Mem;
107 };
108
109 SMLoc Start, End;
110
111public:
112 MSP430Operand(StringRef Tok, SMLoc S)
113 : Kind(k_Tok), Tok(Tok), Start(S), End(S) {}
114 MSP430Operand(KindTy Kind, MCRegister Reg, SMLoc S, SMLoc E)
115 : Kind(Kind), Reg(Reg), Start(S), End(E) {}
116 MSP430Operand(MCExpr const *Imm, SMLoc S, SMLoc E)
117 : Kind(k_Imm), Imm(Imm), Start(S), End(E) {}
118 MSP430Operand(MCRegister Reg, MCExpr const *Expr, SMLoc S, SMLoc E)
119 : Kind(k_Mem), Mem({.Reg: Reg, .Offset: Expr}), Start(S), End(E) {}
120
121 void addRegOperands(MCInst &Inst, unsigned N) const {
122 assert((Kind == k_Reg || Kind == k_IndReg || Kind == k_PostIndReg) &&
123 "Unexpected operand kind");
124 assert(N == 1 && "Invalid number of operands!");
125
126 Inst.addOperand(Op: MCOperand::createReg(Reg: Reg));
127 }
128
129 void addExprOperand(MCInst &Inst, const MCExpr *Expr) const {
130 // Add as immediate when possible
131 if (!Expr)
132 Inst.addOperand(Op: MCOperand::createImm(Val: 0));
133 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Val: Expr))
134 Inst.addOperand(Op: MCOperand::createImm(Val: CE->getValue()));
135 else
136 Inst.addOperand(Op: MCOperand::createExpr(Val: Expr));
137 }
138
139 void addImmOperands(MCInst &Inst, unsigned N) const {
140 assert(Kind == k_Imm && "Unexpected operand kind");
141 assert(N == 1 && "Invalid number of operands!");
142
143 addExprOperand(Inst, Expr: Imm);
144 }
145
146 void addMemOperands(MCInst &Inst, unsigned N) const {
147 assert(Kind == k_Mem && "Unexpected operand kind");
148 assert(N == 2 && "Invalid number of operands");
149
150 Inst.addOperand(Op: MCOperand::createReg(Reg: Mem.Reg));
151 addExprOperand(Inst, Expr: Mem.Offset);
152 }
153
154 bool isReg() const override { return Kind == k_Reg; }
155 bool isImm() const override { return Kind == k_Imm; }
156 bool isToken() const override { return Kind == k_Tok; }
157 bool isMem() const override { return Kind == k_Mem; }
158 bool isIndReg() const { return Kind == k_IndReg; }
159 bool isPostIndReg() const { return Kind == k_PostIndReg; }
160
161 bool isCGImm() const {
162 if (Kind != k_Imm)
163 return false;
164
165 int64_t Val;
166 if (!Imm->evaluateAsAbsolute(Res&: Val))
167 return false;
168
169 if (Val == 0 || Val == 1 || Val == 2 || Val == 4 || Val == 8 || Val == -1)
170 return true;
171
172 return false;
173 }
174
175 StringRef getToken() const {
176 assert(Kind == k_Tok && "Invalid access!");
177 return Tok;
178 }
179
180 MCRegister getReg() const override {
181 assert(Kind == k_Reg && "Invalid access!");
182 return Reg;
183 }
184
185 static std::unique_ptr<MSP430Operand> CreateToken(StringRef Str, SMLoc S) {
186 return std::make_unique<MSP430Operand>(args&: Str, args&: S);
187 }
188
189 static std::unique_ptr<MSP430Operand> CreateReg(MCRegister Reg, SMLoc S,
190 SMLoc E) {
191 return std::make_unique<MSP430Operand>(args: k_Reg, args&: Reg, args&: S, args&: E);
192 }
193
194 static std::unique_ptr<MSP430Operand> CreateImm(const MCExpr *Val, SMLoc S,
195 SMLoc E) {
196 return std::make_unique<MSP430Operand>(args&: Val, args&: S, args&: E);
197 }
198
199 static std::unique_ptr<MSP430Operand>
200 CreateMem(MCRegister Reg, const MCExpr *Val, SMLoc S, SMLoc E) {
201 return std::make_unique<MSP430Operand>(args&: Reg, args&: Val, args&: S, args&: E);
202 }
203
204 static std::unique_ptr<MSP430Operand> CreateIndReg(MCRegister Reg, SMLoc S,
205 SMLoc E) {
206 return std::make_unique<MSP430Operand>(args: k_IndReg, args&: Reg, args&: S, args&: E);
207 }
208
209 static std::unique_ptr<MSP430Operand> CreatePostIndReg(MCRegister Reg,
210 SMLoc S, SMLoc E) {
211 return std::make_unique<MSP430Operand>(args: k_PostIndReg, args&: Reg, args&: S, args&: E);
212 }
213
214 SMLoc getStartLoc() const override { return Start; }
215 SMLoc getEndLoc() const override { return End; }
216
217 void print(raw_ostream &O, const MCAsmInfo &MAI) const override {
218 switch (Kind) {
219 case k_Tok:
220 O << "Token " << Tok;
221 break;
222 case k_Reg:
223 O << "Register " << Reg.id();
224 break;
225 case k_Imm:
226 O << "Immediate ";
227 MAI.printExpr(O, *Imm);
228 break;
229 case k_Mem:
230 O << "Memory ";
231 MAI.printExpr(O, *Mem.Offset);
232 break;
233 case k_IndReg:
234 O << "RegInd " << Reg.id();
235 break;
236 case k_PostIndReg:
237 O << "PostInc " << Reg.id();
238 break;
239 }
240 }
241};
242} // end anonymous namespace
243
244bool MSP430AsmParser::matchAndEmitInstruction(SMLoc Loc, unsigned &Opcode,
245 OperandVector &Operands,
246 MCStreamer &Out,
247 uint64_t &ErrorInfo,
248 bool MatchingInlineAsm) {
249 MCInst Inst;
250 unsigned MatchResult =
251 MatchInstructionImpl(Operands, Inst, ErrorInfo, matchingInlineAsm: MatchingInlineAsm);
252
253 switch (MatchResult) {
254 case Match_Success:
255 Inst.setLoc(Loc);
256 Out.emitInstruction(Inst, STI: *STI);
257 return false;
258 case Match_MnemonicFail:
259 return Error(L: Loc, Msg: "invalid instruction mnemonic");
260 case Match_InvalidOperand: {
261 SMLoc ErrorLoc = Loc;
262 if (ErrorInfo != ~0U) {
263 if (ErrorInfo >= Operands.size())
264 return Error(L: ErrorLoc, Msg: "too few operands for instruction");
265
266 ErrorLoc = ((MSP430Operand &)*Operands[ErrorInfo]).getStartLoc();
267 if (ErrorLoc == SMLoc())
268 ErrorLoc = Loc;
269 }
270 return Error(L: ErrorLoc, Msg: "invalid operand for instruction");
271 }
272 default:
273 return true;
274 }
275}
276
277// Auto-generated by TableGen
278static MCRegister MatchRegisterName(StringRef Name);
279static MCRegister MatchRegisterAltName(StringRef Name);
280
281bool MSP430AsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
282 SMLoc &EndLoc) {
283 ParseStatus Res = tryParseRegister(Reg, StartLoc, EndLoc);
284 if (Res.isFailure())
285 return Error(L: StartLoc, Msg: "invalid register name");
286 if (Res.isSuccess())
287 return false;
288 if (Res.isNoMatch())
289 return true;
290
291 llvm_unreachable("unknown parse status");
292}
293
294ParseStatus MSP430AsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
295 SMLoc &EndLoc) {
296 if (getLexer().getKind() == AsmToken::Identifier) {
297 auto Name = getLexer().getTok().getIdentifier().lower();
298 Reg = MatchRegisterName(Name);
299 if (Reg == MSP430::NoRegister) {
300 Reg = MatchRegisterAltName(Name);
301 if (Reg == MSP430::NoRegister)
302 return ParseStatus::NoMatch;
303 }
304
305 AsmToken const &T = getParser().getTok();
306 StartLoc = T.getLoc();
307 EndLoc = T.getEndLoc();
308 getLexer().Lex(); // eat register token
309
310 return ParseStatus::Success;
311 }
312
313 return ParseStatus::Failure;
314}
315
316bool MSP430AsmParser::parseJccInstruction(ParseInstructionInfo &Info,
317 StringRef Name, SMLoc NameLoc,
318 OperandVector &Operands) {
319 if (!Name.starts_with_insensitive(Prefix: "j"))
320 return true;
321
322 auto CC = Name.drop_front().lower();
323 unsigned CondCode;
324 if (CC == "ne" || CC == "nz")
325 CondCode = MSP430CC::COND_NE;
326 else if (CC == "eq" || CC == "z")
327 CondCode = MSP430CC::COND_E;
328 else if (CC == "lo" || CC == "nc")
329 CondCode = MSP430CC::COND_LO;
330 else if (CC == "hs" || CC == "c")
331 CondCode = MSP430CC::COND_HS;
332 else if (CC == "n")
333 CondCode = MSP430CC::COND_N;
334 else if (CC == "ge")
335 CondCode = MSP430CC::COND_GE;
336 else if (CC == "l")
337 CondCode = MSP430CC::COND_L;
338 else if (CC == "mp")
339 CondCode = MSP430CC::COND_NONE;
340 else
341 return Error(L: NameLoc, Msg: "unknown instruction");
342
343 if (CondCode == (unsigned)MSP430CC::COND_NONE)
344 Operands.push_back(Elt: MSP430Operand::CreateToken(Str: "jmp", S: NameLoc));
345 else {
346 Operands.push_back(Elt: MSP430Operand::CreateToken(Str: "j", S: NameLoc));
347 const MCExpr *CCode = MCConstantExpr::create(Value: CondCode, Ctx&: getContext());
348 Operands.push_back(Elt: MSP430Operand::CreateImm(Val: CCode, S: SMLoc(), E: SMLoc()));
349 }
350
351 // Skip optional '$' sign.
352 (void)parseOptionalToken(T: AsmToken::Dollar);
353
354 const MCExpr *Val;
355 SMLoc ExprLoc = getLexer().getLoc();
356 if (getParser().parseExpression(Res&: Val))
357 return Error(L: ExprLoc, Msg: "expected expression operand");
358
359 int64_t Res;
360 if (Val->evaluateAsAbsolute(Res))
361 if (Res < -512 || Res > 511)
362 return Error(L: ExprLoc, Msg: "invalid jump offset");
363
364 Operands.push_back(Elt: MSP430Operand::CreateImm(Val, S: ExprLoc,
365 E: getLexer().getLoc()));
366
367 if (getLexer().isNot(K: AsmToken::EndOfStatement)) {
368 SMLoc Loc = getLexer().getLoc();
369 getParser().eatToEndOfStatement();
370 return Error(L: Loc, Msg: "unexpected token");
371 }
372
373 getParser().Lex(); // Consume the EndOfStatement.
374 return false;
375}
376
377bool MSP430AsmParser::parseInstruction(ParseInstructionInfo &Info,
378 StringRef Name, SMLoc NameLoc,
379 OperandVector &Operands) {
380 // Drop .w suffix
381 if (Name.ends_with_insensitive(Suffix: ".w"))
382 Name = Name.drop_back(N: 2);
383
384 if (!parseJccInstruction(Info, Name, NameLoc, Operands))
385 return false;
386
387 // First operand is instruction mnemonic
388 Operands.push_back(Elt: MSP430Operand::CreateToken(Str: Name, S: NameLoc));
389
390 // If there are no more operands, then finish
391 if (getLexer().is(K: AsmToken::EndOfStatement))
392 return false;
393
394 // Parse first operand
395 if (ParseOperand(Operands))
396 return true;
397
398 // Parse second operand if any
399 if (parseOptionalToken(T: AsmToken::Comma) && ParseOperand(Operands))
400 return true;
401
402 if (getLexer().isNot(K: AsmToken::EndOfStatement)) {
403 SMLoc Loc = getLexer().getLoc();
404 getParser().eatToEndOfStatement();
405 return Error(L: Loc, Msg: "unexpected token");
406 }
407
408 getParser().Lex(); // Consume the EndOfStatement.
409 return false;
410}
411
412bool MSP430AsmParser::ParseDirectiveRefSym(AsmToken DirectiveID) {
413 StringRef Name;
414 if (getParser().parseIdentifier(Res&: Name))
415 return TokError(Msg: "expected identifier in directive");
416
417 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
418 getStreamer().emitSymbolAttribute(Symbol: Sym, Attribute: MCSA_Global);
419 return parseEOL();
420}
421
422ParseStatus MSP430AsmParser::parseDirective(AsmToken DirectiveID) {
423 StringRef IDVal = DirectiveID.getIdentifier();
424 if (IDVal.lower() == ".long")
425 return ParseLiteralValues(Size: 4, L: DirectiveID.getLoc());
426 if (IDVal.lower() == ".word" || IDVal.lower() == ".short")
427 return ParseLiteralValues(Size: 2, L: DirectiveID.getLoc());
428 if (IDVal.lower() == ".byte")
429 return ParseLiteralValues(Size: 1, L: DirectiveID.getLoc());
430 if (IDVal.lower() == ".refsym")
431 return ParseDirectiveRefSym(DirectiveID);
432 return ParseStatus::NoMatch;
433}
434
435bool MSP430AsmParser::ParseOperand(OperandVector &Operands) {
436 switch (getLexer().getKind()) {
437 default: return true;
438 case AsmToken::Identifier: {
439 // try rN
440 MCRegister RegNo;
441 SMLoc StartLoc, EndLoc;
442 if (!parseRegister(Reg&: RegNo, StartLoc, EndLoc)) {
443 Operands.push_back(Elt: MSP430Operand::CreateReg(Reg: RegNo, S: StartLoc, E: EndLoc));
444 return false;
445 }
446 [[fallthrough]];
447 }
448 case AsmToken::Integer:
449 case AsmToken::Plus:
450 case AsmToken::Minus: {
451 SMLoc StartLoc = getParser().getTok().getLoc();
452 const MCExpr *Val;
453 // Try constexpr[(rN)]
454 if (!getParser().parseExpression(Res&: Val)) {
455 MCRegister RegNo = MSP430::PC;
456 SMLoc EndLoc = getParser().getTok().getLoc();
457 // Try (rN)
458 if (parseOptionalToken(T: AsmToken::LParen)) {
459 SMLoc RegStartLoc;
460 if (parseRegister(Reg&: RegNo, StartLoc&: RegStartLoc, EndLoc))
461 return true;
462 EndLoc = getParser().getTok().getEndLoc();
463 if (!parseOptionalToken(T: AsmToken::RParen))
464 return true;
465 }
466 Operands.push_back(Elt: MSP430Operand::CreateMem(Reg: RegNo, Val, S: StartLoc,
467 E: EndLoc));
468 return false;
469 }
470 return true;
471 }
472 case AsmToken::Amp: {
473 // Try &constexpr
474 SMLoc StartLoc = getParser().getTok().getLoc();
475 getLexer().Lex(); // Eat '&'
476 const MCExpr *Val;
477 if (!getParser().parseExpression(Res&: Val)) {
478 SMLoc EndLoc = getParser().getTok().getLoc();
479 Operands.push_back(Elt: MSP430Operand::CreateMem(Reg: MSP430::SR, Val, S: StartLoc,
480 E: EndLoc));
481 return false;
482 }
483 return true;
484 }
485 case AsmToken::At: {
486 // Try @rN[+]
487 SMLoc StartLoc = getParser().getTok().getLoc();
488 getLexer().Lex(); // Eat '@'
489 MCRegister RegNo;
490 SMLoc RegStartLoc, EndLoc;
491 if (parseRegister(Reg&: RegNo, StartLoc&: RegStartLoc, EndLoc))
492 return true;
493 if (parseOptionalToken(T: AsmToken::Plus)) {
494 Operands.push_back(Elt: MSP430Operand::CreatePostIndReg(Reg: RegNo, S: StartLoc, E: EndLoc));
495 return false;
496 }
497 if (Operands.size() > 1) // Emulate @rd in destination position as 0(rd)
498 Operands.push_back(Elt: MSP430Operand::CreateMem(Reg: RegNo,
499 Val: MCConstantExpr::create(Value: 0, Ctx&: getContext()), S: StartLoc, E: EndLoc));
500 else
501 Operands.push_back(Elt: MSP430Operand::CreateIndReg(Reg: RegNo, S: StartLoc, E: EndLoc));
502 return false;
503 }
504 case AsmToken::Hash:
505 // Try #constexpr
506 SMLoc StartLoc = getParser().getTok().getLoc();
507 getLexer().Lex(); // Eat '#'
508 const MCExpr *Val;
509 if (!getParser().parseExpression(Res&: Val)) {
510 SMLoc EndLoc = getParser().getTok().getLoc();
511 Operands.push_back(Elt: MSP430Operand::CreateImm(Val, S: StartLoc, E: EndLoc));
512 return false;
513 }
514 return true;
515 }
516}
517
518bool MSP430AsmParser::ParseLiteralValues(unsigned Size, SMLoc L) {
519 auto parseOne = [&]() -> bool {
520 const MCExpr *Value;
521 if (getParser().parseExpression(Res&: Value))
522 return true;
523 getParser().getStreamer().emitValue(Value, Size, Loc: L);
524 return false;
525 };
526 return (parseMany(parseOne));
527}
528
529extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
530LLVMInitializeMSP430AsmParser() {
531 RegisterMCAsmParser<MSP430AsmParser> X(getTheMSP430Target());
532}
533
534#define GET_REGISTER_MATCHER
535#define GET_MATCHER_IMPLEMENTATION
536#include "MSP430GenAsmMatcher.inc"
537