LLVM 24.0.0git
AVRAsmParser.cpp
Go to the documentation of this file.
1//===---- AVRAsmParser.cpp - Parse AVR 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
13
14#include "llvm/ADT/APInt.h"
15#include "llvm/MC/MCContext.h"
16#include "llvm/MC/MCExpr.h"
17#include "llvm/MC/MCInst.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"
30
31#include <array>
32
33#define DEBUG_TYPE "avr-asm-parser"
34
35using namespace llvm;
36
38 unsigned From = AVR::sub_lo) {
39 MCRegisterClass const *Class = &getAVRMCRegisterClass(AVR::DREGSRegClassID);
40 return MRI.getMatchingSuperReg(Reg, From, Class);
41}
42
43namespace {
44/// Parses AVR assembly from a stream.
45class AVRAsmParser : public MCTargetAsmParser {
46 MCAsmParser &Parser;
47 const MCRegisterInfo *MRI;
48 const std::string GENERATE_STUBS = "gs";
49
50 enum AVRMatchResultTy {
51 Match_InvalidRegisterOnTiny = FIRST_TARGET_MATCH_RESULT_TY + 1,
52 };
53
54#define GET_ASSEMBLER_HEADER
55#include "AVRGenAsmMatcher.inc"
56
57 bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
60 bool MatchingInlineAsm) override;
61
62 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
63 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
64 SMLoc &EndLoc) override;
65
66 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
67 SMLoc NameLoc, OperandVector &Operands) override;
68
69 ParseStatus parseDirective(AsmToken DirectiveID) override;
70
71 ParseStatus parseMemriOperand(OperandVector &Operands);
72
73 bool parseOperand(OperandVector &Operands, bool maybeReg);
74 MCRegister parseRegisterName(MCRegister (*matchFn)(StringRef));
75 MCRegister parseRegisterName();
76 MCRegister parseRegister(bool RestoreOnFailure = false);
77 bool tryParseRegisterOperand(OperandVector &Operands);
78 bool tryParseExpression(OperandVector &Operands, int64_t offset);
79 bool tryParseRelocExpression(OperandVector &Operands);
80 void eatComma();
81
82 unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
83 unsigned Kind) override;
84
85 bool emit(MCInst &Instruction, SMLoc Loc, MCStreamer &Out) const;
86 bool invalidOperand(SMLoc Loc, OperandVector const &Operands,
87 uint64_t const &ErrorInfo);
88 bool missingFeature(SMLoc Loc, uint64_t const &ErrorInfo);
89
90 ParseStatus parseLiteralValues(unsigned SizeInBytes, SMLoc L);
91
92public:
93 AVRAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
94 const MCInstrInfo &MII)
95 : MCTargetAsmParser(STI, MII), Parser(Parser) {
97 MRI = getContext().getRegisterInfo();
98
99 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
100 }
101
102 MCAsmParser &getParser() const { return Parser; }
103 AsmLexer &getLexer() const { return Parser.getLexer(); }
104};
105
106/// An parsed AVR assembly operand.
107class AVROperand : public MCParsedAsmOperand {
108 typedef MCParsedAsmOperand Base;
109 enum KindTy { k_Immediate, k_Register, k_Token, k_Memri } Kind;
110
111public:
112 AVROperand(StringRef Tok, SMLoc S)
113 : Kind(k_Token), Tok(Tok), Start(S), End(S) {}
114 AVROperand(MCRegister Reg, SMLoc S, SMLoc E,
115 const MCRegisterInfo *MRI = nullptr)
116 : Kind(k_Register), RegImm({Reg, nullptr}), Start(S), End(E), MRI(MRI) {}
117 AVROperand(MCExpr const *Imm, SMLoc S, SMLoc E,
118 const MCRegisterInfo *MRI = nullptr)
119 : Kind(k_Immediate), RegImm({0, Imm}), Start(S), End(E), MRI(MRI) {}
120 AVROperand(MCRegister Reg, MCExpr const *Imm, SMLoc S, SMLoc E)
121 : Kind(k_Memri), RegImm({Reg, Imm}), Start(S), End(E) {}
122
123 struct RegisterImmediate {
124 MCRegister Reg;
125 MCExpr const *Imm;
126 };
127 union {
128 StringRef Tok;
129 RegisterImmediate RegImm;
130 };
131
132 SMLoc Start, End;
133 /// Needed to convert GPR8 registers to DREGS in addDREGSRegOperands.
134 const MCRegisterInfo *MRI = nullptr;
135
136public:
137 /// Returns the register for a register operand or a bare register number
138 /// (GCC accepts e.g. "24" for r24), or an invalid register otherwise.
139 MCRegister getRegOrBareNumber() const {
140 if (Kind == k_Register)
141 return getReg();
142 if (Kind == k_Immediate)
143 if (const auto *CE = dyn_cast<MCConstantExpr>(getImm()))
144 if (0 <= CE->getValue() && CE->getValue() <= 31)
145 return AVR::R0 + CE->getValue();
146 return MCRegister();
147 }
148
149 void addRegOperands(MCInst &Inst, unsigned N) const {
150 assert(N == 1 && "Invalid number of operands!");
151 MCRegister Reg = getRegOrBareNumber();
152 assert(Reg && "Unexpected operand kind");
154 }
155
156 void addDREGSRegOperands(MCInst &Inst, unsigned N) const {
157 assert(N == 1 && "Invalid number of operands!");
158 MCRegister Reg = getRegOrBareNumber();
159 assert(Reg && "Unexpected operand kind");
160 if (MCRegister DReg = toDREG(*MRI, Reg))
161 Reg = DReg;
163 }
164
165 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
166 // Add as immediate when possible
167 if (!Expr)
169 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
170 Inst.addOperand(MCOperand::createImm(CE->getValue()));
171 else
173 }
174
175 void addImmOperands(MCInst &Inst, unsigned N) const {
176 assert(Kind == k_Immediate && "Unexpected operand kind");
177 assert(N == 1 && "Invalid number of operands!");
178
179 const MCExpr *Expr = getImm();
180 addExpr(Inst, Expr);
181 }
182
183 /// Adds the contained reg+imm operand to an instruction.
184 void addMemriOperands(MCInst &Inst, unsigned N) const {
185 assert(Kind == k_Memri && "Unexpected operand kind");
186 assert(N == 2 && "Invalid number of operands");
187
189 addExpr(Inst, getImm());
190 }
191
192 void addImmCom8Operands(MCInst &Inst, unsigned N) const {
193 assert(N == 1 && "Invalid number of operands!");
194 // The operand is actually a imm8, but we have its bitwise
195 // negation in the assembly source, so twiddle it here.
196 const auto *CE = cast<MCConstantExpr>(getImm());
197 Inst.addOperand(MCOperand::createImm(~(uint8_t)CE->getValue()));
198 }
199
200 bool isImmCom8() const {
201 if (!isImm())
202 return false;
203 const auto *CE = dyn_cast<MCConstantExpr>(getImm());
204 if (!CE)
205 return false;
206 int64_t Value = CE->getValue();
207 return isUInt<8>(Value);
208 }
209
210 bool isReg() const override { return Kind == k_Register; }
211 bool isImm() const override { return Kind == k_Immediate; }
212 bool isToken() const override { return Kind == k_Token; }
213 bool isMem() const override { return Kind == k_Memri; }
214 bool isMemri() const { return Kind == k_Memri; }
215
216 StringRef getToken() const {
217 assert(Kind == k_Token && "Invalid access!");
218 return Tok;
219 }
220
221 MCRegister getReg() const override {
222 assert((Kind == k_Register || Kind == k_Memri) && "Invalid access!");
223
224 return RegImm.Reg;
225 }
226
227 const MCExpr *getImm() const {
228 assert((Kind == k_Immediate || Kind == k_Memri) && "Invalid access!");
229 return RegImm.Imm;
230 }
231
232 static std::unique_ptr<AVROperand> CreateToken(StringRef Str, SMLoc S) {
233 return std::make_unique<AVROperand>(Str, S);
234 }
235
236 static std::unique_ptr<AVROperand> CreateReg(MCRegister Reg, SMLoc S, SMLoc E,
237 const MCRegisterInfo *MRI) {
238 return std::make_unique<AVROperand>(Reg, S, E, MRI);
239 }
240
241 static std::unique_ptr<AVROperand>
242 CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, const MCRegisterInfo *MRI) {
243 return std::make_unique<AVROperand>(Val, S, E, MRI);
244 }
245
246 static std::unique_ptr<AVROperand>
247 CreateMemri(MCRegister Reg, const MCExpr *Val, SMLoc S, SMLoc E) {
248 return std::make_unique<AVROperand>(Reg, Val, S, E);
249 }
250
251 SMLoc getStartLoc() const override { return Start; }
252 SMLoc getEndLoc() const override { return End; }
253
254 void print(raw_ostream &O, const MCAsmInfo &MAI) const override {
255 switch (Kind) {
256 case k_Token:
257 O << "Token: \"" << getToken() << "\"";
258 break;
259 case k_Register:
260 O << "Register: " << getReg().id();
261 break;
262 case k_Immediate:
263 O << "Immediate: \"";
264 MAI.printExpr(O, *getImm());
265 O << "\"";
266 break;
267 case k_Memri: {
268 // only manually print the size for non-negative values,
269 // as the sign is inserted automatically.
270 O << "Memri: \"" << getReg().id() << '+';
271 MAI.printExpr(O, *getImm());
272 O << "\"";
273 break;
274 }
275 }
276 O << "\n";
277 }
278};
279
280} // end anonymous namespace.
281
282// Auto-generated Match Functions
283
284/// Maps from the set of all register names to a register number.
285/// \note Generated by TableGen.
287
288/// Maps from the set of all alternative registernames to a register number.
289/// \note Generated by TableGen.
291
292bool AVRAsmParser::invalidOperand(SMLoc Loc, OperandVector const &Operands,
293 uint64_t const &ErrorInfo) {
294 SMLoc ErrorLoc = Loc;
295 char const *Diag = nullptr;
296
297 if (ErrorInfo != ~0U) {
298 if (ErrorInfo >= Operands.size()) {
299 Diag = "too few operands for instruction.";
300 } else {
301 AVROperand const &Op = (AVROperand const &)*Operands[ErrorInfo];
302
303 // TODO: See if we can do a better error than just "invalid ...".
304 if (Op.getStartLoc() != SMLoc()) {
305 ErrorLoc = Op.getStartLoc();
306 }
307 }
308 }
309
310 if (!Diag) {
311 Diag = "invalid operand for instruction";
312 }
313
314 return Error(ErrorLoc, Diag);
315}
316
317bool AVRAsmParser::missingFeature(SMLoc Loc, uint64_t const &ErrorInfo) {
318 return Error(Loc, "instruction requires a CPU feature not currently enabled");
319}
320
321bool AVRAsmParser::emit(MCInst &Inst, SMLoc Loc, MCStreamer &Out) const {
322 Inst.setLoc(Loc);
323 Out.emitInstruction(Inst, *STI);
324
325 return false;
326}
327
328bool AVRAsmParser::matchAndEmitInstruction(SMLoc Loc, unsigned &Opcode,
330 MCStreamer &Out, uint64_t &ErrorInfo,
331 bool MatchingInlineAsm) {
332 MCInst Inst;
333 unsigned MatchResult =
334 MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
335
336 switch (MatchResult) {
337 case Match_Success:
338 return emit(Inst, Loc, Out);
339 case Match_MissingFeature:
340 return missingFeature(Loc, ErrorInfo);
341 case Match_InvalidOperand:
342 return invalidOperand(Loc, Operands, ErrorInfo);
343 case Match_MnemonicFail:
344 return Error(Loc, "invalid instruction");
345 case Match_InvalidRegisterOnTiny:
346 return Error(Loc, "invalid register on avrtiny");
347 default:
348 return true;
349 }
350}
351
352/// Parses a register name using a given matching function.
353/// Checks for lowercase or uppercase if necessary.
354MCRegister AVRAsmParser::parseRegisterName(MCRegister (*matchFn)(StringRef)) {
355 StringRef Name = Parser.getTok().getString();
356
357 MCRegister Reg = matchFn(Name);
358
359 // GCC supports case insensitive register names. Some of the AVR registers
360 // are all lower case, some are all upper case but non are mixed. We prefer
361 // to use the original names in the register definitions. That is why we
362 // have to test both upper and lower case here.
363 if (!Reg) {
364 Reg = matchFn(Name.lower());
365 }
366 if (!Reg) {
367 Reg = matchFn(Name.upper());
368 }
369
370 return Reg;
371}
372
373MCRegister AVRAsmParser::parseRegisterName() {
374 MCRegister Reg = parseRegisterName(&MatchRegisterName);
375
376 if (!Reg)
377 Reg = parseRegisterName(&MatchRegisterAltName);
378
379 return Reg;
380}
381
382MCRegister AVRAsmParser::parseRegister(bool RestoreOnFailure) {
383 MCRegister Reg;
384
385 if (Parser.getTok().is(AsmToken::Identifier)) {
386 // Check for register pair syntax
387 if (Parser.getLexer().peekTok().is(AsmToken::Colon)) {
388 AsmToken HighTok = Parser.getTok();
389 Parser.Lex();
390 AsmToken ColonTok = Parser.getTok();
391 Parser.Lex(); // Eat high (odd) register and colon
392
393 if (Parser.getTok().is(AsmToken::Identifier)) {
394 // Convert lower (even) register to DREG
395 Reg = toDREG(*MRI, parseRegisterName());
396 }
397 if (!Reg && RestoreOnFailure) {
398 getLexer().UnLex(std::move(ColonTok));
399 getLexer().UnLex(std::move(HighTok));
400 }
401 } else {
402 Reg = parseRegisterName();
403 }
404 }
405 return Reg;
406}
407
408bool AVRAsmParser::tryParseRegisterOperand(OperandVector &Operands) {
409 MCRegister Reg = parseRegister();
410
411 if (!Reg)
412 return true;
413
414 // Reject R0~R15 on avrtiny.
415 if (AVR::R0 <= Reg && Reg <= AVR::R15 &&
416 STI->hasFeature(AVR::FeatureTinyEncoding))
417 return Error(Parser.getTok().getLoc(), "invalid register on avrtiny");
418
419 AsmToken const &T = Parser.getTok();
420 Operands.push_back(
421 AVROperand::CreateReg(Reg, T.getLoc(), T.getEndLoc(), MRI));
422 Parser.Lex(); // Eat register token.
423
424 return false;
425}
426
427bool AVRAsmParser::tryParseExpression(OperandVector &Operands, int64_t offset) {
428 SMLoc S = Parser.getTok().getLoc();
429
430 if (!tryParseRelocExpression(Operands))
431 return false;
432
433 if ((Parser.getTok().getKind() == AsmToken::Plus ||
434 Parser.getTok().getKind() == AsmToken::Minus) &&
436 // Don't handle this case - it should be split into two
437 // separate tokens.
438 return true;
439 }
440
441 // Parse (potentially inner) expression
442 MCExpr const *Expression;
443 if (getParser().parseExpression(Expression))
444 return true;
445
446 if (offset) {
447 Expression = MCBinaryExpr::createAdd(
448 Expression, MCConstantExpr::create(offset, getContext()), getContext());
449 }
450
451 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
452 Operands.push_back(AVROperand::CreateImm(Expression, S, E, MRI));
453 return false;
454}
455
456bool AVRAsmParser::tryParseRelocExpression(OperandVector &Operands) {
457 bool isNegated = false;
458 AVR::Specifier ModifierKind = AVR::S_AVR_NONE;
459
460 SMLoc S = Parser.getTok().getLoc();
461
462 // Reject the form in which sign comes first. This behaviour is
463 // in accordance with avr-gcc.
464 AsmToken::TokenKind CurTok = Parser.getLexer().getKind();
465 if (CurTok == AsmToken::Minus || CurTok == AsmToken::Plus)
466 return true;
467
468 // Check for sign.
469 AsmToken tokens[2];
470 if (Parser.getLexer().peekTokens(tokens) == 2)
471 if (tokens[0].getKind() == AsmToken::LParen &&
472 tokens[1].getKind() == AsmToken::Minus)
473 isNegated = true;
474
475 // Check if we have a target specific modifier (lo8, hi8, &c)
476 if (CurTok != AsmToken::Identifier ||
477 Parser.getLexer().peekTok().getKind() != AsmToken::LParen) {
478 // Not a reloc expr
479 return true;
480 }
481 StringRef ModifierName = Parser.getTok().getString();
482 ModifierKind = AVRMCExpr::parseSpecifier(ModifierName);
483
484 if (ModifierKind != AVR::S_AVR_NONE) {
485 Parser.Lex();
486 Parser.Lex(); // Eat modifier name and parenthesis
487 if (Parser.getTok().getString() == GENERATE_STUBS &&
488 Parser.getTok().getKind() == AsmToken::Identifier) {
489 std::string GSModName = ModifierName.str() + "_" + GENERATE_STUBS;
490 ModifierKind = AVRMCExpr::parseSpecifier(GSModName);
491 if (ModifierKind != AVR::S_AVR_NONE)
492 Parser.Lex(); // Eat gs modifier name
493 }
494 } else {
495 return Error(Parser.getTok().getLoc(), "unknown modifier");
496 }
497
498 if (tokens[1].getKind() == AsmToken::Minus ||
499 tokens[1].getKind() == AsmToken::Plus) {
500 Parser.Lex();
501 assert(Parser.getTok().getKind() == AsmToken::LParen);
502 Parser.Lex(); // Eat the sign and parenthesis
503 }
504
505 MCExpr const *InnerExpression;
506 if (getParser().parseExpression(InnerExpression))
507 return true;
508
509 if (tokens[1].getKind() == AsmToken::Minus ||
510 tokens[1].getKind() == AsmToken::Plus) {
511 assert(Parser.getTok().getKind() == AsmToken::RParen);
512 Parser.Lex(); // Eat closing parenthesis
513 }
514
515 // If we have a modifier wrap the inner expression
516 assert(Parser.getTok().getKind() == AsmToken::RParen);
517 Parser.Lex(); // Eat closing parenthesis
518
519 MCExpr const *Expression =
520 AVRMCExpr::create(ModifierKind, InnerExpression, isNegated, getContext());
521
522 SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
523 Operands.push_back(AVROperand::CreateImm(Expression, S, E, MRI));
524
525 return false;
526}
527
528bool AVRAsmParser::parseOperand(OperandVector &Operands, bool maybeReg) {
529 LLVM_DEBUG(dbgs() << "parseOperand\n");
530
531 switch (getLexer().getKind()) {
532 default:
533 return Error(Parser.getTok().getLoc(), "unexpected token in operand");
534
536 // Try to parse a register, fall through to the next case if it fails.
537 if (maybeReg && !tryParseRegisterOperand(Operands)) {
538 return false;
539 }
540 [[fallthrough]];
541 case AsmToken::LParen:
543 return tryParseExpression(Operands, 0);
544 case AsmToken::Dot:
545 return tryParseExpression(Operands, 2);
546 case AsmToken::Plus:
547 case AsmToken::Minus: {
548 // If the sign preceeds a number, parse the number,
549 // otherwise treat the sign a an independent token.
550 switch (getLexer().peekTok().getKind()) {
552 case AsmToken::BigNum:
554 case AsmToken::Real:
555 if (!tryParseExpression(Operands, 0))
556 return false;
557 break;
558 default:
559 break;
560 }
561 // Treat the token as an independent token.
562 Operands.push_back(AVROperand::CreateToken(Parser.getTok().getString(),
563 Parser.getTok().getLoc()));
564 Parser.Lex(); // Eat the token.
565 return false;
566 }
567 }
568
569 // Could not parse operand
570 return true;
571}
572
573ParseStatus AVRAsmParser::parseMemriOperand(OperandVector &Operands) {
574 LLVM_DEBUG(dbgs() << "parseMemriOperand()\n");
575
576 SMLoc E, S;
577 MCExpr const *Expression;
578 MCRegister Reg;
579
580 // Parse register.
581 {
582 Reg = parseRegister();
583
584 if (!Reg)
586
587 S = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
588 Parser.Lex(); // Eat register token.
589 }
590
591 // Parse immediate;
592 {
593 if (getParser().parseExpression(Expression))
595
596 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
597 }
598
599 Operands.push_back(AVROperand::CreateMemri(Reg, Expression, S, E));
600
602}
603
604bool AVRAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
605 SMLoc &EndLoc) {
606 StartLoc = Parser.getTok().getLoc();
607 Reg = parseRegister(/*RestoreOnFailure=*/false);
608 EndLoc = Parser.getTok().getLoc();
609
610 return Reg == AVR::NoRegister;
611}
612
613ParseStatus AVRAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
614 SMLoc &EndLoc) {
615 StartLoc = Parser.getTok().getLoc();
616 Reg = parseRegister(/*RestoreOnFailure=*/true);
617 EndLoc = Parser.getTok().getLoc();
618
619 if (Reg == AVR::NoRegister)
622}
623
624void AVRAsmParser::eatComma() {
625 if (getLexer().is(AsmToken::Comma)) {
626 Parser.Lex();
627 } else {
628 // GCC allows commas to be omitted.
629 }
630}
631
632bool AVRAsmParser::parseInstruction(ParseInstructionInfo &Info,
633 StringRef Mnemonic, SMLoc NameLoc,
635 Operands.push_back(AVROperand::CreateToken(Mnemonic, NameLoc));
636
637 int OperandNum = -1;
638 while (getLexer().isNot(AsmToken::EndOfStatement)) {
639 OperandNum++;
640 if (OperandNum > 0)
641 eatComma();
642
643 ParseStatus ParseRes = MatchOperandParserImpl(Operands, Mnemonic);
644
645 if (ParseRes.isSuccess())
646 continue;
647
648 if (ParseRes.isFailure()) {
649 SMLoc Loc = getLexer().getLoc();
650 Parser.eatToEndOfStatement();
651
652 return Error(Loc, "failed to parse register and immediate pair");
653 }
654
655 // These specific operands should be treated as addresses/symbols/labels,
656 // other than registers.
657 bool maybeReg = true;
658
659 if (OperandNum == 1) {
660 std::array<StringRef, 8> Insts = {"lds", "adiw", "sbiw", "ldi"};
661 for (auto Inst : Insts) {
662 if (Inst == Mnemonic) {
663 maybeReg = false;
664 break;
665 }
666 }
667 } else if (OperandNum == 0) {
668 std::array<StringRef, 8> Insts = {"sts", "call", "rcall", "rjmp", "jmp"};
669 for (auto Inst : Insts) {
670 if (Inst == Mnemonic) {
671 maybeReg = false;
672 break;
673 }
674 }
675 }
676
677 if (parseOperand(Operands, maybeReg)) {
678 SMLoc Loc = getLexer().getLoc();
679 Parser.eatToEndOfStatement();
680 return Error(Loc, "unexpected token in argument list");
681 }
682 }
683 Parser.Lex(); // Consume the EndOfStatement
684 return false;
685}
686
687ParseStatus AVRAsmParser::parseDirective(llvm::AsmToken DirectiveID) {
688 StringRef IDVal = DirectiveID.getIdentifier();
689 if (IDVal.lower() == ".long")
690 return parseLiteralValues(SIZE_LONG, DirectiveID.getLoc());
691 if (IDVal.lower() == ".word" || IDVal.lower() == ".short")
692 return parseLiteralValues(SIZE_WORD, DirectiveID.getLoc());
693 if (IDVal.lower() == ".byte")
694 return parseLiteralValues(1, DirectiveID.getLoc());
696}
697
698ParseStatus AVRAsmParser::parseLiteralValues(unsigned SizeInBytes, SMLoc L) {
699 MCAsmParser &Parser = getParser();
700 AVRMCELFStreamer &AVRStreamer =
701 static_cast<AVRMCELFStreamer &>(Parser.getStreamer());
702 AsmToken Tokens[2];
703 size_t ReadCount = Parser.getLexer().peekTokens(Tokens);
704 if (ReadCount == 2 && Parser.getTok().getKind() == AsmToken::Identifier &&
705 Tokens[0].getKind() == AsmToken::Minus &&
706 Tokens[1].getKind() == AsmToken::Identifier) {
707 MCSymbol *Symbol = getContext().getOrCreateSymbol(".text");
708 AVRStreamer.emitValueForModiferKind(Symbol, SizeInBytes, L,
711 }
712
713 if (Parser.getTok().getKind() == AsmToken::Identifier &&
714 Parser.getLexer().peekTok().getKind() == AsmToken::LParen) {
715 StringRef ModifierName = Parser.getTok().getString();
716 AVR::Specifier Spec = AVRMCExpr::parseSpecifier(ModifierName);
717 if (Spec != AVR::S_AVR_NONE) {
718 Parser.Lex();
719 Parser.Lex(); // Eat the modifier and parenthesis
720 } else {
721 return Error(Parser.getTok().getLoc(), "unknown modifier");
722 }
724 getContext().getOrCreateSymbol(Parser.getTok().getString());
725 AVRStreamer.emitValueForModiferKind(Symbol, SizeInBytes, L, Spec);
726 Lex(); // Eat the symbol name.
727 if (parseToken(AsmToken::RParen))
729 return parseEOL();
730 }
731
732 auto parseOne = [&]() -> bool {
733 const MCExpr *Value;
734 if (Parser.parseExpression(Value))
735 return true;
736 Parser.getStreamer().emitValue(Value, SizeInBytes, L);
737 return false;
738 };
739 return (parseMany(parseOne));
740}
741
745
746#define GET_REGISTER_MATCHER
747#define GET_MATCHER_IMPLEMENTATION
748#include "AVRGenAsmMatcher.inc"
749
750// Uses enums defined in AVRGenAsmMatcher.inc
751unsigned AVRAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
752 unsigned ExpectedKind) {
753 AVROperand &Op = static_cast<AVROperand &>(AsmOp);
754 MatchClassKind Expected = static_cast<MatchClassKind>(ExpectedKind);
755 if (Expected <= MCK_LAST_TOKEN || Expected > MCK_LAST_REGISTER)
756 return Match_InvalidOperand;
757
758 // If need be, GCC converts bare numbers to register names
759 // It's ugly, but GCC supports it.
760 MCRegister Reg = Op.getRegOrBareNumber();
761 if (!Reg)
762 return Match_InvalidOperand;
763 if (Op.isImm()) {
764 // Reject R0~R15 on avrtiny.
765 if (Reg.id() - AVR::R0 <= 15 && STI->hasFeature(AVR::FeatureTinyEncoding))
766 return Match_InvalidRegisterOnTiny;
767 AVROperand RegOp(Reg, Op.getStartLoc(), Op.getEndLoc());
768 if (validateOperandClass(RegOp, Expected, *STI) == Match_Success)
769 return Match_Success;
770 }
771
772 // If the instruction uses a register pair but we got a single, lower
773 // register we perform a "class cast".
774 if (isSubclass(Expected, MCK_DREGS)) {
775 if (MCRegister CorrespondingDREG = toDREG(*MRI, Reg)) {
776 AVROperand RegOp(CorrespondingDREG, Op.getStartLoc(), Op.getEndLoc());
777 return validateOperandClass(RegOp, Expected, *STI);
778 }
779 }
780 return Match_InvalidOperand;
781}
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.
static MCRegister MatchRegisterName(StringRef Name)
Maps from the set of all register names to a register number.
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAVRAsmParser()
static MCRegister toDREG(const MCRegisterInfo &MRI, MCRegister Reg, unsigned From=AVR::sub_lo)
#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
static bool hasFeature(StringRef Feature, const FeatureBitset &FeatureBits, ArrayRef< SubtargetFeatureKV > ProcFeatures)
Register Reg
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineRegisterInfo & MRI
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
#define LLVM_DEBUG(...)
Definition Debug.h:119
void emitValueForModiferKind(const MCSymbol *Sym, unsigned SizeInBytes, SMLoc Loc=SMLoc(), AVRMCExpr::Specifier ModifierKind=AVR::S_AVR_NONE)
static const AVRMCExpr * create(Specifier S, const MCExpr *Expr, bool isNegated, MCContext &Ctx)
Specifies the type of an expression.
Definition AVRMCExpr.cpp:17
static Specifier parseSpecifier(StringRef Name)
const AsmToken peekTok(bool ShouldSkipSpace=true)
Look ahead at the next token to be lexed.
Definition AsmLexer.h:122
AsmToken::TokenKind getKind() const
Get the kind of current token.
Definition AsmLexer.h:145
LLVM_ABI size_t peekTokens(MutableArrayRef< AsmToken > Buf, bool ShouldSkipSpace=true)
Look ahead an arbitrary number of tokens.
Definition AsmLexer.cpp:762
Target independent representation for an assembler token.
Definition MCAsmMacro.h:22
LLVM_ABI SMLoc getLoc() const
Definition AsmLexer.cpp:31
StringRef getString() const
Get the string for the current token, this includes all characters (for example, the quotes on string...
Definition MCAsmMacro.h:103
bool is(TokenKind K) const
Definition MCAsmMacro.h:75
TokenKind getKind() const
Definition MCAsmMacro.h:74
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
Tagged union holding either a T or a Error.
Definition Error.h:485
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.
virtual void eatToEndOfStatement()=0
Skip to the end of the current statement, for error recovery.
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc)=0
Parse an arbitrary expression.
AsmLexer & getLexer()
const AsmToken & getTok() const
Get the current AsmToken from the stream.
virtual const AsmToken & Lex()=0
Get the next AsmToken in the stream, possibly handling file inclusion first.
MCStreamer & getStreamer()
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
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.
MCRegisterClass - Base class of TargetRegisterClass.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr unsigned id() const
Definition MCRegister.h:82
Streaming machine code generation interface.
Definition MCStreamer.h:222
void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc())
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
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
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
constexpr const char * getPointer() const
Definition SMLoc.h:33
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
LLVM_ABI std::string lower() const
uint16_t Specifier
@ 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 & getTheAVRTarget()
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SmallVectorImpl< std::unique_ptr< MCParsedAsmOperand > > OperandVector
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
DWARFExpression::Operation Op
const int SIZE_WORD
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
const int SIZE_LONG
#define N
RegisterMCAsmParser - Helper template for registering a target specific assembly parser,...