LLVM 24.0.0git
MSP430AsmParser.cpp
Go to the documentation of this file.
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
10#include "MSP430.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"
22#include "llvm/MC/MCStreamer.h"
24#include "llvm/MC/MCSymbol.h"
25#include "llvm/MC/MCValue.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
40 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
43 bool MatchingInlineAsm) override;
44
45 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
46 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
47 SMLoc &EndLoc) override;
48
49 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
50 SMLoc NameLoc, OperandVector &Operands) override;
51
52 ParseStatus parseDirective(AsmToken DirectiveID) override;
53 bool ParseDirectiveRefSym(AsmToken DirectiveID);
54
55 bool parseJccInstruction(ParseInstructionInfo &Info, StringRef Name,
56 SMLoc NameLoc, OperandVector &Operands);
57
58 bool ParseOperand(OperandVector &Operands);
59
60 bool ParseLiteralValues(unsigned Size, SMLoc L);
61
62 MCAsmParser &getParser() const { return Parser; }
63 AsmLexer &getLexer() const { return Parser.getLexer(); }
64
65 /// @name Auto-generated Matcher Functions
66 /// {
67
68#define GET_ASSEMBLER_HEADER
69#include "MSP430GenAsmMatcher.inc"
70
71 /// }
72
73public:
74 MSP430AsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
75 const MCInstrInfo &MII)
76 : MCTargetAsmParser(STI, MII), Parser(Parser) {
78
79 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
80 }
81};
82
83/// A parsed MSP430 assembly operand.
84class MSP430Operand : public MCParsedAsmOperand {
85 typedef MCParsedAsmOperand Base;
86
87 enum KindTy {
88 k_Imm,
89 k_Reg,
90 k_Tok,
91 k_Mem,
92 k_IndReg,
93 k_PostIndReg
94 } Kind;
95
96 struct Memory {
97 MCRegister Reg;
98 const MCExpr *Offset;
99 };
100 union {
101 const MCExpr *Imm;
102 MCRegister Reg;
103 StringRef Tok;
104 Memory Mem;
105 };
106
107 SMLoc Start, End;
108
109public:
110 MSP430Operand(StringRef Tok, SMLoc S)
111 : Kind(k_Tok), Tok(Tok), Start(S), End(S) {}
112 MSP430Operand(KindTy Kind, MCRegister Reg, SMLoc S, SMLoc E)
113 : Kind(Kind), Reg(Reg), Start(S), End(E) {}
114 MSP430Operand(MCExpr const *Imm, SMLoc S, SMLoc E)
115 : Kind(k_Imm), Imm(Imm), Start(S), End(E) {}
116 MSP430Operand(MCRegister Reg, MCExpr const *Expr, SMLoc S, SMLoc E)
117 : Kind(k_Mem), Mem({Reg, Expr}), Start(S), End(E) {}
118
119 void addRegOperands(MCInst &Inst, unsigned N) const {
120 assert((Kind == k_Reg || Kind == k_IndReg || Kind == k_PostIndReg) &&
121 "Unexpected operand kind");
122 assert(N == 1 && "Invalid number of operands!");
123
125 }
126
127 void addExprOperand(MCInst &Inst, const MCExpr *Expr) const {
128 // Add as immediate when possible
129 if (!Expr)
131 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
132 Inst.addOperand(MCOperand::createImm(CE->getValue()));
133 else
135 }
136
137 void addImmOperands(MCInst &Inst, unsigned N) const {
138 assert(Kind == k_Imm && "Unexpected operand kind");
139 assert(N == 1 && "Invalid number of operands!");
140
141 addExprOperand(Inst, Imm);
142 }
143
144 void addMemOperands(MCInst &Inst, unsigned N) const {
145 assert(Kind == k_Mem && "Unexpected operand kind");
146 assert(N == 2 && "Invalid number of operands");
147
148 Inst.addOperand(MCOperand::createReg(Mem.Reg));
149 addExprOperand(Inst, Mem.Offset);
150 }
151
152 bool isReg() const override { return Kind == k_Reg; }
153 bool isImm() const override { return Kind == k_Imm; }
154 bool isToken() const override { return Kind == k_Tok; }
155 bool isMem() const override { return Kind == k_Mem; }
156 bool isIndReg() const { return Kind == k_IndReg; }
157 bool isPostIndReg() const { return Kind == k_PostIndReg; }
158
159 bool isCGImm() const {
160 if (Kind != k_Imm)
161 return false;
162
163 int64_t Val;
164 if (!Imm->evaluateAsAbsolute(Val))
165 return false;
166
167 if (Val == 0 || Val == 1 || Val == 2 || Val == 4 || Val == 8 || Val == -1)
168 return true;
169
170 return false;
171 }
172
173 StringRef getToken() const {
174 assert(Kind == k_Tok && "Invalid access!");
175 return Tok;
176 }
177
178 MCRegister getReg() const override {
179 assert(Kind == k_Reg && "Invalid access!");
180 return Reg;
181 }
182
183 static std::unique_ptr<MSP430Operand> CreateToken(StringRef Str, SMLoc S) {
184 return std::make_unique<MSP430Operand>(Str, S);
185 }
186
187 static std::unique_ptr<MSP430Operand> CreateReg(MCRegister Reg, SMLoc S,
188 SMLoc E) {
189 return std::make_unique<MSP430Operand>(k_Reg, Reg, S, E);
190 }
191
192 static std::unique_ptr<MSP430Operand> CreateImm(const MCExpr *Val, SMLoc S,
193 SMLoc E) {
194 return std::make_unique<MSP430Operand>(Val, S, E);
195 }
196
197 static std::unique_ptr<MSP430Operand>
198 CreateMem(MCRegister Reg, const MCExpr *Val, SMLoc S, SMLoc E) {
199 return std::make_unique<MSP430Operand>(Reg, Val, S, E);
200 }
201
202 static std::unique_ptr<MSP430Operand> CreateIndReg(MCRegister Reg, SMLoc S,
203 SMLoc E) {
204 return std::make_unique<MSP430Operand>(k_IndReg, Reg, S, E);
205 }
206
207 static std::unique_ptr<MSP430Operand> CreatePostIndReg(MCRegister Reg,
208 SMLoc S, SMLoc E) {
209 return std::make_unique<MSP430Operand>(k_PostIndReg, Reg, S, E);
210 }
211
212 SMLoc getStartLoc() const override { return Start; }
213 SMLoc getEndLoc() const override { return End; }
214
215 void print(raw_ostream &O, const MCAsmInfo &MAI) const override {
216 switch (Kind) {
217 case k_Tok:
218 O << "Token " << Tok;
219 break;
220 case k_Reg:
221 O << "Register " << Reg.id();
222 break;
223 case k_Imm:
224 O << "Immediate ";
225 MAI.printExpr(O, *Imm);
226 break;
227 case k_Mem:
228 O << "Memory ";
229 MAI.printExpr(O, *Mem.Offset);
230 break;
231 case k_IndReg:
232 O << "RegInd " << Reg.id();
233 break;
234 case k_PostIndReg:
235 O << "PostInc " << Reg.id();
236 break;
237 }
238 }
239};
240} // end anonymous namespace
241
242bool MSP430AsmParser::matchAndEmitInstruction(SMLoc Loc, unsigned &Opcode,
244 MCStreamer &Out,
246 bool MatchingInlineAsm) {
247 MCInst Inst;
248 unsigned MatchResult =
249 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
250
251 switch (MatchResult) {
252 case Match_Success:
253 Inst.setLoc(Loc);
254 Out.emitInstruction(Inst, *STI);
255 return false;
256 case Match_MnemonicFail:
257 return Error(Loc, "invalid instruction mnemonic");
258 case Match_InvalidOperand: {
259 SMLoc ErrorLoc = Loc;
260 if (ErrorInfo != ~0U) {
261 if (ErrorInfo >= Operands.size())
262 return Error(ErrorLoc, "too few operands for instruction");
263
264 ErrorLoc = ((MSP430Operand &)*Operands[ErrorInfo]).getStartLoc();
265 if (ErrorLoc == SMLoc())
266 ErrorLoc = Loc;
267 }
268 return Error(ErrorLoc, "invalid operand for instruction");
269 }
270 default:
271 return true;
272 }
273}
274
275// Auto-generated by TableGen
278
279bool MSP430AsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
280 SMLoc &EndLoc) {
281 ParseStatus Res = tryParseRegister(Reg, StartLoc, EndLoc);
282 if (Res.isFailure())
283 return Error(StartLoc, "invalid register name");
284 if (Res.isSuccess())
285 return false;
286 if (Res.isNoMatch())
287 return true;
288
289 llvm_unreachable("unknown parse status");
290}
291
292ParseStatus MSP430AsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
293 SMLoc &EndLoc) {
294 if (getLexer().getKind() == AsmToken::Identifier) {
295 auto Name = getLexer().getTok().getIdentifier().lower();
296 Reg = MatchRegisterName(Name);
297 if (Reg == MSP430::NoRegister) {
299 if (Reg == MSP430::NoRegister)
301 }
302
303 AsmToken const &T = getParser().getTok();
304 StartLoc = T.getLoc();
305 EndLoc = T.getEndLoc();
306 getLexer().Lex(); // eat register token
307
309 }
310
312}
313
314bool MSP430AsmParser::parseJccInstruction(ParseInstructionInfo &Info,
315 StringRef Name, SMLoc NameLoc,
317 if (!Name.starts_with_insensitive("j"))
318 return true;
319
320 auto CC = Name.drop_front().lower();
321 unsigned CondCode;
322 if (CC == "ne" || CC == "nz")
324 else if (CC == "eq" || CC == "z")
326 else if (CC == "lo" || CC == "nc")
328 else if (CC == "hs" || CC == "c")
330 else if (CC == "n")
332 else if (CC == "ge")
334 else if (CC == "l")
336 else if (CC == "mp")
338 else
339 return Error(NameLoc, "unknown instruction");
340
341 if (CondCode == (unsigned)MSP430CC::COND_NONE)
342 Operands.push_back(MSP430Operand::CreateToken("jmp", NameLoc));
343 else {
344 Operands.push_back(MSP430Operand::CreateToken("j", NameLoc));
345 const MCExpr *CCode = MCConstantExpr::create(CondCode, getContext());
346 Operands.push_back(MSP430Operand::CreateImm(CCode, SMLoc(), SMLoc()));
347 }
348
349 // Skip optional '$' sign.
350 (void)parseOptionalToken(AsmToken::Dollar);
351
352 const MCExpr *Val;
353 SMLoc ExprLoc = getLexer().getLoc();
354 if (getParser().parseExpression(Val))
355 return Error(ExprLoc, "expected expression operand");
356
357 int64_t Res;
358 if (Val->evaluateAsAbsolute(Res))
359 if (Res < -512 || Res > 511)
360 return Error(ExprLoc, "invalid jump offset");
361
362 Operands.push_back(MSP430Operand::CreateImm(Val, ExprLoc,
363 getLexer().getLoc()));
364
365 if (getLexer().isNot(AsmToken::EndOfStatement)) {
366 SMLoc Loc = getLexer().getLoc();
367 getParser().eatToEndOfStatement();
368 return Error(Loc, "unexpected token");
369 }
370
371 getParser().Lex(); // Consume the EndOfStatement.
372 return false;
373}
374
375bool MSP430AsmParser::parseInstruction(ParseInstructionInfo &Info,
376 StringRef Name, SMLoc NameLoc,
378 // Drop .w suffix
379 if (Name.ends_with_insensitive(".w"))
380 Name = Name.drop_back(2);
381
382 if (!parseJccInstruction(Info, Name, NameLoc, Operands))
383 return false;
384
385 // First operand is instruction mnemonic
386 Operands.push_back(MSP430Operand::CreateToken(Name, NameLoc));
387
388 // If there are no more operands, then finish
389 if (getLexer().is(AsmToken::EndOfStatement))
390 return false;
391
392 // Parse first operand
393 if (ParseOperand(Operands))
394 return true;
395
396 // Parse second operand if any
397 if (parseOptionalToken(AsmToken::Comma) && ParseOperand(Operands))
398 return true;
399
400 if (getLexer().isNot(AsmToken::EndOfStatement)) {
401 SMLoc Loc = getLexer().getLoc();
402 getParser().eatToEndOfStatement();
403 return Error(Loc, "unexpected token");
404 }
405
406 getParser().Lex(); // Consume the EndOfStatement.
407 return false;
408}
409
410bool MSP430AsmParser::ParseDirectiveRefSym(AsmToken DirectiveID) {
411 StringRef Name;
412 if (getParser().parseIdentifier(Name))
413 return TokError("expected identifier in directive");
414
415 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
416 getStreamer().emitSymbolAttribute(Sym, MCSA_Global);
417 return parseEOL();
418}
419
420ParseStatus MSP430AsmParser::parseDirective(AsmToken DirectiveID) {
421 StringRef IDVal = DirectiveID.getIdentifier();
422 if (IDVal.lower() == ".long")
423 return ParseLiteralValues(4, DirectiveID.getLoc());
424 if (IDVal.lower() == ".word" || IDVal.lower() == ".short")
425 return ParseLiteralValues(2, DirectiveID.getLoc());
426 if (IDVal.lower() == ".byte")
427 return ParseLiteralValues(1, DirectiveID.getLoc());
428 if (IDVal.lower() == ".refsym")
429 return ParseDirectiveRefSym(DirectiveID);
431}
432
433bool MSP430AsmParser::ParseOperand(OperandVector &Operands) {
434 switch (getLexer().getKind()) {
435 default: return true;
437 // try rN
438 MCRegister RegNo;
439 SMLoc StartLoc, EndLoc;
440 if (!parseRegister(RegNo, StartLoc, EndLoc)) {
441 Operands.push_back(MSP430Operand::CreateReg(RegNo, StartLoc, EndLoc));
442 return false;
443 }
444 [[fallthrough]];
445 }
447 case AsmToken::Plus:
448 case AsmToken::Minus: {
449 SMLoc StartLoc = getParser().getTok().getLoc();
450 const MCExpr *Val;
451 // Try constexpr[(rN)]
452 if (!getParser().parseExpression(Val)) {
453 MCRegister RegNo = MSP430::PC;
454 SMLoc EndLoc = getParser().getTok().getLoc();
455 // Try (rN)
456 if (parseOptionalToken(AsmToken::LParen)) {
457 SMLoc RegStartLoc;
458 if (parseRegister(RegNo, RegStartLoc, EndLoc))
459 return true;
460 EndLoc = getParser().getTok().getEndLoc();
461 if (!parseOptionalToken(AsmToken::RParen))
462 return true;
463 }
464 Operands.push_back(MSP430Operand::CreateMem(RegNo, Val, StartLoc,
465 EndLoc));
466 return false;
467 }
468 return true;
469 }
470 case AsmToken::Amp: {
471 // Try &constexpr
472 SMLoc StartLoc = getParser().getTok().getLoc();
473 getLexer().Lex(); // Eat '&'
474 const MCExpr *Val;
475 if (!getParser().parseExpression(Val)) {
476 SMLoc EndLoc = getParser().getTok().getLoc();
477 Operands.push_back(MSP430Operand::CreateMem(MSP430::SR, Val, StartLoc,
478 EndLoc));
479 return false;
480 }
481 return true;
482 }
483 case AsmToken::At: {
484 // Try @rN[+]
485 SMLoc StartLoc = getParser().getTok().getLoc();
486 getLexer().Lex(); // Eat '@'
487 MCRegister RegNo;
488 SMLoc RegStartLoc, EndLoc;
489 if (parseRegister(RegNo, RegStartLoc, EndLoc))
490 return true;
491 if (parseOptionalToken(AsmToken::Plus)) {
492 Operands.push_back(MSP430Operand::CreatePostIndReg(RegNo, StartLoc, EndLoc));
493 return false;
494 }
495 if (Operands.size() > 1) // Emulate @rd in destination position as 0(rd)
496 Operands.push_back(MSP430Operand::CreateMem(RegNo,
497 MCConstantExpr::create(0, getContext()), StartLoc, EndLoc));
498 else
499 Operands.push_back(MSP430Operand::CreateIndReg(RegNo, StartLoc, EndLoc));
500 return false;
501 }
502 case AsmToken::Hash:
503 // Try #constexpr
504 SMLoc StartLoc = getParser().getTok().getLoc();
505 getLexer().Lex(); // Eat '#'
506 const MCExpr *Val;
507 if (!getParser().parseExpression(Val)) {
508 SMLoc EndLoc = getParser().getTok().getLoc();
509 Operands.push_back(MSP430Operand::CreateImm(Val, StartLoc, EndLoc));
510 return false;
511 }
512 return true;
513 }
514}
515
516bool MSP430AsmParser::ParseLiteralValues(unsigned Size, SMLoc L) {
517 auto parseOne = [&]() -> bool {
518 const MCExpr *Value;
519 if (getParser().parseExpression(Value))
520 return true;
521 getParser().getStreamer().emitValue(Value, Size, L);
522 return false;
523 };
524 return (parseMany(parseOne));
525}
526
531
532#define GET_REGISTER_MATCHER
533#define GET_MATCHER_IMPLEMENTATION
534#include "MSP430GenAsmMatcher.inc"
static MCRegister MatchRegisterName(StringRef Name)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
static bool isNot(const MachineRegisterInfo &MRI, const MachineInstr &MI)
This file implements a class to represent arbitrary precision integral constant values and operations...
static MCRegister MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMSP430AsmParser()
Register Reg
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
RISCVCC::CondCode CC
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
Target independent representation for an assembler token.
Definition MCAsmMacro.h:22
LLVM_ABI SMLoc getLoc() const
Definition AsmLexer.cpp:31
StringRef getIdentifier() const
Get the identifier string for the current token, which should be an identifier or a string.
Definition MCAsmMacro.h:92
Base class for user error types.
Definition Error.h:354
void printExpr(raw_ostream &, const MCExpr &) const
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
Generic assembler parser interface, for use by target specific assembly parsers.
AsmLexer & getLexer()
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
void setLoc(SMLoc loc)
Definition MCInst.h:207
void addOperand(const MCOperand Op)
Definition MCInst.h:215
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
MCParsedAsmOperand - This abstract class represents a source-level assembly instruction operand.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Streaming machine code generation interface.
Definition MCStreamer.h:222
Generic base class for all target subtargets.
const FeatureBitset & getFeatureBits() const
MCTargetAsmParser - Generic interface to target specific assembly parsers.
Ternary parse status returned by various parse* methods.
constexpr bool isFailure() const
static constexpr StatusTy Failure
constexpr bool isSuccess() const
static constexpr StatusTy Success
static constexpr StatusTy NoMatch
constexpr bool isNoMatch() const
constexpr unsigned id() const
Definition Register.h:100
Represents a location in source code.
Definition SMLoc.h:22
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM_ABI std::string lower() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ COND_LO
Definition MSP430.h:30
@ COND_N
Definition MSP430.h:33
@ COND_L
Definition MSP430.h:32
@ COND_E
Definition MSP430.h:27
@ COND_GE
Definition MSP430.h:31
@ COND_NONE
Definition MSP430.h:34
@ COND_NE
Definition MSP430.h:28
@ COND_HS
Definition MSP430.h:29
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
static bool isMem(const MachineInstr &MI, unsigned Op)
LLVM_ABI std::pair< StringRef, StringRef > getToken(StringRef Source, StringRef Delimiters=" \t\n\v\f\r")
getToken - This function extracts one token from source, ignoring any leading characters that appear ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Target & getTheMSP430Target()
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SmallVectorImpl< std::unique_ptr< MCParsedAsmOperand > > OperandVector
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
@ MCSA_Global
.type _foo, @gnu_unique_object
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...