1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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 class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCParser/AsmCond.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
26 #include "llvm/MC/MCSectionMachO.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
39 /// \brief Helper class for tracking macro definitions.
45 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 /// \brief Helper class for storing information about an active macro
50 struct MacroInstantiation {
51 /// The macro being instantiated.
52 const Macro *TheMacro;
54 /// The macro instantiation with substitutions.
55 MemoryBuffer *Instantiation;
57 /// The location of the instantiation.
58 SMLoc InstantiationLoc;
60 /// The location where parsing should resume upon instantiation completion.
64 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL);
67 /// \brief The concrete assembly parser instance.
68 class AsmParser : public MCAsmParser {
69 friend class GenericAsmParser;
71 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
72 void operator=(const AsmParser &); // DO NOT IMPLEMENT
78 MCAsmParserExtension *GenericParser;
79 MCAsmParserExtension *PlatformParser;
81 /// This is the current buffer index we're lexing from as managed by the
86 std::vector<AsmCond> TheCondStack;
88 /// DirectiveMap - This is a table handlers for directives. Each handler is
89 /// invoked after the directive identifier is read and is responsible for
90 /// parsing and validating the rest of the directive. The handler is passed
91 /// in the directive name and the location of the directive keyword.
92 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
94 /// MacroMap - Map of currently defined macros.
95 StringMap<Macro*> MacroMap;
97 /// ActiveMacros - Stack of active macro instantiations.
98 std::vector<MacroInstantiation*> ActiveMacros;
100 /// Boolean tracking whether macro substitution is enabled.
101 unsigned MacrosEnabled : 1;
104 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
105 const MCAsmInfo &MAI);
108 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
110 void AddDirectiveHandler(MCAsmParserExtension *Object,
112 DirectiveHandler Handler) {
113 DirectiveMap[Directive] = std::make_pair(Object, Handler);
117 /// @name MCAsmParser Interface
120 virtual SourceMgr &getSourceManager() { return SrcMgr; }
121 virtual MCAsmLexer &getLexer() { return Lexer; }
122 virtual MCContext &getContext() { return Ctx; }
123 virtual MCStreamer &getStreamer() { return Out; }
125 virtual void Warning(SMLoc L, const Twine &Meg);
126 virtual bool Error(SMLoc L, const Twine &Msg);
128 const AsmToken &Lex();
130 bool ParseExpression(const MCExpr *&Res);
131 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
132 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
133 virtual bool ParseAbsoluteExpression(int64_t &Res);
138 bool ParseStatement();
140 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
141 void HandleMacroExit();
143 void PrintMacroInstantiations();
144 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
146 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
147 bool EnterIncludeFile(const std::string &Filename);
149 /// \brief Reset the current lexer position to that given by \arg Loc. The
150 /// current token is not set; clients should ensure Lex() is called
152 void JumpToLoc(SMLoc Loc);
154 void EatToEndOfStatement();
156 bool ParseAssignment(StringRef Name);
158 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
159 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
160 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
162 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
163 /// and set \arg Res to the identifier contents.
164 bool ParseIdentifier(StringRef &Res);
166 // Directive Parsing.
167 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
168 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
169 bool ParseDirectiveFill(); // ".fill"
170 bool ParseDirectiveSpace(); // ".space"
171 bool ParseDirectiveSet(); // ".set"
172 bool ParseDirectiveOrg(); // ".org"
173 // ".align{,32}", ".p2align{,w,l}"
174 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
176 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
177 /// accepts a single symbol (which should be a label or an external).
178 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
179 bool ParseDirectiveELFType(); // ELF specific ".type"
181 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
183 bool ParseDirectiveAbort(); // ".abort"
184 bool ParseDirectiveInclude(); // ".include"
186 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
187 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
188 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
189 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
191 /// ParseEscapedString - Parse the current token as a string which may include
192 /// escaped characters and return the string contents.
193 bool ParseEscapedString(std::string &Data);
196 /// \brief Generic implementations of directive handling, etc. which is shared
197 /// (or the default, at least) for all assembler parser.
198 class GenericAsmParser : public MCAsmParserExtension {
200 GenericAsmParser() {}
202 AsmParser &getParser() {
203 return (AsmParser&) this->MCAsmParserExtension::getParser();
206 virtual void Initialize(MCAsmParser &Parser) {
207 // Call the base implementation.
208 this->MCAsmParserExtension::Initialize(Parser);
210 // Debugging directives.
211 Parser.AddDirectiveHandler(this, ".file", MCAsmParser::DirectiveHandler(
212 &GenericAsmParser::ParseDirectiveFile));
213 Parser.AddDirectiveHandler(this, ".line", MCAsmParser::DirectiveHandler(
214 &GenericAsmParser::ParseDirectiveLine));
215 Parser.AddDirectiveHandler(this, ".loc", MCAsmParser::DirectiveHandler(
216 &GenericAsmParser::ParseDirectiveLoc));
219 Parser.AddDirectiveHandler(this, ".macros_on",
220 MCAsmParser::DirectiveHandler(
221 &GenericAsmParser::ParseDirectiveMacrosOnOff));
222 Parser.AddDirectiveHandler(this, ".macros_off",
223 MCAsmParser::DirectiveHandler(
224 &GenericAsmParser::ParseDirectiveMacrosOnOff));
225 Parser.AddDirectiveHandler(this, ".macro", MCAsmParser::DirectiveHandler(
226 &GenericAsmParser::ParseDirectiveMacro));
227 Parser.AddDirectiveHandler(this, ".endm", MCAsmParser::DirectiveHandler(
228 &GenericAsmParser::ParseDirectiveEndMacro));
229 Parser.AddDirectiveHandler(this, ".endmacro", MCAsmParser::DirectiveHandler(
230 &GenericAsmParser::ParseDirectiveEndMacro));
233 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
234 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
235 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
237 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
238 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
239 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
246 extern MCAsmParserExtension *createDarwinAsmParser();
247 extern MCAsmParserExtension *createELFAsmParser();
251 enum { DEFAULT_ADDRSPACE = 0 };
253 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
254 MCStreamer &_Out, const MCAsmInfo &_MAI)
255 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
256 GenericParser(new GenericAsmParser), PlatformParser(0),
257 CurBuffer(0), MacrosEnabled(true) {
258 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
260 // Initialize the generic parser.
261 GenericParser->Initialize(*this);
263 // Initialize the platform / file format parser.
265 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
267 if (_MAI.hasSubsectionsViaSymbols()) {
268 PlatformParser = createDarwinAsmParser();
269 PlatformParser->Initialize(*this);
271 PlatformParser = createELFAsmParser();
272 PlatformParser->Initialize(*this);
276 AsmParser::~AsmParser() {
277 delete PlatformParser;
278 delete GenericParser;
281 void AsmParser::PrintMacroInstantiations() {
282 // Print the active macro instantiation stack.
283 for (std::vector<MacroInstantiation*>::const_reverse_iterator
284 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
285 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
289 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
290 PrintMessage(L, Msg.str(), "warning");
291 PrintMacroInstantiations();
294 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
295 PrintMessage(L, Msg.str(), "error");
296 PrintMacroInstantiations();
300 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
301 const char *Type) const {
302 SrcMgr.PrintMessage(Loc, Msg, Type);
305 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
306 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
312 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
317 void AsmParser::JumpToLoc(SMLoc Loc) {
318 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
319 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
322 const AsmToken &AsmParser::Lex() {
323 const AsmToken *tok = &Lexer.Lex();
325 if (tok->is(AsmToken::Eof)) {
326 // If this is the end of an included file, pop the parent file off the
328 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
329 if (ParentIncludeLoc != SMLoc()) {
330 JumpToLoc(ParentIncludeLoc);
335 if (tok->is(AsmToken::Error))
336 Error(Lexer.getErrLoc(), Lexer.getErr());
341 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
342 // Create the initial section, if requested.
344 // FIXME: Target hook & command line option for initial section.
345 if (!NoInitialTextSection)
346 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
347 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
348 0, SectionKind::getText()));
353 bool HadError = false;
355 AsmCond StartingCondState = TheCondState;
357 // While we have input, parse each statement.
358 while (Lexer.isNot(AsmToken::Eof)) {
359 if (!ParseStatement()) continue;
361 // We had an error, remember it and recover by skipping to the next line.
363 EatToEndOfStatement();
366 if (TheCondState.TheCond != StartingCondState.TheCond ||
367 TheCondState.Ignore != StartingCondState.Ignore)
368 return TokError("unmatched .ifs or .elses");
370 // Finalize the output stream if there are no errors and if the client wants
372 if (!HadError && !NoFinalize)
378 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
379 void AsmParser::EatToEndOfStatement() {
380 while (Lexer.isNot(AsmToken::EndOfStatement) &&
381 Lexer.isNot(AsmToken::Eof))
385 if (Lexer.is(AsmToken::EndOfStatement))
390 /// ParseParenExpr - Parse a paren expression and return it.
391 /// NOTE: This assumes the leading '(' has already been consumed.
393 /// parenexpr ::= expr)
395 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
396 if (ParseExpression(Res)) return true;
397 if (Lexer.isNot(AsmToken::RParen))
398 return TokError("expected ')' in parentheses expression");
399 EndLoc = Lexer.getLoc();
404 /// ParsePrimaryExpr - Parse a primary expression and return it.
405 /// primaryexpr ::= (parenexpr
406 /// primaryexpr ::= symbol
407 /// primaryexpr ::= number
408 /// primaryexpr ::= '.'
409 /// primaryexpr ::= ~,+,- primaryexpr
410 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
411 switch (Lexer.getKind()) {
413 return TokError("unknown token in expression");
414 case AsmToken::Exclaim:
415 Lex(); // Eat the operator.
416 if (ParsePrimaryExpr(Res, EndLoc))
418 Res = MCUnaryExpr::CreateLNot(Res, getContext());
420 case AsmToken::String:
421 case AsmToken::Identifier: {
422 // This is a symbol reference.
423 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
424 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
426 // Mark the symbol as used in an expression.
427 Sym->setUsedInExpr(true);
429 // Lookup the symbol variant if used.
430 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
431 if (Split.first.size() != getTok().getIdentifier().size())
432 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
434 EndLoc = Lexer.getLoc();
435 Lex(); // Eat identifier.
437 // If this is an absolute variable reference, substitute it now to preserve
438 // semantics in the face of reassignment.
439 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
441 return Error(EndLoc, "unexpected modified on variable reference");
443 Res = Sym->getVariableValue();
447 // Otherwise create a symbol ref.
448 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
451 case AsmToken::Integer: {
452 SMLoc Loc = getTok().getLoc();
453 int64_t IntVal = getTok().getIntVal();
454 Res = MCConstantExpr::Create(IntVal, getContext());
455 EndLoc = Lexer.getLoc();
457 // Look for 'b' or 'f' following an Integer as a directional label
458 if (Lexer.getKind() == AsmToken::Identifier) {
459 StringRef IDVal = getTok().getString();
460 if (IDVal == "f" || IDVal == "b"){
461 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
462 IDVal == "f" ? 1 : 0);
463 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
465 if(IDVal == "b" && Sym->isUndefined())
466 return Error(Loc, "invalid reference to undefined symbol");
467 EndLoc = Lexer.getLoc();
468 Lex(); // Eat identifier.
473 case AsmToken::Dot: {
474 // This is a '.' reference, which references the current PC. Emit a
475 // temporary label to the streamer and refer to it.
476 MCSymbol *Sym = Ctx.CreateTempSymbol();
478 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
479 EndLoc = Lexer.getLoc();
480 Lex(); // Eat identifier.
484 case AsmToken::LParen:
485 Lex(); // Eat the '('.
486 return ParseParenExpr(Res, EndLoc);
487 case AsmToken::Minus:
488 Lex(); // Eat the operator.
489 if (ParsePrimaryExpr(Res, EndLoc))
491 Res = MCUnaryExpr::CreateMinus(Res, getContext());
494 Lex(); // Eat the operator.
495 if (ParsePrimaryExpr(Res, EndLoc))
497 Res = MCUnaryExpr::CreatePlus(Res, getContext());
499 case AsmToken::Tilde:
500 Lex(); // Eat the operator.
501 if (ParsePrimaryExpr(Res, EndLoc))
503 Res = MCUnaryExpr::CreateNot(Res, getContext());
508 bool AsmParser::ParseExpression(const MCExpr *&Res) {
510 return ParseExpression(Res, EndLoc);
513 /// ParseExpression - Parse an expression and return it.
515 /// expr ::= expr +,- expr -> lowest.
516 /// expr ::= expr |,^,&,! expr -> middle.
517 /// expr ::= expr *,/,%,<<,>> expr -> highest.
518 /// expr ::= primaryexpr
520 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
521 // Parse the expression.
523 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
526 // Try to constant fold it up front, if possible.
528 if (Res->EvaluateAsAbsolute(Value))
529 Res = MCConstantExpr::Create(Value, getContext());
534 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
536 return ParseParenExpr(Res, EndLoc) ||
537 ParseBinOpRHS(1, Res, EndLoc);
540 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
543 SMLoc StartLoc = Lexer.getLoc();
544 if (ParseExpression(Expr))
547 if (!Expr->EvaluateAsAbsolute(Res))
548 return Error(StartLoc, "expected absolute expression");
553 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
554 MCBinaryExpr::Opcode &Kind) {
557 return 0; // not a binop.
559 // Lowest Precedence: &&, ||
560 case AsmToken::AmpAmp:
561 Kind = MCBinaryExpr::LAnd;
563 case AsmToken::PipePipe:
564 Kind = MCBinaryExpr::LOr;
567 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
569 Kind = MCBinaryExpr::Add;
571 case AsmToken::Minus:
572 Kind = MCBinaryExpr::Sub;
574 case AsmToken::EqualEqual:
575 Kind = MCBinaryExpr::EQ;
577 case AsmToken::ExclaimEqual:
578 case AsmToken::LessGreater:
579 Kind = MCBinaryExpr::NE;
582 Kind = MCBinaryExpr::LT;
584 case AsmToken::LessEqual:
585 Kind = MCBinaryExpr::LTE;
587 case AsmToken::Greater:
588 Kind = MCBinaryExpr::GT;
590 case AsmToken::GreaterEqual:
591 Kind = MCBinaryExpr::GTE;
594 // Intermediate Precedence: |, &, ^
596 // FIXME: gas seems to support '!' as an infix operator?
598 Kind = MCBinaryExpr::Or;
600 case AsmToken::Caret:
601 Kind = MCBinaryExpr::Xor;
604 Kind = MCBinaryExpr::And;
607 // Highest Precedence: *, /, %, <<, >>
609 Kind = MCBinaryExpr::Mul;
611 case AsmToken::Slash:
612 Kind = MCBinaryExpr::Div;
614 case AsmToken::Percent:
615 Kind = MCBinaryExpr::Mod;
617 case AsmToken::LessLess:
618 Kind = MCBinaryExpr::Shl;
620 case AsmToken::GreaterGreater:
621 Kind = MCBinaryExpr::Shr;
627 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
628 /// Res contains the LHS of the expression on input.
629 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
632 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
633 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
635 // If the next token is lower precedence than we are allowed to eat, return
636 // successfully with what we ate already.
637 if (TokPrec < Precedence)
642 // Eat the next primary expression.
644 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
646 // If BinOp binds less tightly with RHS than the operator after RHS, let
647 // the pending operator take RHS as its LHS.
648 MCBinaryExpr::Opcode Dummy;
649 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
650 if (TokPrec < NextTokPrec) {
651 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
654 // Merge LHS and RHS according to operator.
655 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
663 /// ::= EndOfStatement
664 /// ::= Label* Directive ...Operands... EndOfStatement
665 /// ::= Label* Identifier OperandList* EndOfStatement
666 bool AsmParser::ParseStatement() {
667 if (Lexer.is(AsmToken::EndOfStatement)) {
673 // Statements always start with an identifier.
674 AsmToken ID = getTok();
675 SMLoc IDLoc = ID.getLoc();
677 int64_t LocalLabelVal = -1;
678 // GUESS allow an integer followed by a ':' as a directional local label
679 if (Lexer.is(AsmToken::Integer)) {
680 LocalLabelVal = getTok().getIntVal();
681 if (LocalLabelVal < 0) {
682 if (!TheCondState.Ignore)
683 return TokError("unexpected token at start of statement");
687 IDVal = getTok().getString();
688 Lex(); // Consume the integer token to be used as an identifier token.
689 if (Lexer.getKind() != AsmToken::Colon) {
690 if (!TheCondState.Ignore)
691 return TokError("unexpected token at start of statement");
695 else if (ParseIdentifier(IDVal)) {
696 if (!TheCondState.Ignore)
697 return TokError("unexpected token at start of statement");
701 // Handle conditional assembly here before checking for skipping. We
702 // have to do this so that .endif isn't skipped in a ".if 0" block for
705 return ParseDirectiveIf(IDLoc);
706 if (IDVal == ".elseif")
707 return ParseDirectiveElseIf(IDLoc);
708 if (IDVal == ".else")
709 return ParseDirectiveElse(IDLoc);
710 if (IDVal == ".endif")
711 return ParseDirectiveEndIf(IDLoc);
713 // If we are in a ".if 0" block, ignore this statement.
714 if (TheCondState.Ignore) {
715 EatToEndOfStatement();
719 // FIXME: Recurse on local labels?
721 // See what kind of statement we have.
722 switch (Lexer.getKind()) {
723 case AsmToken::Colon: {
724 // identifier ':' -> Label.
727 // Diagnose attempt to use a variable as a label.
729 // FIXME: Diagnostics. Note the location of the definition as a label.
730 // FIXME: This doesn't diagnose assignment to a symbol which has been
731 // implicitly marked as external.
733 if (LocalLabelVal == -1)
734 Sym = getContext().GetOrCreateSymbol(IDVal);
736 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
737 if (!Sym->isUndefined() || Sym->isVariable())
738 return Error(IDLoc, "invalid symbol redefinition");
743 // Consume any end of statement token, if present, to avoid spurious
744 // AddBlankLine calls().
745 if (Lexer.is(AsmToken::EndOfStatement)) {
747 if (Lexer.is(AsmToken::Eof))
751 return ParseStatement();
754 case AsmToken::Equal:
755 // identifier '=' ... -> assignment statement
758 return ParseAssignment(IDVal);
760 default: // Normal instruction or directive.
764 // If macros are enabled, check to see if this is a macro instantiation.
766 if (const Macro *M = MacroMap.lookup(IDVal))
767 return HandleMacroEntry(IDVal, IDLoc, M);
769 // Otherwise, we have a normal instruction or directive.
770 if (IDVal[0] == '.') {
771 // Assembler features
773 return ParseDirectiveSet();
777 if (IDVal == ".ascii")
778 return ParseDirectiveAscii(false);
779 if (IDVal == ".asciz")
780 return ParseDirectiveAscii(true);
782 if (IDVal == ".byte")
783 return ParseDirectiveValue(1);
784 if (IDVal == ".short")
785 return ParseDirectiveValue(2);
786 if (IDVal == ".long")
787 return ParseDirectiveValue(4);
788 if (IDVal == ".quad")
789 return ParseDirectiveValue(8);
791 // FIXME: Target hooks for IsPow2.
792 if (IDVal == ".align")
793 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
794 if (IDVal == ".align32")
795 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
796 if (IDVal == ".balign")
797 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
798 if (IDVal == ".balignw")
799 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
800 if (IDVal == ".balignl")
801 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
802 if (IDVal == ".p2align")
803 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
804 if (IDVal == ".p2alignw")
805 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
806 if (IDVal == ".p2alignl")
807 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
810 return ParseDirectiveOrg();
812 if (IDVal == ".fill")
813 return ParseDirectiveFill();
814 if (IDVal == ".space")
815 return ParseDirectiveSpace();
817 // Symbol attribute directives
819 if (IDVal == ".globl" || IDVal == ".global")
820 return ParseDirectiveSymbolAttribute(MCSA_Global);
821 if (IDVal == ".hidden")
822 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
823 if (IDVal == ".indirect_symbol")
824 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
825 if (IDVal == ".internal")
826 return ParseDirectiveSymbolAttribute(MCSA_Internal);
827 if (IDVal == ".lazy_reference")
828 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
829 if (IDVal == ".no_dead_strip")
830 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
831 if (IDVal == ".private_extern")
832 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
833 if (IDVal == ".protected")
834 return ParseDirectiveSymbolAttribute(MCSA_Protected);
835 if (IDVal == ".reference")
836 return ParseDirectiveSymbolAttribute(MCSA_Reference);
837 if (IDVal == ".type")
838 return ParseDirectiveELFType();
839 if (IDVal == ".weak")
840 return ParseDirectiveSymbolAttribute(MCSA_Weak);
841 if (IDVal == ".weak_definition")
842 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
843 if (IDVal == ".weak_reference")
844 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
845 if (IDVal == ".weak_def_can_be_hidden")
846 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
848 if (IDVal == ".comm")
849 return ParseDirectiveComm(/*IsLocal=*/false);
850 if (IDVal == ".lcomm")
851 return ParseDirectiveComm(/*IsLocal=*/true);
853 if (IDVal == ".abort")
854 return ParseDirectiveAbort();
855 if (IDVal == ".include")
856 return ParseDirectiveInclude();
858 // Look up the handler in the handler table.
859 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
860 DirectiveMap.lookup(IDVal);
862 return (Handler.first->*Handler.second)(IDVal, IDLoc);
864 // Target hook for parsing target specific directives.
865 if (!getTargetParser().ParseDirective(ID))
868 Warning(IDLoc, "ignoring directive for now");
869 EatToEndOfStatement();
873 // Canonicalize the opcode to lower case.
874 SmallString<128> Opcode;
875 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
876 Opcode.push_back(tolower(IDVal[i]));
878 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
879 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
881 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
882 HadError = TokError("unexpected token in argument list");
884 // If parsing succeeded, match the instruction.
887 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
888 // Emit the instruction on success.
889 Out.EmitInstruction(Inst);
891 // Otherwise emit a diagnostic about the match failure and set the error
894 // FIXME: We should give nicer diagnostics about the exact failure.
895 Error(IDLoc, "unrecognized instruction");
900 // If there was no error, consume the end-of-statement token. Otherwise this
901 // will be done by our caller.
905 // Free any parsed operands.
906 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
907 delete ParsedOperands[i];
912 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL)
913 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
915 // Macro instantiation is lexical, unfortunately. We construct a new buffer
916 // to hold the macro body with substitutions.
917 llvm::SmallString<256> Buf;
920 // We include the .endmacro in the buffer as our queue to exit the macro
922 Buf += ".endmacro\n";
924 Instantiation = MemoryBuffer::getMemBufferCopy(Buf, "<instantiation>");
927 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
929 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
930 // this, although we should protect against infinite loops.
931 if (ActiveMacros.size() == 20)
932 return TokError("macros cannot be nested more than 20 levels deep");
934 EatToEndOfStatement();
936 // Create the macro instantiation object and add to the current macro
937 // instantiation stack.
938 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
940 ActiveMacros.push_back(MI);
942 // Jump to the macro instantiation and prime the lexer.
943 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
944 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
950 void AsmParser::HandleMacroExit() {
951 // Jump to the EndOfStatement we should return to, and consume it.
952 JumpToLoc(ActiveMacros.back()->ExitLoc);
955 // Pop the instantiation entry.
956 delete ActiveMacros.back();
957 ActiveMacros.pop_back();
960 bool AsmParser::ParseAssignment(StringRef Name) {
961 // FIXME: Use better location, we should use proper tokens.
962 SMLoc EqualLoc = Lexer.getLoc();
965 if (ParseExpression(Value))
968 if (Lexer.isNot(AsmToken::EndOfStatement))
969 return TokError("unexpected token in assignment");
971 // Eat the end of statement marker.
974 // Validate that the LHS is allowed to be a variable (either it has not been
975 // used as a symbol, or it is an absolute symbol).
976 MCSymbol *Sym = getContext().LookupSymbol(Name);
978 // Diagnose assignment to a label.
980 // FIXME: Diagnostics. Note the location of the definition as a label.
981 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
982 if (Sym->isUndefined() && !Sym->isUsedInExpr())
983 ; // Allow redefinitions of undefined symbols only used in directives.
984 else if (!Sym->isUndefined() && !Sym->isAbsolute())
985 return Error(EqualLoc, "redefinition of '" + Name + "'");
986 else if (!Sym->isVariable())
987 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
988 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
989 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
992 Sym = getContext().GetOrCreateSymbol(Name);
994 // FIXME: Handle '.'.
996 Sym->setUsedInExpr(true);
998 // Do the assignment.
999 Out.EmitAssignment(Sym, Value);
1004 /// ParseIdentifier:
1007 bool AsmParser::ParseIdentifier(StringRef &Res) {
1008 if (Lexer.isNot(AsmToken::Identifier) &&
1009 Lexer.isNot(AsmToken::String))
1012 Res = getTok().getIdentifier();
1014 Lex(); // Consume the identifier token.
1019 /// ParseDirectiveSet:
1020 /// ::= .set identifier ',' expression
1021 bool AsmParser::ParseDirectiveSet() {
1024 if (ParseIdentifier(Name))
1025 return TokError("expected identifier after '.set' directive");
1027 if (getLexer().isNot(AsmToken::Comma))
1028 return TokError("unexpected token in '.set'");
1031 return ParseAssignment(Name);
1034 bool AsmParser::ParseEscapedString(std::string &Data) {
1035 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1038 StringRef Str = getTok().getStringContents();
1039 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1040 if (Str[i] != '\\') {
1045 // Recognize escaped characters. Note that this escape semantics currently
1046 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1049 return TokError("unexpected backslash at end of string");
1051 // Recognize octal sequences.
1052 if ((unsigned) (Str[i] - '0') <= 7) {
1053 // Consume up to three octal characters.
1054 unsigned Value = Str[i] - '0';
1056 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1058 Value = Value * 8 + (Str[i] - '0');
1060 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1062 Value = Value * 8 + (Str[i] - '0');
1067 return TokError("invalid octal escape sequence (out of range)");
1069 Data += (unsigned char) Value;
1073 // Otherwise recognize individual escapes.
1076 // Just reject invalid escape sequences for now.
1077 return TokError("invalid escape sequence (unrecognized character)");
1079 case 'b': Data += '\b'; break;
1080 case 'f': Data += '\f'; break;
1081 case 'n': Data += '\n'; break;
1082 case 'r': Data += '\r'; break;
1083 case 't': Data += '\t'; break;
1084 case '"': Data += '"'; break;
1085 case '\\': Data += '\\'; break;
1092 /// ParseDirectiveAscii:
1093 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1094 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1095 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1097 if (getLexer().isNot(AsmToken::String))
1098 return TokError("expected string in '.ascii' or '.asciz' directive");
1101 if (ParseEscapedString(Data))
1104 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1106 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1110 if (getLexer().is(AsmToken::EndOfStatement))
1113 if (getLexer().isNot(AsmToken::Comma))
1114 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1123 /// ParseDirectiveValue
1124 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1125 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1126 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1128 const MCExpr *Value;
1129 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1130 if (ParseExpression(Value))
1133 // Special case constant expressions to match code generator.
1134 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1135 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1137 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1139 if (getLexer().is(AsmToken::EndOfStatement))
1142 // FIXME: Improve diagnostic.
1143 if (getLexer().isNot(AsmToken::Comma))
1144 return TokError("unexpected token in directive");
1153 /// ParseDirectiveSpace
1154 /// ::= .space expression [ , expression ]
1155 bool AsmParser::ParseDirectiveSpace() {
1157 if (ParseAbsoluteExpression(NumBytes))
1160 int64_t FillExpr = 0;
1161 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1162 if (getLexer().isNot(AsmToken::Comma))
1163 return TokError("unexpected token in '.space' directive");
1166 if (ParseAbsoluteExpression(FillExpr))
1169 if (getLexer().isNot(AsmToken::EndOfStatement))
1170 return TokError("unexpected token in '.space' directive");
1176 return TokError("invalid number of bytes in '.space' directive");
1178 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1179 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1184 /// ParseDirectiveFill
1185 /// ::= .fill expression , expression , expression
1186 bool AsmParser::ParseDirectiveFill() {
1188 if (ParseAbsoluteExpression(NumValues))
1191 if (getLexer().isNot(AsmToken::Comma))
1192 return TokError("unexpected token in '.fill' directive");
1196 if (ParseAbsoluteExpression(FillSize))
1199 if (getLexer().isNot(AsmToken::Comma))
1200 return TokError("unexpected token in '.fill' directive");
1204 if (ParseAbsoluteExpression(FillExpr))
1207 if (getLexer().isNot(AsmToken::EndOfStatement))
1208 return TokError("unexpected token in '.fill' directive");
1212 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1213 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1215 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1216 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1221 /// ParseDirectiveOrg
1222 /// ::= .org expression [ , expression ]
1223 bool AsmParser::ParseDirectiveOrg() {
1224 const MCExpr *Offset;
1225 if (ParseExpression(Offset))
1228 // Parse optional fill expression.
1229 int64_t FillExpr = 0;
1230 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1231 if (getLexer().isNot(AsmToken::Comma))
1232 return TokError("unexpected token in '.org' directive");
1235 if (ParseAbsoluteExpression(FillExpr))
1238 if (getLexer().isNot(AsmToken::EndOfStatement))
1239 return TokError("unexpected token in '.org' directive");
1244 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1245 // has to be relative to the current section.
1246 getStreamer().EmitValueToOffset(Offset, FillExpr);
1251 /// ParseDirectiveAlign
1252 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1253 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1254 SMLoc AlignmentLoc = getLexer().getLoc();
1256 if (ParseAbsoluteExpression(Alignment))
1260 bool HasFillExpr = false;
1261 int64_t FillExpr = 0;
1262 int64_t MaxBytesToFill = 0;
1263 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1264 if (getLexer().isNot(AsmToken::Comma))
1265 return TokError("unexpected token in directive");
1268 // The fill expression can be omitted while specifying a maximum number of
1269 // alignment bytes, e.g:
1271 if (getLexer().isNot(AsmToken::Comma)) {
1273 if (ParseAbsoluteExpression(FillExpr))
1277 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1278 if (getLexer().isNot(AsmToken::Comma))
1279 return TokError("unexpected token in directive");
1282 MaxBytesLoc = getLexer().getLoc();
1283 if (ParseAbsoluteExpression(MaxBytesToFill))
1286 if (getLexer().isNot(AsmToken::EndOfStatement))
1287 return TokError("unexpected token in directive");
1296 // Compute alignment in bytes.
1298 // FIXME: Diagnose overflow.
1299 if (Alignment >= 32) {
1300 Error(AlignmentLoc, "invalid alignment value");
1304 Alignment = 1ULL << Alignment;
1307 // Diagnose non-sensical max bytes to align.
1308 if (MaxBytesLoc.isValid()) {
1309 if (MaxBytesToFill < 1) {
1310 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1311 "many bytes, ignoring maximum bytes expression");
1315 if (MaxBytesToFill >= Alignment) {
1316 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1322 // Check whether we should use optimal code alignment for this .align
1325 // FIXME: This should be using a target hook.
1326 bool UseCodeAlign = false;
1327 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1328 getStreamer().getCurrentSection()))
1329 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1330 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1331 ValueSize == 1 && UseCodeAlign) {
1332 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1334 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1335 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1342 /// ParseDirectiveSymbolAttribute
1343 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1344 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1345 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1349 if (ParseIdentifier(Name))
1350 return TokError("expected identifier in directive");
1352 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1354 getStreamer().EmitSymbolAttribute(Sym, Attr);
1356 if (getLexer().is(AsmToken::EndOfStatement))
1359 if (getLexer().isNot(AsmToken::Comma))
1360 return TokError("unexpected token in directive");
1369 /// ParseDirectiveELFType
1370 /// ::= .type identifier , @attribute
1371 bool AsmParser::ParseDirectiveELFType() {
1373 if (ParseIdentifier(Name))
1374 return TokError("expected identifier in directive");
1376 // Handle the identifier as the key symbol.
1377 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1379 if (getLexer().isNot(AsmToken::Comma))
1380 return TokError("unexpected token in '.type' directive");
1383 if (getLexer().isNot(AsmToken::At))
1384 return TokError("expected '@' before type");
1390 TypeLoc = getLexer().getLoc();
1391 if (ParseIdentifier(Type))
1392 return TokError("expected symbol type in directive");
1394 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1395 .Case("function", MCSA_ELF_TypeFunction)
1396 .Case("object", MCSA_ELF_TypeObject)
1397 .Case("tls_object", MCSA_ELF_TypeTLS)
1398 .Case("common", MCSA_ELF_TypeCommon)
1399 .Case("notype", MCSA_ELF_TypeNoType)
1400 .Default(MCSA_Invalid);
1402 if (Attr == MCSA_Invalid)
1403 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1405 if (getLexer().isNot(AsmToken::EndOfStatement))
1406 return TokError("unexpected token in '.type' directive");
1410 getStreamer().EmitSymbolAttribute(Sym, Attr);
1415 /// ParseDirectiveComm
1416 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1417 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1418 SMLoc IDLoc = getLexer().getLoc();
1420 if (ParseIdentifier(Name))
1421 return TokError("expected identifier in directive");
1423 // Handle the identifier as the key symbol.
1424 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1426 if (getLexer().isNot(AsmToken::Comma))
1427 return TokError("unexpected token in directive");
1431 SMLoc SizeLoc = getLexer().getLoc();
1432 if (ParseAbsoluteExpression(Size))
1435 int64_t Pow2Alignment = 0;
1436 SMLoc Pow2AlignmentLoc;
1437 if (getLexer().is(AsmToken::Comma)) {
1439 Pow2AlignmentLoc = getLexer().getLoc();
1440 if (ParseAbsoluteExpression(Pow2Alignment))
1443 // If this target takes alignments in bytes (not log) validate and convert.
1444 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1445 if (!isPowerOf2_64(Pow2Alignment))
1446 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1447 Pow2Alignment = Log2_64(Pow2Alignment);
1451 if (getLexer().isNot(AsmToken::EndOfStatement))
1452 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1456 // NOTE: a size of zero for a .comm should create a undefined symbol
1457 // but a size of .lcomm creates a bss symbol of size zero.
1459 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1460 "be less than zero");
1462 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1463 // may internally end up wanting an alignment in bytes.
1464 // FIXME: Diagnose overflow.
1465 if (Pow2Alignment < 0)
1466 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1467 "alignment, can't be less than zero");
1469 if (!Sym->isUndefined())
1470 return Error(IDLoc, "invalid symbol redefinition");
1472 // '.lcomm' is equivalent to '.zerofill'.
1473 // Create the Symbol as a common or local common with Size and Pow2Alignment
1475 getStreamer().EmitZerofill(Ctx.getMachOSection(
1476 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1477 0, SectionKind::getBSS()),
1478 Sym, Size, 1 << Pow2Alignment);
1482 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1486 /// ParseDirectiveAbort
1487 /// ::= .abort [ "abort_string" ]
1488 bool AsmParser::ParseDirectiveAbort() {
1489 // FIXME: Use loc from directive.
1490 SMLoc Loc = getLexer().getLoc();
1493 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1494 if (getLexer().isNot(AsmToken::String))
1495 return TokError("expected string in '.abort' directive");
1497 Str = getTok().getString();
1502 if (getLexer().isNot(AsmToken::EndOfStatement))
1503 return TokError("unexpected token in '.abort' directive");
1507 // FIXME: Handle here.
1509 Error(Loc, ".abort detected. Assembly stopping.");
1511 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1516 /// ParseDirectiveInclude
1517 /// ::= .include "filename"
1518 bool AsmParser::ParseDirectiveInclude() {
1519 if (getLexer().isNot(AsmToken::String))
1520 return TokError("expected string in '.include' directive");
1522 std::string Filename = getTok().getString();
1523 SMLoc IncludeLoc = getLexer().getLoc();
1526 if (getLexer().isNot(AsmToken::EndOfStatement))
1527 return TokError("unexpected token in '.include' directive");
1529 // Strip the quotes.
1530 Filename = Filename.substr(1, Filename.size()-2);
1532 // Attempt to switch the lexer to the included file before consuming the end
1533 // of statement to avoid losing it when we switch.
1534 if (EnterIncludeFile(Filename)) {
1535 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1542 /// ParseDirectiveIf
1543 /// ::= .if expression
1544 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1545 TheCondStack.push_back(TheCondState);
1546 TheCondState.TheCond = AsmCond::IfCond;
1547 if(TheCondState.Ignore) {
1548 EatToEndOfStatement();
1552 if (ParseAbsoluteExpression(ExprValue))
1555 if (getLexer().isNot(AsmToken::EndOfStatement))
1556 return TokError("unexpected token in '.if' directive");
1560 TheCondState.CondMet = ExprValue;
1561 TheCondState.Ignore = !TheCondState.CondMet;
1567 /// ParseDirectiveElseIf
1568 /// ::= .elseif expression
1569 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1570 if (TheCondState.TheCond != AsmCond::IfCond &&
1571 TheCondState.TheCond != AsmCond::ElseIfCond)
1572 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1574 TheCondState.TheCond = AsmCond::ElseIfCond;
1576 bool LastIgnoreState = false;
1577 if (!TheCondStack.empty())
1578 LastIgnoreState = TheCondStack.back().Ignore;
1579 if (LastIgnoreState || TheCondState.CondMet) {
1580 TheCondState.Ignore = true;
1581 EatToEndOfStatement();
1585 if (ParseAbsoluteExpression(ExprValue))
1588 if (getLexer().isNot(AsmToken::EndOfStatement))
1589 return TokError("unexpected token in '.elseif' directive");
1592 TheCondState.CondMet = ExprValue;
1593 TheCondState.Ignore = !TheCondState.CondMet;
1599 /// ParseDirectiveElse
1601 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1602 if (getLexer().isNot(AsmToken::EndOfStatement))
1603 return TokError("unexpected token in '.else' directive");
1607 if (TheCondState.TheCond != AsmCond::IfCond &&
1608 TheCondState.TheCond != AsmCond::ElseIfCond)
1609 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1611 TheCondState.TheCond = AsmCond::ElseCond;
1612 bool LastIgnoreState = false;
1613 if (!TheCondStack.empty())
1614 LastIgnoreState = TheCondStack.back().Ignore;
1615 if (LastIgnoreState || TheCondState.CondMet)
1616 TheCondState.Ignore = true;
1618 TheCondState.Ignore = false;
1623 /// ParseDirectiveEndIf
1625 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1626 if (getLexer().isNot(AsmToken::EndOfStatement))
1627 return TokError("unexpected token in '.endif' directive");
1631 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1632 TheCondStack.empty())
1633 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1635 if (!TheCondStack.empty()) {
1636 TheCondState = TheCondStack.back();
1637 TheCondStack.pop_back();
1643 /// ParseDirectiveFile
1644 /// ::= .file [number] string
1645 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1646 // FIXME: I'm not sure what this is.
1647 int64_t FileNumber = -1;
1648 if (getLexer().is(AsmToken::Integer)) {
1649 FileNumber = getTok().getIntVal();
1653 return TokError("file number less than one");
1656 if (getLexer().isNot(AsmToken::String))
1657 return TokError("unexpected token in '.file' directive");
1659 StringRef Filename = getTok().getString();
1660 Filename = Filename.substr(1, Filename.size()-2);
1663 if (getLexer().isNot(AsmToken::EndOfStatement))
1664 return TokError("unexpected token in '.file' directive");
1666 if (FileNumber == -1)
1667 getStreamer().EmitFileDirective(Filename);
1669 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1674 /// ParseDirectiveLine
1675 /// ::= .line [number]
1676 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1677 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1678 if (getLexer().isNot(AsmToken::Integer))
1679 return TokError("unexpected token in '.line' directive");
1681 int64_t LineNumber = getTok().getIntVal();
1685 // FIXME: Do something with the .line.
1688 if (getLexer().isNot(AsmToken::EndOfStatement))
1689 return TokError("unexpected token in '.line' directive");
1695 /// ParseDirectiveLoc
1696 /// ::= .loc number [number [number]]
1697 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1698 if (getLexer().isNot(AsmToken::Integer))
1699 return TokError("unexpected token in '.loc' directive");
1701 // FIXME: What are these fields?
1702 int64_t FileNumber = getTok().getIntVal();
1704 // FIXME: Validate file.
1707 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1708 if (getLexer().isNot(AsmToken::Integer))
1709 return TokError("unexpected token in '.loc' directive");
1711 int64_t Param2 = getTok().getIntVal();
1715 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1716 if (getLexer().isNot(AsmToken::Integer))
1717 return TokError("unexpected token in '.loc' directive");
1719 int64_t Param3 = getTok().getIntVal();
1723 // FIXME: Do something with the .loc.
1727 if (getLexer().isNot(AsmToken::EndOfStatement))
1728 return TokError("unexpected token in '.file' directive");
1733 /// ParseDirectiveMacrosOnOff
1736 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1737 SMLoc DirectiveLoc) {
1738 if (getLexer().isNot(AsmToken::EndOfStatement))
1739 return Error(getLexer().getLoc(),
1740 "unexpected token in '" + Directive + "' directive");
1742 getParser().MacrosEnabled = Directive == ".macros_on";
1747 /// ParseDirectiveMacro
1749 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1750 SMLoc DirectiveLoc) {
1752 if (getParser().ParseIdentifier(Name))
1753 return TokError("expected identifier in directive");
1755 if (getLexer().isNot(AsmToken::EndOfStatement))
1756 return TokError("unexpected token in '.macro' directive");
1758 // Eat the end of statement.
1761 AsmToken EndToken, StartToken = getTok();
1763 // Lex the macro definition.
1765 // Check whether we have reached the end of the file.
1766 if (getLexer().is(AsmToken::Eof))
1767 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1769 // Otherwise, check whether we have reach the .endmacro.
1770 if (getLexer().is(AsmToken::Identifier) &&
1771 (getTok().getIdentifier() == ".endm" ||
1772 getTok().getIdentifier() == ".endmacro")) {
1773 EndToken = getTok();
1775 if (getLexer().isNot(AsmToken::EndOfStatement))
1776 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1781 // Otherwise, scan til the end of the statement.
1782 getParser().EatToEndOfStatement();
1785 if (getParser().MacroMap.lookup(Name)) {
1786 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1789 const char *BodyStart = StartToken.getLoc().getPointer();
1790 const char *BodyEnd = EndToken.getLoc().getPointer();
1791 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1792 getParser().MacroMap[Name] = new Macro(Name, Body);
1796 /// ParseDirectiveEndMacro
1799 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1800 SMLoc DirectiveLoc) {
1801 if (getLexer().isNot(AsmToken::EndOfStatement))
1802 return TokError("unexpected token in '" + Directive + "' directive");
1804 // If we are inside a macro instantiation, terminate the current
1806 if (!getParser().ActiveMacros.empty()) {
1807 getParser().HandleMacroExit();
1811 // Otherwise, this .endmacro is a stray entry in the file; well formed
1812 // .endmacro directives are handled during the macro definition parsing.
1813 return TokError("unexpected '" + Directive + "' in file, "
1814 "no current macro definition");
1817 /// \brief Create an MCAsmParser instance.
1818 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1819 MCContext &C, MCStreamer &Out,
1820 const MCAsmInfo &MAI) {
1821 return new AsmParser(T, SM, C, Out, MAI);