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,
65 const std::vector<std::vector<AsmToken> > &A);
68 /// \brief The concrete assembly parser instance.
69 class AsmParser : public MCAsmParser {
70 friend class GenericAsmParser;
72 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
73 void operator=(const AsmParser &); // DO NOT IMPLEMENT
79 MCAsmParserExtension *GenericParser;
80 MCAsmParserExtension *PlatformParser;
82 /// This is the current buffer index we're lexing from as managed by the
87 std::vector<AsmCond> TheCondStack;
89 /// DirectiveMap - This is a table handlers for directives. Each handler is
90 /// invoked after the directive identifier is read and is responsible for
91 /// parsing and validating the rest of the directive. The handler is passed
92 /// in the directive name and the location of the directive keyword.
93 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95 /// MacroMap - Map of currently defined macros.
96 StringMap<Macro*> MacroMap;
98 /// ActiveMacros - Stack of active macro instantiations.
99 std::vector<MacroInstantiation*> ActiveMacros;
101 /// Boolean tracking whether macro substitution is enabled.
102 unsigned MacrosEnabled : 1;
105 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
106 const MCAsmInfo &MAI);
109 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
111 void AddDirectiveHandler(MCAsmParserExtension *Object,
113 DirectiveHandler Handler) {
114 DirectiveMap[Directive] = std::make_pair(Object, Handler);
118 /// @name MCAsmParser Interface
121 virtual SourceMgr &getSourceManager() { return SrcMgr; }
122 virtual MCAsmLexer &getLexer() { return Lexer; }
123 virtual MCContext &getContext() { return Ctx; }
124 virtual MCStreamer &getStreamer() { return Out; }
126 virtual void Warning(SMLoc L, const Twine &Meg);
127 virtual bool Error(SMLoc L, const Twine &Msg);
129 const AsmToken &Lex();
131 bool ParseExpression(const MCExpr *&Res);
132 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
133 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
134 virtual bool ParseAbsoluteExpression(int64_t &Res);
139 bool ParseStatement();
141 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
142 void HandleMacroExit();
144 void PrintMacroInstantiations();
145 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
147 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
148 bool EnterIncludeFile(const std::string &Filename);
150 /// \brief Reset the current lexer position to that given by \arg Loc. The
151 /// current token is not set; clients should ensure Lex() is called
153 void JumpToLoc(SMLoc Loc);
155 void EatToEndOfStatement();
157 /// \brief Parse up to the end of statement and a return the contents from the
158 /// current token until the end of the statement; the current token on exit
159 /// will be either the EndOfStatement or EOF.
160 StringRef ParseStringToEndOfStatement();
162 bool ParseAssignment(StringRef Name);
164 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
165 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
166 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
168 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
169 /// and set \arg Res to the identifier contents.
170 bool ParseIdentifier(StringRef &Res);
172 // Directive Parsing.
173 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
174 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
175 bool ParseDirectiveFill(); // ".fill"
176 bool ParseDirectiveSpace(); // ".space"
177 bool ParseDirectiveSet(); // ".set"
178 bool ParseDirectiveOrg(); // ".org"
179 // ".align{,32}", ".p2align{,w,l}"
180 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
182 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
183 /// accepts a single symbol (which should be a label or an external).
184 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
185 bool ParseDirectiveELFType(); // ELF specific ".type"
187 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
189 bool ParseDirectiveAbort(); // ".abort"
190 bool ParseDirectiveInclude(); // ".include"
192 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
193 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
194 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
195 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
197 /// ParseEscapedString - Parse the current token as a string which may include
198 /// escaped characters and return the string contents.
199 bool ParseEscapedString(std::string &Data);
202 /// \brief Generic implementations of directive handling, etc. which is shared
203 /// (or the default, at least) for all assembler parser.
204 class GenericAsmParser : public MCAsmParserExtension {
205 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
206 void AddDirectiveHandler(StringRef Directive) {
207 getParser().AddDirectiveHandler(this, Directive,
208 HandleDirective<GenericAsmParser, Handler>);
212 GenericAsmParser() {}
214 AsmParser &getParser() {
215 return (AsmParser&) this->MCAsmParserExtension::getParser();
218 virtual void Initialize(MCAsmParser &Parser) {
219 // Call the base implementation.
220 this->MCAsmParserExtension::Initialize(Parser);
222 // Debugging directives.
223 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
224 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
225 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
228 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
230 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
232 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
233 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
237 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
238 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
239 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
241 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
242 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
243 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
250 extern MCAsmParserExtension *createDarwinAsmParser();
251 extern MCAsmParserExtension *createELFAsmParser();
255 enum { DEFAULT_ADDRSPACE = 0 };
257 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
258 MCStreamer &_Out, const MCAsmInfo &_MAI)
259 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
260 GenericParser(new GenericAsmParser), PlatformParser(0),
261 CurBuffer(0), MacrosEnabled(true) {
262 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
264 // Initialize the generic parser.
265 GenericParser->Initialize(*this);
267 // Initialize the platform / file format parser.
269 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
271 if (_MAI.hasSubsectionsViaSymbols()) {
272 PlatformParser = createDarwinAsmParser();
273 PlatformParser->Initialize(*this);
275 PlatformParser = createELFAsmParser();
276 PlatformParser->Initialize(*this);
280 AsmParser::~AsmParser() {
281 delete PlatformParser;
282 delete GenericParser;
285 void AsmParser::PrintMacroInstantiations() {
286 // Print the active macro instantiation stack.
287 for (std::vector<MacroInstantiation*>::const_reverse_iterator
288 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
289 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
293 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
294 PrintMessage(L, Msg.str(), "warning");
295 PrintMacroInstantiations();
298 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
299 PrintMessage(L, Msg.str(), "error");
300 PrintMacroInstantiations();
304 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
305 const char *Type) const {
306 SrcMgr.PrintMessage(Loc, Msg, Type);
309 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
310 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
316 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
321 void AsmParser::JumpToLoc(SMLoc Loc) {
322 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
323 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
326 const AsmToken &AsmParser::Lex() {
327 const AsmToken *tok = &Lexer.Lex();
329 if (tok->is(AsmToken::Eof)) {
330 // If this is the end of an included file, pop the parent file off the
332 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
333 if (ParentIncludeLoc != SMLoc()) {
334 JumpToLoc(ParentIncludeLoc);
339 if (tok->is(AsmToken::Error))
340 Error(Lexer.getErrLoc(), Lexer.getErr());
345 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
346 // Create the initial section, if requested.
348 // FIXME: Target hook & command line option for initial section.
349 if (!NoInitialTextSection)
350 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
351 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
352 0, SectionKind::getText()));
357 bool HadError = false;
359 AsmCond StartingCondState = TheCondState;
361 // While we have input, parse each statement.
362 while (Lexer.isNot(AsmToken::Eof)) {
363 if (!ParseStatement()) continue;
365 // We had an error, remember it and recover by skipping to the next line.
367 EatToEndOfStatement();
370 if (TheCondState.TheCond != StartingCondState.TheCond ||
371 TheCondState.Ignore != StartingCondState.Ignore)
372 return TokError("unmatched .ifs or .elses");
374 // Finalize the output stream if there are no errors and if the client wants
376 if (!HadError && !NoFinalize)
382 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
383 void AsmParser::EatToEndOfStatement() {
384 while (Lexer.isNot(AsmToken::EndOfStatement) &&
385 Lexer.isNot(AsmToken::Eof))
389 if (Lexer.is(AsmToken::EndOfStatement))
393 StringRef AsmParser::ParseStringToEndOfStatement() {
394 const char *Start = getTok().getLoc().getPointer();
396 while (Lexer.isNot(AsmToken::EndOfStatement) &&
397 Lexer.isNot(AsmToken::Eof))
400 const char *End = getTok().getLoc().getPointer();
401 return StringRef(Start, End - Start);
404 /// ParseParenExpr - Parse a paren expression and return it.
405 /// NOTE: This assumes the leading '(' has already been consumed.
407 /// parenexpr ::= expr)
409 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
410 if (ParseExpression(Res)) return true;
411 if (Lexer.isNot(AsmToken::RParen))
412 return TokError("expected ')' in parentheses expression");
413 EndLoc = Lexer.getLoc();
418 /// ParsePrimaryExpr - Parse a primary expression and return it.
419 /// primaryexpr ::= (parenexpr
420 /// primaryexpr ::= symbol
421 /// primaryexpr ::= number
422 /// primaryexpr ::= '.'
423 /// primaryexpr ::= ~,+,- primaryexpr
424 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
425 switch (Lexer.getKind()) {
427 return TokError("unknown token in expression");
428 case AsmToken::Exclaim:
429 Lex(); // Eat the operator.
430 if (ParsePrimaryExpr(Res, EndLoc))
432 Res = MCUnaryExpr::CreateLNot(Res, getContext());
434 case AsmToken::String:
435 case AsmToken::Identifier: {
436 // This is a symbol reference.
437 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
438 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
440 // Mark the symbol as used in an expression.
441 Sym->setUsedInExpr(true);
443 // Lookup the symbol variant if used.
444 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
445 if (Split.first.size() != getTok().getIdentifier().size())
446 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
448 EndLoc = Lexer.getLoc();
449 Lex(); // Eat identifier.
451 // If this is an absolute variable reference, substitute it now to preserve
452 // semantics in the face of reassignment.
453 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
455 return Error(EndLoc, "unexpected modified on variable reference");
457 Res = Sym->getVariableValue();
461 // Otherwise create a symbol ref.
462 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
465 case AsmToken::Integer: {
466 SMLoc Loc = getTok().getLoc();
467 int64_t IntVal = getTok().getIntVal();
468 Res = MCConstantExpr::Create(IntVal, getContext());
469 EndLoc = Lexer.getLoc();
471 // Look for 'b' or 'f' following an Integer as a directional label
472 if (Lexer.getKind() == AsmToken::Identifier) {
473 StringRef IDVal = getTok().getString();
474 if (IDVal == "f" || IDVal == "b"){
475 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
476 IDVal == "f" ? 1 : 0);
477 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
479 if(IDVal == "b" && Sym->isUndefined())
480 return Error(Loc, "invalid reference to undefined symbol");
481 EndLoc = Lexer.getLoc();
482 Lex(); // Eat identifier.
487 case AsmToken::Dot: {
488 // This is a '.' reference, which references the current PC. Emit a
489 // temporary label to the streamer and refer to it.
490 MCSymbol *Sym = Ctx.CreateTempSymbol();
492 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
493 EndLoc = Lexer.getLoc();
494 Lex(); // Eat identifier.
498 case AsmToken::LParen:
499 Lex(); // Eat the '('.
500 return ParseParenExpr(Res, EndLoc);
501 case AsmToken::Minus:
502 Lex(); // Eat the operator.
503 if (ParsePrimaryExpr(Res, EndLoc))
505 Res = MCUnaryExpr::CreateMinus(Res, getContext());
508 Lex(); // Eat the operator.
509 if (ParsePrimaryExpr(Res, EndLoc))
511 Res = MCUnaryExpr::CreatePlus(Res, getContext());
513 case AsmToken::Tilde:
514 Lex(); // Eat the operator.
515 if (ParsePrimaryExpr(Res, EndLoc))
517 Res = MCUnaryExpr::CreateNot(Res, getContext());
522 bool AsmParser::ParseExpression(const MCExpr *&Res) {
524 return ParseExpression(Res, EndLoc);
527 /// ParseExpression - Parse an expression and return it.
529 /// expr ::= expr +,- expr -> lowest.
530 /// expr ::= expr |,^,&,! expr -> middle.
531 /// expr ::= expr *,/,%,<<,>> expr -> highest.
532 /// expr ::= primaryexpr
534 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
535 // Parse the expression.
537 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
540 // Try to constant fold it up front, if possible.
542 if (Res->EvaluateAsAbsolute(Value))
543 Res = MCConstantExpr::Create(Value, getContext());
548 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
550 return ParseParenExpr(Res, EndLoc) ||
551 ParseBinOpRHS(1, Res, EndLoc);
554 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
557 SMLoc StartLoc = Lexer.getLoc();
558 if (ParseExpression(Expr))
561 if (!Expr->EvaluateAsAbsolute(Res))
562 return Error(StartLoc, "expected absolute expression");
567 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
568 MCBinaryExpr::Opcode &Kind) {
571 return 0; // not a binop.
573 // Lowest Precedence: &&, ||
574 case AsmToken::AmpAmp:
575 Kind = MCBinaryExpr::LAnd;
577 case AsmToken::PipePipe:
578 Kind = MCBinaryExpr::LOr;
581 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
583 Kind = MCBinaryExpr::Add;
585 case AsmToken::Minus:
586 Kind = MCBinaryExpr::Sub;
588 case AsmToken::EqualEqual:
589 Kind = MCBinaryExpr::EQ;
591 case AsmToken::ExclaimEqual:
592 case AsmToken::LessGreater:
593 Kind = MCBinaryExpr::NE;
596 Kind = MCBinaryExpr::LT;
598 case AsmToken::LessEqual:
599 Kind = MCBinaryExpr::LTE;
601 case AsmToken::Greater:
602 Kind = MCBinaryExpr::GT;
604 case AsmToken::GreaterEqual:
605 Kind = MCBinaryExpr::GTE;
608 // Intermediate Precedence: |, &, ^
610 // FIXME: gas seems to support '!' as an infix operator?
612 Kind = MCBinaryExpr::Or;
614 case AsmToken::Caret:
615 Kind = MCBinaryExpr::Xor;
618 Kind = MCBinaryExpr::And;
621 // Highest Precedence: *, /, %, <<, >>
623 Kind = MCBinaryExpr::Mul;
625 case AsmToken::Slash:
626 Kind = MCBinaryExpr::Div;
628 case AsmToken::Percent:
629 Kind = MCBinaryExpr::Mod;
631 case AsmToken::LessLess:
632 Kind = MCBinaryExpr::Shl;
634 case AsmToken::GreaterGreater:
635 Kind = MCBinaryExpr::Shr;
641 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
642 /// Res contains the LHS of the expression on input.
643 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
646 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
647 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
649 // If the next token is lower precedence than we are allowed to eat, return
650 // successfully with what we ate already.
651 if (TokPrec < Precedence)
656 // Eat the next primary expression.
658 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
660 // If BinOp binds less tightly with RHS than the operator after RHS, let
661 // the pending operator take RHS as its LHS.
662 MCBinaryExpr::Opcode Dummy;
663 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
664 if (TokPrec < NextTokPrec) {
665 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
668 // Merge LHS and RHS according to operator.
669 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
677 /// ::= EndOfStatement
678 /// ::= Label* Directive ...Operands... EndOfStatement
679 /// ::= Label* Identifier OperandList* EndOfStatement
680 bool AsmParser::ParseStatement() {
681 if (Lexer.is(AsmToken::EndOfStatement)) {
687 // Statements always start with an identifier.
688 AsmToken ID = getTok();
689 SMLoc IDLoc = ID.getLoc();
691 int64_t LocalLabelVal = -1;
692 // GUESS allow an integer followed by a ':' as a directional local label
693 if (Lexer.is(AsmToken::Integer)) {
694 LocalLabelVal = getTok().getIntVal();
695 if (LocalLabelVal < 0) {
696 if (!TheCondState.Ignore)
697 return TokError("unexpected token at start of statement");
701 IDVal = getTok().getString();
702 Lex(); // Consume the integer token to be used as an identifier token.
703 if (Lexer.getKind() != AsmToken::Colon) {
704 if (!TheCondState.Ignore)
705 return TokError("unexpected token at start of statement");
709 else if (ParseIdentifier(IDVal)) {
710 if (!TheCondState.Ignore)
711 return TokError("unexpected token at start of statement");
715 // Handle conditional assembly here before checking for skipping. We
716 // have to do this so that .endif isn't skipped in a ".if 0" block for
719 return ParseDirectiveIf(IDLoc);
720 if (IDVal == ".elseif")
721 return ParseDirectiveElseIf(IDLoc);
722 if (IDVal == ".else")
723 return ParseDirectiveElse(IDLoc);
724 if (IDVal == ".endif")
725 return ParseDirectiveEndIf(IDLoc);
727 // If we are in a ".if 0" block, ignore this statement.
728 if (TheCondState.Ignore) {
729 EatToEndOfStatement();
733 // FIXME: Recurse on local labels?
735 // See what kind of statement we have.
736 switch (Lexer.getKind()) {
737 case AsmToken::Colon: {
738 // identifier ':' -> Label.
741 // Diagnose attempt to use a variable as a label.
743 // FIXME: Diagnostics. Note the location of the definition as a label.
744 // FIXME: This doesn't diagnose assignment to a symbol which has been
745 // implicitly marked as external.
747 if (LocalLabelVal == -1)
748 Sym = getContext().GetOrCreateSymbol(IDVal);
750 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
751 if (!Sym->isUndefined() || Sym->isVariable())
752 return Error(IDLoc, "invalid symbol redefinition");
757 // Consume any end of statement token, if present, to avoid spurious
758 // AddBlankLine calls().
759 if (Lexer.is(AsmToken::EndOfStatement)) {
761 if (Lexer.is(AsmToken::Eof))
765 return ParseStatement();
768 case AsmToken::Equal:
769 // identifier '=' ... -> assignment statement
772 return ParseAssignment(IDVal);
774 default: // Normal instruction or directive.
778 // If macros are enabled, check to see if this is a macro instantiation.
780 if (const Macro *M = MacroMap.lookup(IDVal))
781 return HandleMacroEntry(IDVal, IDLoc, M);
783 // Otherwise, we have a normal instruction or directive.
784 if (IDVal[0] == '.') {
785 // Assembler features
787 return ParseDirectiveSet();
791 if (IDVal == ".ascii")
792 return ParseDirectiveAscii(false);
793 if (IDVal == ".asciz")
794 return ParseDirectiveAscii(true);
796 if (IDVal == ".byte")
797 return ParseDirectiveValue(1);
798 if (IDVal == ".short")
799 return ParseDirectiveValue(2);
800 if (IDVal == ".long")
801 return ParseDirectiveValue(4);
802 if (IDVal == ".quad")
803 return ParseDirectiveValue(8);
805 if (IDVal == ".align") {
806 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
807 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
809 if (IDVal == ".align32") {
810 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
811 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
813 if (IDVal == ".balign")
814 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
815 if (IDVal == ".balignw")
816 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
817 if (IDVal == ".balignl")
818 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
819 if (IDVal == ".p2align")
820 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
821 if (IDVal == ".p2alignw")
822 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
823 if (IDVal == ".p2alignl")
824 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
827 return ParseDirectiveOrg();
829 if (IDVal == ".fill")
830 return ParseDirectiveFill();
831 if (IDVal == ".space")
832 return ParseDirectiveSpace();
834 // Symbol attribute directives
836 if (IDVal == ".globl" || IDVal == ".global")
837 return ParseDirectiveSymbolAttribute(MCSA_Global);
838 if (IDVal == ".hidden")
839 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
840 if (IDVal == ".indirect_symbol")
841 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
842 if (IDVal == ".internal")
843 return ParseDirectiveSymbolAttribute(MCSA_Internal);
844 if (IDVal == ".lazy_reference")
845 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
846 if (IDVal == ".no_dead_strip")
847 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
848 if (IDVal == ".private_extern")
849 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
850 if (IDVal == ".protected")
851 return ParseDirectiveSymbolAttribute(MCSA_Protected);
852 if (IDVal == ".reference")
853 return ParseDirectiveSymbolAttribute(MCSA_Reference);
854 if (IDVal == ".type")
855 return ParseDirectiveELFType();
856 if (IDVal == ".weak")
857 return ParseDirectiveSymbolAttribute(MCSA_Weak);
858 if (IDVal == ".weak_definition")
859 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
860 if (IDVal == ".weak_reference")
861 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
862 if (IDVal == ".weak_def_can_be_hidden")
863 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
865 if (IDVal == ".comm")
866 return ParseDirectiveComm(/*IsLocal=*/false);
867 if (IDVal == ".lcomm")
868 return ParseDirectiveComm(/*IsLocal=*/true);
870 if (IDVal == ".abort")
871 return ParseDirectiveAbort();
872 if (IDVal == ".include")
873 return ParseDirectiveInclude();
875 // Look up the handler in the handler table.
876 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
877 DirectiveMap.lookup(IDVal);
879 return (*Handler.second)(Handler.first, IDVal, IDLoc);
881 // Target hook for parsing target specific directives.
882 if (!getTargetParser().ParseDirective(ID))
885 Warning(IDLoc, "ignoring directive for now");
886 EatToEndOfStatement();
890 // Canonicalize the opcode to lower case.
891 SmallString<128> Opcode;
892 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
893 Opcode.push_back(tolower(IDVal[i]));
895 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
896 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
898 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
899 HadError = TokError("unexpected token in argument list");
901 // If parsing succeeded, match the instruction.
904 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
905 // Emit the instruction on success.
906 Out.EmitInstruction(Inst);
908 // Otherwise emit a diagnostic about the match failure and set the error
911 // FIXME: We should give nicer diagnostics about the exact failure.
912 Error(IDLoc, "unrecognized instruction");
917 // If there was no error, consume the end-of-statement token. Otherwise this
918 // will be done by our caller.
922 // Free any parsed operands.
923 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
924 delete ParsedOperands[i];
929 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
930 const std::vector<std::vector<AsmToken> > &A)
931 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
933 // Macro instantiation is lexical, unfortunately. We construct a new buffer
934 // to hold the macro body with substitutions.
935 SmallString<256> Buf;
936 raw_svector_ostream OS(Buf);
938 StringRef Body = M->Body;
939 while (!Body.empty()) {
940 // Scan for the next substitution.
941 std::size_t End = Body.size(), Pos = 0;
942 for (; Pos != End; ++Pos) {
943 // Check for a substitution or escape.
944 if (Body[Pos] != '$' || Pos + 1 == End)
947 char Next = Body[Pos + 1];
948 if (Next == '$' || Next == 'n' || isdigit(Next))
953 OS << Body.slice(0, Pos);
955 // Check if we reached the end.
959 switch (Body[Pos+1]) {
965 // $n => number of arguments
970 // $[0-9] => argument
972 // Missing arguments are ignored.
973 unsigned Index = Body[Pos+1] - '0';
974 if (Index >= A.size())
977 // Otherwise substitute with the token values, with spaces eliminated.
978 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
979 ie = A[Index].end(); it != ie; ++it)
980 OS << it->getString();
985 // Update the scan point.
986 Body = Body.substr(Pos + 2);
989 // We include the .endmacro in the buffer as our queue to exit the macro
993 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
996 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
998 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
999 // this, although we should protect against infinite loops.
1000 if (ActiveMacros.size() == 20)
1001 return TokError("macros cannot be nested more than 20 levels deep");
1003 // Parse the macro instantiation arguments.
1004 std::vector<std::vector<AsmToken> > MacroArguments;
1005 MacroArguments.push_back(std::vector<AsmToken>());
1006 unsigned ParenLevel = 0;
1008 if (Lexer.is(AsmToken::Eof))
1009 return TokError("unexpected token in macro instantiation");
1010 if (Lexer.is(AsmToken::EndOfStatement))
1013 // If we aren't inside parentheses and this is a comma, start a new token
1015 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1016 MacroArguments.push_back(std::vector<AsmToken>());
1017 } else if (Lexer.is(AsmToken::LParen)) {
1019 } else if (Lexer.is(AsmToken::RParen)) {
1023 MacroArguments.back().push_back(getTok());
1028 // Create the macro instantiation object and add to the current macro
1029 // instantiation stack.
1030 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1033 ActiveMacros.push_back(MI);
1035 // Jump to the macro instantiation and prime the lexer.
1036 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1037 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1043 void AsmParser::HandleMacroExit() {
1044 // Jump to the EndOfStatement we should return to, and consume it.
1045 JumpToLoc(ActiveMacros.back()->ExitLoc);
1048 // Pop the instantiation entry.
1049 delete ActiveMacros.back();
1050 ActiveMacros.pop_back();
1053 bool AsmParser::ParseAssignment(StringRef Name) {
1054 // FIXME: Use better location, we should use proper tokens.
1055 SMLoc EqualLoc = Lexer.getLoc();
1057 const MCExpr *Value;
1058 if (ParseExpression(Value))
1061 if (Lexer.isNot(AsmToken::EndOfStatement))
1062 return TokError("unexpected token in assignment");
1064 // Eat the end of statement marker.
1067 // Validate that the LHS is allowed to be a variable (either it has not been
1068 // used as a symbol, or it is an absolute symbol).
1069 MCSymbol *Sym = getContext().LookupSymbol(Name);
1071 // Diagnose assignment to a label.
1073 // FIXME: Diagnostics. Note the location of the definition as a label.
1074 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1075 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1076 ; // Allow redefinitions of undefined symbols only used in directives.
1077 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1078 return Error(EqualLoc, "redefinition of '" + Name + "'");
1079 else if (!Sym->isVariable())
1080 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1081 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1082 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1085 Sym = getContext().GetOrCreateSymbol(Name);
1087 // FIXME: Handle '.'.
1089 Sym->setUsedInExpr(true);
1091 // Do the assignment.
1092 Out.EmitAssignment(Sym, Value);
1097 /// ParseIdentifier:
1100 bool AsmParser::ParseIdentifier(StringRef &Res) {
1101 if (Lexer.isNot(AsmToken::Identifier) &&
1102 Lexer.isNot(AsmToken::String))
1105 Res = getTok().getIdentifier();
1107 Lex(); // Consume the identifier token.
1112 /// ParseDirectiveSet:
1113 /// ::= .set identifier ',' expression
1114 bool AsmParser::ParseDirectiveSet() {
1117 if (ParseIdentifier(Name))
1118 return TokError("expected identifier after '.set' directive");
1120 if (getLexer().isNot(AsmToken::Comma))
1121 return TokError("unexpected token in '.set'");
1124 return ParseAssignment(Name);
1127 bool AsmParser::ParseEscapedString(std::string &Data) {
1128 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1131 StringRef Str = getTok().getStringContents();
1132 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1133 if (Str[i] != '\\') {
1138 // Recognize escaped characters. Note that this escape semantics currently
1139 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1142 return TokError("unexpected backslash at end of string");
1144 // Recognize octal sequences.
1145 if ((unsigned) (Str[i] - '0') <= 7) {
1146 // Consume up to three octal characters.
1147 unsigned Value = Str[i] - '0';
1149 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1151 Value = Value * 8 + (Str[i] - '0');
1153 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1155 Value = Value * 8 + (Str[i] - '0');
1160 return TokError("invalid octal escape sequence (out of range)");
1162 Data += (unsigned char) Value;
1166 // Otherwise recognize individual escapes.
1169 // Just reject invalid escape sequences for now.
1170 return TokError("invalid escape sequence (unrecognized character)");
1172 case 'b': Data += '\b'; break;
1173 case 'f': Data += '\f'; break;
1174 case 'n': Data += '\n'; break;
1175 case 'r': Data += '\r'; break;
1176 case 't': Data += '\t'; break;
1177 case '"': Data += '"'; break;
1178 case '\\': Data += '\\'; break;
1185 /// ParseDirectiveAscii:
1186 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1187 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1188 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1190 if (getLexer().isNot(AsmToken::String))
1191 return TokError("expected string in '.ascii' or '.asciz' directive");
1194 if (ParseEscapedString(Data))
1197 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1199 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1203 if (getLexer().is(AsmToken::EndOfStatement))
1206 if (getLexer().isNot(AsmToken::Comma))
1207 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1216 /// ParseDirectiveValue
1217 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1218 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1219 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1221 const MCExpr *Value;
1222 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1223 if (ParseExpression(Value))
1226 // Special case constant expressions to match code generator.
1227 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1228 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1230 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1232 if (getLexer().is(AsmToken::EndOfStatement))
1235 // FIXME: Improve diagnostic.
1236 if (getLexer().isNot(AsmToken::Comma))
1237 return TokError("unexpected token in directive");
1246 /// ParseDirectiveSpace
1247 /// ::= .space expression [ , expression ]
1248 bool AsmParser::ParseDirectiveSpace() {
1250 if (ParseAbsoluteExpression(NumBytes))
1253 int64_t FillExpr = 0;
1254 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1255 if (getLexer().isNot(AsmToken::Comma))
1256 return TokError("unexpected token in '.space' directive");
1259 if (ParseAbsoluteExpression(FillExpr))
1262 if (getLexer().isNot(AsmToken::EndOfStatement))
1263 return TokError("unexpected token in '.space' directive");
1269 return TokError("invalid number of bytes in '.space' directive");
1271 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1272 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1277 /// ParseDirectiveFill
1278 /// ::= .fill expression , expression , expression
1279 bool AsmParser::ParseDirectiveFill() {
1281 if (ParseAbsoluteExpression(NumValues))
1284 if (getLexer().isNot(AsmToken::Comma))
1285 return TokError("unexpected token in '.fill' directive");
1289 if (ParseAbsoluteExpression(FillSize))
1292 if (getLexer().isNot(AsmToken::Comma))
1293 return TokError("unexpected token in '.fill' directive");
1297 if (ParseAbsoluteExpression(FillExpr))
1300 if (getLexer().isNot(AsmToken::EndOfStatement))
1301 return TokError("unexpected token in '.fill' directive");
1305 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1306 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1308 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1309 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1314 /// ParseDirectiveOrg
1315 /// ::= .org expression [ , expression ]
1316 bool AsmParser::ParseDirectiveOrg() {
1317 const MCExpr *Offset;
1318 if (ParseExpression(Offset))
1321 // Parse optional fill expression.
1322 int64_t FillExpr = 0;
1323 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1324 if (getLexer().isNot(AsmToken::Comma))
1325 return TokError("unexpected token in '.org' directive");
1328 if (ParseAbsoluteExpression(FillExpr))
1331 if (getLexer().isNot(AsmToken::EndOfStatement))
1332 return TokError("unexpected token in '.org' directive");
1337 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1338 // has to be relative to the current section.
1339 getStreamer().EmitValueToOffset(Offset, FillExpr);
1344 /// ParseDirectiveAlign
1345 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1346 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1347 SMLoc AlignmentLoc = getLexer().getLoc();
1349 if (ParseAbsoluteExpression(Alignment))
1353 bool HasFillExpr = false;
1354 int64_t FillExpr = 0;
1355 int64_t MaxBytesToFill = 0;
1356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1357 if (getLexer().isNot(AsmToken::Comma))
1358 return TokError("unexpected token in directive");
1361 // The fill expression can be omitted while specifying a maximum number of
1362 // alignment bytes, e.g:
1364 if (getLexer().isNot(AsmToken::Comma)) {
1366 if (ParseAbsoluteExpression(FillExpr))
1370 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1371 if (getLexer().isNot(AsmToken::Comma))
1372 return TokError("unexpected token in directive");
1375 MaxBytesLoc = getLexer().getLoc();
1376 if (ParseAbsoluteExpression(MaxBytesToFill))
1379 if (getLexer().isNot(AsmToken::EndOfStatement))
1380 return TokError("unexpected token in directive");
1389 // Compute alignment in bytes.
1391 // FIXME: Diagnose overflow.
1392 if (Alignment >= 32) {
1393 Error(AlignmentLoc, "invalid alignment value");
1397 Alignment = 1ULL << Alignment;
1400 // Diagnose non-sensical max bytes to align.
1401 if (MaxBytesLoc.isValid()) {
1402 if (MaxBytesToFill < 1) {
1403 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1404 "many bytes, ignoring maximum bytes expression");
1408 if (MaxBytesToFill >= Alignment) {
1409 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1415 // Check whether we should use optimal code alignment for this .align
1418 // FIXME: This should be using a target hook.
1419 bool UseCodeAlign = false;
1420 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1421 getStreamer().getCurrentSection()))
1422 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1423 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1424 ValueSize == 1 && UseCodeAlign) {
1425 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1427 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1428 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1435 /// ParseDirectiveSymbolAttribute
1436 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1437 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1438 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1442 if (ParseIdentifier(Name))
1443 return TokError("expected identifier in directive");
1445 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1447 getStreamer().EmitSymbolAttribute(Sym, Attr);
1449 if (getLexer().is(AsmToken::EndOfStatement))
1452 if (getLexer().isNot(AsmToken::Comma))
1453 return TokError("unexpected token in directive");
1462 /// ParseDirectiveELFType
1463 /// ::= .type identifier , @attribute
1464 bool AsmParser::ParseDirectiveELFType() {
1466 if (ParseIdentifier(Name))
1467 return TokError("expected identifier in directive");
1469 // Handle the identifier as the key symbol.
1470 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1472 if (getLexer().isNot(AsmToken::Comma))
1473 return TokError("unexpected token in '.type' directive");
1476 if (getLexer().isNot(AsmToken::At))
1477 return TokError("expected '@' before type");
1483 TypeLoc = getLexer().getLoc();
1484 if (ParseIdentifier(Type))
1485 return TokError("expected symbol type in directive");
1487 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1488 .Case("function", MCSA_ELF_TypeFunction)
1489 .Case("object", MCSA_ELF_TypeObject)
1490 .Case("tls_object", MCSA_ELF_TypeTLS)
1491 .Case("common", MCSA_ELF_TypeCommon)
1492 .Case("notype", MCSA_ELF_TypeNoType)
1493 .Default(MCSA_Invalid);
1495 if (Attr == MCSA_Invalid)
1496 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1498 if (getLexer().isNot(AsmToken::EndOfStatement))
1499 return TokError("unexpected token in '.type' directive");
1503 getStreamer().EmitSymbolAttribute(Sym, Attr);
1508 /// ParseDirectiveComm
1509 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1510 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1511 SMLoc IDLoc = getLexer().getLoc();
1513 if (ParseIdentifier(Name))
1514 return TokError("expected identifier in directive");
1516 // Handle the identifier as the key symbol.
1517 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1519 if (getLexer().isNot(AsmToken::Comma))
1520 return TokError("unexpected token in directive");
1524 SMLoc SizeLoc = getLexer().getLoc();
1525 if (ParseAbsoluteExpression(Size))
1528 int64_t Pow2Alignment = 0;
1529 SMLoc Pow2AlignmentLoc;
1530 if (getLexer().is(AsmToken::Comma)) {
1532 Pow2AlignmentLoc = getLexer().getLoc();
1533 if (ParseAbsoluteExpression(Pow2Alignment))
1536 // If this target takes alignments in bytes (not log) validate and convert.
1537 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1538 if (!isPowerOf2_64(Pow2Alignment))
1539 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1540 Pow2Alignment = Log2_64(Pow2Alignment);
1544 if (getLexer().isNot(AsmToken::EndOfStatement))
1545 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1549 // NOTE: a size of zero for a .comm should create a undefined symbol
1550 // but a size of .lcomm creates a bss symbol of size zero.
1552 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1553 "be less than zero");
1555 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1556 // may internally end up wanting an alignment in bytes.
1557 // FIXME: Diagnose overflow.
1558 if (Pow2Alignment < 0)
1559 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1560 "alignment, can't be less than zero");
1562 if (!Sym->isUndefined())
1563 return Error(IDLoc, "invalid symbol redefinition");
1565 // '.lcomm' is equivalent to '.zerofill'.
1566 // Create the Symbol as a common or local common with Size and Pow2Alignment
1568 getStreamer().EmitZerofill(Ctx.getMachOSection(
1569 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1570 0, SectionKind::getBSS()),
1571 Sym, Size, 1 << Pow2Alignment);
1575 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1579 /// ParseDirectiveAbort
1580 /// ::= .abort [... message ...]
1581 bool AsmParser::ParseDirectiveAbort() {
1582 // FIXME: Use loc from directive.
1583 SMLoc Loc = getLexer().getLoc();
1585 StringRef Str = ParseStringToEndOfStatement();
1586 if (getLexer().isNot(AsmToken::EndOfStatement))
1587 return TokError("unexpected token in '.abort' directive");
1592 Error(Loc, ".abort detected. Assembly stopping.");
1594 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1595 // FIXME: Actually abort assembly here.
1600 /// ParseDirectiveInclude
1601 /// ::= .include "filename"
1602 bool AsmParser::ParseDirectiveInclude() {
1603 if (getLexer().isNot(AsmToken::String))
1604 return TokError("expected string in '.include' directive");
1606 std::string Filename = getTok().getString();
1607 SMLoc IncludeLoc = getLexer().getLoc();
1610 if (getLexer().isNot(AsmToken::EndOfStatement))
1611 return TokError("unexpected token in '.include' directive");
1613 // Strip the quotes.
1614 Filename = Filename.substr(1, Filename.size()-2);
1616 // Attempt to switch the lexer to the included file before consuming the end
1617 // of statement to avoid losing it when we switch.
1618 if (EnterIncludeFile(Filename)) {
1619 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1626 /// ParseDirectiveIf
1627 /// ::= .if expression
1628 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1629 TheCondStack.push_back(TheCondState);
1630 TheCondState.TheCond = AsmCond::IfCond;
1631 if(TheCondState.Ignore) {
1632 EatToEndOfStatement();
1636 if (ParseAbsoluteExpression(ExprValue))
1639 if (getLexer().isNot(AsmToken::EndOfStatement))
1640 return TokError("unexpected token in '.if' directive");
1644 TheCondState.CondMet = ExprValue;
1645 TheCondState.Ignore = !TheCondState.CondMet;
1651 /// ParseDirectiveElseIf
1652 /// ::= .elseif expression
1653 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1654 if (TheCondState.TheCond != AsmCond::IfCond &&
1655 TheCondState.TheCond != AsmCond::ElseIfCond)
1656 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1658 TheCondState.TheCond = AsmCond::ElseIfCond;
1660 bool LastIgnoreState = false;
1661 if (!TheCondStack.empty())
1662 LastIgnoreState = TheCondStack.back().Ignore;
1663 if (LastIgnoreState || TheCondState.CondMet) {
1664 TheCondState.Ignore = true;
1665 EatToEndOfStatement();
1669 if (ParseAbsoluteExpression(ExprValue))
1672 if (getLexer().isNot(AsmToken::EndOfStatement))
1673 return TokError("unexpected token in '.elseif' directive");
1676 TheCondState.CondMet = ExprValue;
1677 TheCondState.Ignore = !TheCondState.CondMet;
1683 /// ParseDirectiveElse
1685 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1686 if (getLexer().isNot(AsmToken::EndOfStatement))
1687 return TokError("unexpected token in '.else' directive");
1691 if (TheCondState.TheCond != AsmCond::IfCond &&
1692 TheCondState.TheCond != AsmCond::ElseIfCond)
1693 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1695 TheCondState.TheCond = AsmCond::ElseCond;
1696 bool LastIgnoreState = false;
1697 if (!TheCondStack.empty())
1698 LastIgnoreState = TheCondStack.back().Ignore;
1699 if (LastIgnoreState || TheCondState.CondMet)
1700 TheCondState.Ignore = true;
1702 TheCondState.Ignore = false;
1707 /// ParseDirectiveEndIf
1709 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1710 if (getLexer().isNot(AsmToken::EndOfStatement))
1711 return TokError("unexpected token in '.endif' directive");
1715 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1716 TheCondStack.empty())
1717 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1719 if (!TheCondStack.empty()) {
1720 TheCondState = TheCondStack.back();
1721 TheCondStack.pop_back();
1727 /// ParseDirectiveFile
1728 /// ::= .file [number] string
1729 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1730 // FIXME: I'm not sure what this is.
1731 int64_t FileNumber = -1;
1732 if (getLexer().is(AsmToken::Integer)) {
1733 FileNumber = getTok().getIntVal();
1737 return TokError("file number less than one");
1740 if (getLexer().isNot(AsmToken::String))
1741 return TokError("unexpected token in '.file' directive");
1743 StringRef Filename = getTok().getString();
1744 Filename = Filename.substr(1, Filename.size()-2);
1747 if (getLexer().isNot(AsmToken::EndOfStatement))
1748 return TokError("unexpected token in '.file' directive");
1750 if (FileNumber == -1)
1751 getStreamer().EmitFileDirective(Filename);
1753 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1758 /// ParseDirectiveLine
1759 /// ::= .line [number]
1760 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1761 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1762 if (getLexer().isNot(AsmToken::Integer))
1763 return TokError("unexpected token in '.line' directive");
1765 int64_t LineNumber = getTok().getIntVal();
1769 // FIXME: Do something with the .line.
1772 if (getLexer().isNot(AsmToken::EndOfStatement))
1773 return TokError("unexpected token in '.line' directive");
1779 /// ParseDirectiveLoc
1780 /// ::= .loc number [number [number]]
1781 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1782 if (getLexer().isNot(AsmToken::Integer))
1783 return TokError("unexpected token in '.loc' directive");
1785 // FIXME: What are these fields?
1786 int64_t FileNumber = getTok().getIntVal();
1788 // FIXME: Validate file.
1791 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1792 if (getLexer().isNot(AsmToken::Integer))
1793 return TokError("unexpected token in '.loc' directive");
1795 int64_t Param2 = getTok().getIntVal();
1799 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1800 if (getLexer().isNot(AsmToken::Integer))
1801 return TokError("unexpected token in '.loc' directive");
1803 int64_t Param3 = getTok().getIntVal();
1807 // FIXME: Do something with the .loc.
1811 if (getLexer().isNot(AsmToken::EndOfStatement))
1812 return TokError("unexpected token in '.file' directive");
1817 /// ParseDirectiveMacrosOnOff
1820 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1821 SMLoc DirectiveLoc) {
1822 if (getLexer().isNot(AsmToken::EndOfStatement))
1823 return Error(getLexer().getLoc(),
1824 "unexpected token in '" + Directive + "' directive");
1826 getParser().MacrosEnabled = Directive == ".macros_on";
1831 /// ParseDirectiveMacro
1833 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1834 SMLoc DirectiveLoc) {
1836 if (getParser().ParseIdentifier(Name))
1837 return TokError("expected identifier in directive");
1839 if (getLexer().isNot(AsmToken::EndOfStatement))
1840 return TokError("unexpected token in '.macro' directive");
1842 // Eat the end of statement.
1845 AsmToken EndToken, StartToken = getTok();
1847 // Lex the macro definition.
1849 // Check whether we have reached the end of the file.
1850 if (getLexer().is(AsmToken::Eof))
1851 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1853 // Otherwise, check whether we have reach the .endmacro.
1854 if (getLexer().is(AsmToken::Identifier) &&
1855 (getTok().getIdentifier() == ".endm" ||
1856 getTok().getIdentifier() == ".endmacro")) {
1857 EndToken = getTok();
1859 if (getLexer().isNot(AsmToken::EndOfStatement))
1860 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1865 // Otherwise, scan til the end of the statement.
1866 getParser().EatToEndOfStatement();
1869 if (getParser().MacroMap.lookup(Name)) {
1870 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1873 const char *BodyStart = StartToken.getLoc().getPointer();
1874 const char *BodyEnd = EndToken.getLoc().getPointer();
1875 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1876 getParser().MacroMap[Name] = new Macro(Name, Body);
1880 /// ParseDirectiveEndMacro
1883 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1884 SMLoc DirectiveLoc) {
1885 if (getLexer().isNot(AsmToken::EndOfStatement))
1886 return TokError("unexpected token in '" + Directive + "' directive");
1888 // If we are inside a macro instantiation, terminate the current
1890 if (!getParser().ActiveMacros.empty()) {
1891 getParser().HandleMacroExit();
1895 // Otherwise, this .endmacro is a stray entry in the file; well formed
1896 // .endmacro directives are handled during the macro definition parsing.
1897 return TokError("unexpected '" + Directive + "' in file, "
1898 "no current macro definition");
1901 /// \brief Create an MCAsmParser instance.
1902 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1903 MCContext &C, MCStreamer &Out,
1904 const MCAsmInfo &MAI) {
1905 return new AsmParser(T, SM, C, Out, MAI);