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 // FIXME: Target hooks for IsPow2.
806 if (IDVal == ".align")
807 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
808 if (IDVal == ".align32")
809 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
810 if (IDVal == ".balign")
811 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
812 if (IDVal == ".balignw")
813 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
814 if (IDVal == ".balignl")
815 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
816 if (IDVal == ".p2align")
817 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
818 if (IDVal == ".p2alignw")
819 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
820 if (IDVal == ".p2alignl")
821 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
824 return ParseDirectiveOrg();
826 if (IDVal == ".fill")
827 return ParseDirectiveFill();
828 if (IDVal == ".space")
829 return ParseDirectiveSpace();
831 // Symbol attribute directives
833 if (IDVal == ".globl" || IDVal == ".global")
834 return ParseDirectiveSymbolAttribute(MCSA_Global);
835 if (IDVal == ".hidden")
836 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
837 if (IDVal == ".indirect_symbol")
838 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
839 if (IDVal == ".internal")
840 return ParseDirectiveSymbolAttribute(MCSA_Internal);
841 if (IDVal == ".lazy_reference")
842 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
843 if (IDVal == ".no_dead_strip")
844 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
845 if (IDVal == ".private_extern")
846 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
847 if (IDVal == ".protected")
848 return ParseDirectiveSymbolAttribute(MCSA_Protected);
849 if (IDVal == ".reference")
850 return ParseDirectiveSymbolAttribute(MCSA_Reference);
851 if (IDVal == ".type")
852 return ParseDirectiveELFType();
853 if (IDVal == ".weak")
854 return ParseDirectiveSymbolAttribute(MCSA_Weak);
855 if (IDVal == ".weak_definition")
856 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
857 if (IDVal == ".weak_reference")
858 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
859 if (IDVal == ".weak_def_can_be_hidden")
860 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
862 if (IDVal == ".comm")
863 return ParseDirectiveComm(/*IsLocal=*/false);
864 if (IDVal == ".lcomm")
865 return ParseDirectiveComm(/*IsLocal=*/true);
867 if (IDVal == ".abort")
868 return ParseDirectiveAbort();
869 if (IDVal == ".include")
870 return ParseDirectiveInclude();
872 // Look up the handler in the handler table.
873 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
874 DirectiveMap.lookup(IDVal);
876 return (*Handler.second)(Handler.first, IDVal, IDLoc);
878 // Target hook for parsing target specific directives.
879 if (!getTargetParser().ParseDirective(ID))
882 Warning(IDLoc, "ignoring directive for now");
883 EatToEndOfStatement();
887 // Canonicalize the opcode to lower case.
888 SmallString<128> Opcode;
889 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
890 Opcode.push_back(tolower(IDVal[i]));
892 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
893 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
895 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
896 HadError = TokError("unexpected token in argument list");
898 // If parsing succeeded, match the instruction.
901 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
902 // Emit the instruction on success.
903 Out.EmitInstruction(Inst);
905 // Otherwise emit a diagnostic about the match failure and set the error
908 // FIXME: We should give nicer diagnostics about the exact failure.
909 Error(IDLoc, "unrecognized instruction");
914 // If there was no error, consume the end-of-statement token. Otherwise this
915 // will be done by our caller.
919 // Free any parsed operands.
920 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
921 delete ParsedOperands[i];
926 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
927 const std::vector<std::vector<AsmToken> > &A)
928 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
930 // Macro instantiation is lexical, unfortunately. We construct a new buffer
931 // to hold the macro body with substitutions.
932 SmallString<256> Buf;
933 raw_svector_ostream OS(Buf);
935 StringRef Body = M->Body;
936 while (!Body.empty()) {
937 // Scan for the next substitution.
938 std::size_t End = Body.size(), Pos = 0;
939 for (; Pos != End; ++Pos) {
940 // Check for a substitution or escape.
941 if (Body[Pos] != '$' || Pos + 1 == End)
944 char Next = Body[Pos + 1];
945 if (Next == '$' || Next == 'n' || isdigit(Next))
950 OS << Body.slice(0, Pos);
952 // Check if we reached the end.
956 switch (Body[Pos+1]) {
962 // $n => number of arguments
967 // $[0-9] => argument
969 // Missing arguments are ignored.
970 unsigned Index = Body[Pos+1] - '0';
971 if (Index >= A.size())
974 // Otherwise substitute with the token values, with spaces eliminated.
975 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
976 ie = A[Index].end(); it != ie; ++it)
977 OS << it->getString();
982 // Update the scan point.
983 Body = Body.substr(Pos + 2);
986 // We include the .endmacro in the buffer as our queue to exit the macro
990 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
993 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
995 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
996 // this, although we should protect against infinite loops.
997 if (ActiveMacros.size() == 20)
998 return TokError("macros cannot be nested more than 20 levels deep");
1000 // Parse the macro instantiation arguments.
1001 std::vector<std::vector<AsmToken> > MacroArguments;
1002 MacroArguments.push_back(std::vector<AsmToken>());
1003 unsigned ParenLevel = 0;
1005 if (Lexer.is(AsmToken::Eof))
1006 return TokError("unexpected token in macro instantiation");
1007 if (Lexer.is(AsmToken::EndOfStatement))
1010 // If we aren't inside parentheses and this is a comma, start a new token
1012 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1013 MacroArguments.push_back(std::vector<AsmToken>());
1014 } else if (Lexer.is(AsmToken::LParen)) {
1016 } else if (Lexer.is(AsmToken::RParen)) {
1020 MacroArguments.back().push_back(getTok());
1025 // Create the macro instantiation object and add to the current macro
1026 // instantiation stack.
1027 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1030 ActiveMacros.push_back(MI);
1032 // Jump to the macro instantiation and prime the lexer.
1033 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1034 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1040 void AsmParser::HandleMacroExit() {
1041 // Jump to the EndOfStatement we should return to, and consume it.
1042 JumpToLoc(ActiveMacros.back()->ExitLoc);
1045 // Pop the instantiation entry.
1046 delete ActiveMacros.back();
1047 ActiveMacros.pop_back();
1050 bool AsmParser::ParseAssignment(StringRef Name) {
1051 // FIXME: Use better location, we should use proper tokens.
1052 SMLoc EqualLoc = Lexer.getLoc();
1054 const MCExpr *Value;
1055 if (ParseExpression(Value))
1058 if (Lexer.isNot(AsmToken::EndOfStatement))
1059 return TokError("unexpected token in assignment");
1061 // Eat the end of statement marker.
1064 // Validate that the LHS is allowed to be a variable (either it has not been
1065 // used as a symbol, or it is an absolute symbol).
1066 MCSymbol *Sym = getContext().LookupSymbol(Name);
1068 // Diagnose assignment to a label.
1070 // FIXME: Diagnostics. Note the location of the definition as a label.
1071 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1072 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1073 ; // Allow redefinitions of undefined symbols only used in directives.
1074 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1075 return Error(EqualLoc, "redefinition of '" + Name + "'");
1076 else if (!Sym->isVariable())
1077 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1078 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1079 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1082 Sym = getContext().GetOrCreateSymbol(Name);
1084 // FIXME: Handle '.'.
1086 Sym->setUsedInExpr(true);
1088 // Do the assignment.
1089 Out.EmitAssignment(Sym, Value);
1094 /// ParseIdentifier:
1097 bool AsmParser::ParseIdentifier(StringRef &Res) {
1098 if (Lexer.isNot(AsmToken::Identifier) &&
1099 Lexer.isNot(AsmToken::String))
1102 Res = getTok().getIdentifier();
1104 Lex(); // Consume the identifier token.
1109 /// ParseDirectiveSet:
1110 /// ::= .set identifier ',' expression
1111 bool AsmParser::ParseDirectiveSet() {
1114 if (ParseIdentifier(Name))
1115 return TokError("expected identifier after '.set' directive");
1117 if (getLexer().isNot(AsmToken::Comma))
1118 return TokError("unexpected token in '.set'");
1121 return ParseAssignment(Name);
1124 bool AsmParser::ParseEscapedString(std::string &Data) {
1125 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1128 StringRef Str = getTok().getStringContents();
1129 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1130 if (Str[i] != '\\') {
1135 // Recognize escaped characters. Note that this escape semantics currently
1136 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1139 return TokError("unexpected backslash at end of string");
1141 // Recognize octal sequences.
1142 if ((unsigned) (Str[i] - '0') <= 7) {
1143 // Consume up to three octal characters.
1144 unsigned Value = Str[i] - '0';
1146 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1148 Value = Value * 8 + (Str[i] - '0');
1150 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1152 Value = Value * 8 + (Str[i] - '0');
1157 return TokError("invalid octal escape sequence (out of range)");
1159 Data += (unsigned char) Value;
1163 // Otherwise recognize individual escapes.
1166 // Just reject invalid escape sequences for now.
1167 return TokError("invalid escape sequence (unrecognized character)");
1169 case 'b': Data += '\b'; break;
1170 case 'f': Data += '\f'; break;
1171 case 'n': Data += '\n'; break;
1172 case 'r': Data += '\r'; break;
1173 case 't': Data += '\t'; break;
1174 case '"': Data += '"'; break;
1175 case '\\': Data += '\\'; break;
1182 /// ParseDirectiveAscii:
1183 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1184 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1185 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1187 if (getLexer().isNot(AsmToken::String))
1188 return TokError("expected string in '.ascii' or '.asciz' directive");
1191 if (ParseEscapedString(Data))
1194 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1196 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1200 if (getLexer().is(AsmToken::EndOfStatement))
1203 if (getLexer().isNot(AsmToken::Comma))
1204 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1213 /// ParseDirectiveValue
1214 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1215 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1218 const MCExpr *Value;
1219 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1220 if (ParseExpression(Value))
1223 // Special case constant expressions to match code generator.
1224 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1225 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1227 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1229 if (getLexer().is(AsmToken::EndOfStatement))
1232 // FIXME: Improve diagnostic.
1233 if (getLexer().isNot(AsmToken::Comma))
1234 return TokError("unexpected token in directive");
1243 /// ParseDirectiveSpace
1244 /// ::= .space expression [ , expression ]
1245 bool AsmParser::ParseDirectiveSpace() {
1247 if (ParseAbsoluteExpression(NumBytes))
1250 int64_t FillExpr = 0;
1251 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1252 if (getLexer().isNot(AsmToken::Comma))
1253 return TokError("unexpected token in '.space' directive");
1256 if (ParseAbsoluteExpression(FillExpr))
1259 if (getLexer().isNot(AsmToken::EndOfStatement))
1260 return TokError("unexpected token in '.space' directive");
1266 return TokError("invalid number of bytes in '.space' directive");
1268 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1269 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1274 /// ParseDirectiveFill
1275 /// ::= .fill expression , expression , expression
1276 bool AsmParser::ParseDirectiveFill() {
1278 if (ParseAbsoluteExpression(NumValues))
1281 if (getLexer().isNot(AsmToken::Comma))
1282 return TokError("unexpected token in '.fill' directive");
1286 if (ParseAbsoluteExpression(FillSize))
1289 if (getLexer().isNot(AsmToken::Comma))
1290 return TokError("unexpected token in '.fill' directive");
1294 if (ParseAbsoluteExpression(FillExpr))
1297 if (getLexer().isNot(AsmToken::EndOfStatement))
1298 return TokError("unexpected token in '.fill' directive");
1302 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1303 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1305 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1306 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1311 /// ParseDirectiveOrg
1312 /// ::= .org expression [ , expression ]
1313 bool AsmParser::ParseDirectiveOrg() {
1314 const MCExpr *Offset;
1315 if (ParseExpression(Offset))
1318 // Parse optional fill expression.
1319 int64_t FillExpr = 0;
1320 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1321 if (getLexer().isNot(AsmToken::Comma))
1322 return TokError("unexpected token in '.org' directive");
1325 if (ParseAbsoluteExpression(FillExpr))
1328 if (getLexer().isNot(AsmToken::EndOfStatement))
1329 return TokError("unexpected token in '.org' directive");
1334 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1335 // has to be relative to the current section.
1336 getStreamer().EmitValueToOffset(Offset, FillExpr);
1341 /// ParseDirectiveAlign
1342 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1343 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1344 SMLoc AlignmentLoc = getLexer().getLoc();
1346 if (ParseAbsoluteExpression(Alignment))
1350 bool HasFillExpr = false;
1351 int64_t FillExpr = 0;
1352 int64_t MaxBytesToFill = 0;
1353 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1354 if (getLexer().isNot(AsmToken::Comma))
1355 return TokError("unexpected token in directive");
1358 // The fill expression can be omitted while specifying a maximum number of
1359 // alignment bytes, e.g:
1361 if (getLexer().isNot(AsmToken::Comma)) {
1363 if (ParseAbsoluteExpression(FillExpr))
1367 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1368 if (getLexer().isNot(AsmToken::Comma))
1369 return TokError("unexpected token in directive");
1372 MaxBytesLoc = getLexer().getLoc();
1373 if (ParseAbsoluteExpression(MaxBytesToFill))
1376 if (getLexer().isNot(AsmToken::EndOfStatement))
1377 return TokError("unexpected token in directive");
1386 // Compute alignment in bytes.
1388 // FIXME: Diagnose overflow.
1389 if (Alignment >= 32) {
1390 Error(AlignmentLoc, "invalid alignment value");
1394 Alignment = 1ULL << Alignment;
1397 // Diagnose non-sensical max bytes to align.
1398 if (MaxBytesLoc.isValid()) {
1399 if (MaxBytesToFill < 1) {
1400 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1401 "many bytes, ignoring maximum bytes expression");
1405 if (MaxBytesToFill >= Alignment) {
1406 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1412 // Check whether we should use optimal code alignment for this .align
1415 // FIXME: This should be using a target hook.
1416 bool UseCodeAlign = false;
1417 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1418 getStreamer().getCurrentSection()))
1419 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1420 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1421 ValueSize == 1 && UseCodeAlign) {
1422 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1424 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1425 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1432 /// ParseDirectiveSymbolAttribute
1433 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1434 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1435 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1439 if (ParseIdentifier(Name))
1440 return TokError("expected identifier in directive");
1442 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1444 getStreamer().EmitSymbolAttribute(Sym, Attr);
1446 if (getLexer().is(AsmToken::EndOfStatement))
1449 if (getLexer().isNot(AsmToken::Comma))
1450 return TokError("unexpected token in directive");
1459 /// ParseDirectiveELFType
1460 /// ::= .type identifier , @attribute
1461 bool AsmParser::ParseDirectiveELFType() {
1463 if (ParseIdentifier(Name))
1464 return TokError("expected identifier in directive");
1466 // Handle the identifier as the key symbol.
1467 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1469 if (getLexer().isNot(AsmToken::Comma))
1470 return TokError("unexpected token in '.type' directive");
1473 if (getLexer().isNot(AsmToken::At))
1474 return TokError("expected '@' before type");
1480 TypeLoc = getLexer().getLoc();
1481 if (ParseIdentifier(Type))
1482 return TokError("expected symbol type in directive");
1484 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1485 .Case("function", MCSA_ELF_TypeFunction)
1486 .Case("object", MCSA_ELF_TypeObject)
1487 .Case("tls_object", MCSA_ELF_TypeTLS)
1488 .Case("common", MCSA_ELF_TypeCommon)
1489 .Case("notype", MCSA_ELF_TypeNoType)
1490 .Default(MCSA_Invalid);
1492 if (Attr == MCSA_Invalid)
1493 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1495 if (getLexer().isNot(AsmToken::EndOfStatement))
1496 return TokError("unexpected token in '.type' directive");
1500 getStreamer().EmitSymbolAttribute(Sym, Attr);
1505 /// ParseDirectiveComm
1506 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1507 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1508 SMLoc IDLoc = getLexer().getLoc();
1510 if (ParseIdentifier(Name))
1511 return TokError("expected identifier in directive");
1513 // Handle the identifier as the key symbol.
1514 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1516 if (getLexer().isNot(AsmToken::Comma))
1517 return TokError("unexpected token in directive");
1521 SMLoc SizeLoc = getLexer().getLoc();
1522 if (ParseAbsoluteExpression(Size))
1525 int64_t Pow2Alignment = 0;
1526 SMLoc Pow2AlignmentLoc;
1527 if (getLexer().is(AsmToken::Comma)) {
1529 Pow2AlignmentLoc = getLexer().getLoc();
1530 if (ParseAbsoluteExpression(Pow2Alignment))
1533 // If this target takes alignments in bytes (not log) validate and convert.
1534 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1535 if (!isPowerOf2_64(Pow2Alignment))
1536 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1537 Pow2Alignment = Log2_64(Pow2Alignment);
1541 if (getLexer().isNot(AsmToken::EndOfStatement))
1542 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1546 // NOTE: a size of zero for a .comm should create a undefined symbol
1547 // but a size of .lcomm creates a bss symbol of size zero.
1549 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1550 "be less than zero");
1552 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1553 // may internally end up wanting an alignment in bytes.
1554 // FIXME: Diagnose overflow.
1555 if (Pow2Alignment < 0)
1556 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1557 "alignment, can't be less than zero");
1559 if (!Sym->isUndefined())
1560 return Error(IDLoc, "invalid symbol redefinition");
1562 // '.lcomm' is equivalent to '.zerofill'.
1563 // Create the Symbol as a common or local common with Size and Pow2Alignment
1565 getStreamer().EmitZerofill(Ctx.getMachOSection(
1566 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1567 0, SectionKind::getBSS()),
1568 Sym, Size, 1 << Pow2Alignment);
1572 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1576 /// ParseDirectiveAbort
1577 /// ::= .abort [... message ...]
1578 bool AsmParser::ParseDirectiveAbort() {
1579 // FIXME: Use loc from directive.
1580 SMLoc Loc = getLexer().getLoc();
1582 StringRef Str = ParseStringToEndOfStatement();
1583 if (getLexer().isNot(AsmToken::EndOfStatement))
1584 return TokError("unexpected token in '.abort' directive");
1589 Error(Loc, ".abort detected. Assembly stopping.");
1591 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1592 // FIXME: Actually abort assembly here.
1597 /// ParseDirectiveInclude
1598 /// ::= .include "filename"
1599 bool AsmParser::ParseDirectiveInclude() {
1600 if (getLexer().isNot(AsmToken::String))
1601 return TokError("expected string in '.include' directive");
1603 std::string Filename = getTok().getString();
1604 SMLoc IncludeLoc = getLexer().getLoc();
1607 if (getLexer().isNot(AsmToken::EndOfStatement))
1608 return TokError("unexpected token in '.include' directive");
1610 // Strip the quotes.
1611 Filename = Filename.substr(1, Filename.size()-2);
1613 // Attempt to switch the lexer to the included file before consuming the end
1614 // of statement to avoid losing it when we switch.
1615 if (EnterIncludeFile(Filename)) {
1616 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1623 /// ParseDirectiveIf
1624 /// ::= .if expression
1625 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1626 TheCondStack.push_back(TheCondState);
1627 TheCondState.TheCond = AsmCond::IfCond;
1628 if(TheCondState.Ignore) {
1629 EatToEndOfStatement();
1633 if (ParseAbsoluteExpression(ExprValue))
1636 if (getLexer().isNot(AsmToken::EndOfStatement))
1637 return TokError("unexpected token in '.if' directive");
1641 TheCondState.CondMet = ExprValue;
1642 TheCondState.Ignore = !TheCondState.CondMet;
1648 /// ParseDirectiveElseIf
1649 /// ::= .elseif expression
1650 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1651 if (TheCondState.TheCond != AsmCond::IfCond &&
1652 TheCondState.TheCond != AsmCond::ElseIfCond)
1653 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1655 TheCondState.TheCond = AsmCond::ElseIfCond;
1657 bool LastIgnoreState = false;
1658 if (!TheCondStack.empty())
1659 LastIgnoreState = TheCondStack.back().Ignore;
1660 if (LastIgnoreState || TheCondState.CondMet) {
1661 TheCondState.Ignore = true;
1662 EatToEndOfStatement();
1666 if (ParseAbsoluteExpression(ExprValue))
1669 if (getLexer().isNot(AsmToken::EndOfStatement))
1670 return TokError("unexpected token in '.elseif' directive");
1673 TheCondState.CondMet = ExprValue;
1674 TheCondState.Ignore = !TheCondState.CondMet;
1680 /// ParseDirectiveElse
1682 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1683 if (getLexer().isNot(AsmToken::EndOfStatement))
1684 return TokError("unexpected token in '.else' directive");
1688 if (TheCondState.TheCond != AsmCond::IfCond &&
1689 TheCondState.TheCond != AsmCond::ElseIfCond)
1690 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1692 TheCondState.TheCond = AsmCond::ElseCond;
1693 bool LastIgnoreState = false;
1694 if (!TheCondStack.empty())
1695 LastIgnoreState = TheCondStack.back().Ignore;
1696 if (LastIgnoreState || TheCondState.CondMet)
1697 TheCondState.Ignore = true;
1699 TheCondState.Ignore = false;
1704 /// ParseDirectiveEndIf
1706 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1707 if (getLexer().isNot(AsmToken::EndOfStatement))
1708 return TokError("unexpected token in '.endif' directive");
1712 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1713 TheCondStack.empty())
1714 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1716 if (!TheCondStack.empty()) {
1717 TheCondState = TheCondStack.back();
1718 TheCondStack.pop_back();
1724 /// ParseDirectiveFile
1725 /// ::= .file [number] string
1726 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1727 // FIXME: I'm not sure what this is.
1728 int64_t FileNumber = -1;
1729 if (getLexer().is(AsmToken::Integer)) {
1730 FileNumber = getTok().getIntVal();
1734 return TokError("file number less than one");
1737 if (getLexer().isNot(AsmToken::String))
1738 return TokError("unexpected token in '.file' directive");
1740 StringRef Filename = getTok().getString();
1741 Filename = Filename.substr(1, Filename.size()-2);
1744 if (getLexer().isNot(AsmToken::EndOfStatement))
1745 return TokError("unexpected token in '.file' directive");
1747 if (FileNumber == -1)
1748 getStreamer().EmitFileDirective(Filename);
1750 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1755 /// ParseDirectiveLine
1756 /// ::= .line [number]
1757 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1758 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1759 if (getLexer().isNot(AsmToken::Integer))
1760 return TokError("unexpected token in '.line' directive");
1762 int64_t LineNumber = getTok().getIntVal();
1766 // FIXME: Do something with the .line.
1769 if (getLexer().isNot(AsmToken::EndOfStatement))
1770 return TokError("unexpected token in '.line' directive");
1776 /// ParseDirectiveLoc
1777 /// ::= .loc number [number [number]]
1778 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1779 if (getLexer().isNot(AsmToken::Integer))
1780 return TokError("unexpected token in '.loc' directive");
1782 // FIXME: What are these fields?
1783 int64_t FileNumber = getTok().getIntVal();
1785 // FIXME: Validate file.
1788 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1789 if (getLexer().isNot(AsmToken::Integer))
1790 return TokError("unexpected token in '.loc' directive");
1792 int64_t Param2 = getTok().getIntVal();
1796 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1797 if (getLexer().isNot(AsmToken::Integer))
1798 return TokError("unexpected token in '.loc' directive");
1800 int64_t Param3 = getTok().getIntVal();
1804 // FIXME: Do something with the .loc.
1808 if (getLexer().isNot(AsmToken::EndOfStatement))
1809 return TokError("unexpected token in '.file' directive");
1814 /// ParseDirectiveMacrosOnOff
1817 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1818 SMLoc DirectiveLoc) {
1819 if (getLexer().isNot(AsmToken::EndOfStatement))
1820 return Error(getLexer().getLoc(),
1821 "unexpected token in '" + Directive + "' directive");
1823 getParser().MacrosEnabled = Directive == ".macros_on";
1828 /// ParseDirectiveMacro
1830 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1831 SMLoc DirectiveLoc) {
1833 if (getParser().ParseIdentifier(Name))
1834 return TokError("expected identifier in directive");
1836 if (getLexer().isNot(AsmToken::EndOfStatement))
1837 return TokError("unexpected token in '.macro' directive");
1839 // Eat the end of statement.
1842 AsmToken EndToken, StartToken = getTok();
1844 // Lex the macro definition.
1846 // Check whether we have reached the end of the file.
1847 if (getLexer().is(AsmToken::Eof))
1848 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1850 // Otherwise, check whether we have reach the .endmacro.
1851 if (getLexer().is(AsmToken::Identifier) &&
1852 (getTok().getIdentifier() == ".endm" ||
1853 getTok().getIdentifier() == ".endmacro")) {
1854 EndToken = getTok();
1856 if (getLexer().isNot(AsmToken::EndOfStatement))
1857 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1862 // Otherwise, scan til the end of the statement.
1863 getParser().EatToEndOfStatement();
1866 if (getParser().MacroMap.lookup(Name)) {
1867 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1870 const char *BodyStart = StartToken.getLoc().getPointer();
1871 const char *BodyEnd = EndToken.getLoc().getPointer();
1872 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1873 getParser().MacroMap[Name] = new Macro(Name, Body);
1877 /// ParseDirectiveEndMacro
1880 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1881 SMLoc DirectiveLoc) {
1882 if (getLexer().isNot(AsmToken::EndOfStatement))
1883 return TokError("unexpected token in '" + Directive + "' directive");
1885 // If we are inside a macro instantiation, terminate the current
1887 if (!getParser().ActiveMacros.empty()) {
1888 getParser().HandleMacroExit();
1892 // Otherwise, this .endmacro is a stray entry in the file; well formed
1893 // .endmacro directives are handled during the macro definition parsing.
1894 return TokError("unexpected '" + Directive + "' in file, "
1895 "no current macro definition");
1898 /// \brief Create an MCAsmParser instance.
1899 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1900 MCContext &C, MCStreamer &Out,
1901 const MCAsmInfo &MAI) {
1902 return new AsmParser(T, SM, C, Out, MAI);