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/MC/MCDwarf.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmParser.h"
40 /// \brief Helper class for tracking macro definitions.
46 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
49 /// \brief Helper class for storing information about an active macro
51 struct MacroInstantiation {
52 /// The macro being instantiated.
53 const Macro *TheMacro;
55 /// The macro instantiation with substitutions.
56 MemoryBuffer *Instantiation;
58 /// The location of the instantiation.
59 SMLoc InstantiationLoc;
61 /// The location where parsing should resume upon instantiation completion.
65 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
66 const std::vector<std::vector<AsmToken> > &A);
69 /// \brief The concrete assembly parser instance.
70 class AsmParser : public MCAsmParser {
71 friend class GenericAsmParser;
73 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
74 void operator=(const AsmParser &); // DO NOT IMPLEMENT
80 MCAsmParserExtension *GenericParser;
81 MCAsmParserExtension *PlatformParser;
83 /// This is the current buffer index we're lexing from as managed by the
88 std::vector<AsmCond> TheCondStack;
90 /// DirectiveMap - This is a table handlers for directives. Each handler is
91 /// invoked after the directive identifier is read and is responsible for
92 /// parsing and validating the rest of the directive. The handler is passed
93 /// in the directive name and the location of the directive keyword.
94 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
96 /// MacroMap - Map of currently defined macros.
97 StringMap<Macro*> MacroMap;
99 /// ActiveMacros - Stack of active macro instantiations.
100 std::vector<MacroInstantiation*> ActiveMacros;
102 /// Boolean tracking whether macro substitution is enabled.
103 unsigned MacrosEnabled : 1;
106 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
107 const MCAsmInfo &MAI);
110 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
112 void AddDirectiveHandler(MCAsmParserExtension *Object,
114 DirectiveHandler Handler) {
115 DirectiveMap[Directive] = std::make_pair(Object, Handler);
119 /// @name MCAsmParser Interface
122 virtual SourceMgr &getSourceManager() { return SrcMgr; }
123 virtual MCAsmLexer &getLexer() { return Lexer; }
124 virtual MCContext &getContext() { return Ctx; }
125 virtual MCStreamer &getStreamer() { return Out; }
127 virtual void Warning(SMLoc L, const Twine &Meg);
128 virtual bool Error(SMLoc L, const Twine &Msg);
130 const AsmToken &Lex();
132 bool ParseExpression(const MCExpr *&Res);
133 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
134 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
135 virtual bool ParseAbsoluteExpression(int64_t &Res);
140 bool ParseStatement();
142 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
143 void HandleMacroExit();
145 void PrintMacroInstantiations();
146 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
148 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
149 bool EnterIncludeFile(const std::string &Filename);
151 /// \brief Reset the current lexer position to that given by \arg Loc. The
152 /// current token is not set; clients should ensure Lex() is called
154 void JumpToLoc(SMLoc Loc);
156 void EatToEndOfStatement();
158 /// \brief Parse up to the end of statement and a return the contents from the
159 /// current token until the end of the statement; the current token on exit
160 /// will be either the EndOfStatement or EOF.
161 StringRef ParseStringToEndOfStatement();
163 bool ParseAssignment(StringRef Name);
165 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
166 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
167 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
169 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
170 /// and set \arg Res to the identifier contents.
171 bool ParseIdentifier(StringRef &Res);
173 // Directive Parsing.
174 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
175 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
176 bool ParseDirectiveFill(); // ".fill"
177 bool ParseDirectiveSpace(); // ".space"
178 bool ParseDirectiveSet(); // ".set"
179 bool ParseDirectiveOrg(); // ".org"
180 // ".align{,32}", ".p2align{,w,l}"
181 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
183 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
184 /// accepts a single symbol (which should be a label or an external).
185 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
186 bool ParseDirectiveELFType(); // ELF specific ".type"
188 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
190 bool ParseDirectiveAbort(); // ".abort"
191 bool ParseDirectiveInclude(); // ".include"
193 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
194 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
195 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
196 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
198 /// ParseEscapedString - Parse the current token as a string which may include
199 /// escaped characters and return the string contents.
200 bool ParseEscapedString(std::string &Data);
203 /// \brief Generic implementations of directive handling, etc. which is shared
204 /// (or the default, at least) for all assembler parser.
205 class GenericAsmParser : public MCAsmParserExtension {
206 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
207 void AddDirectiveHandler(StringRef Directive) {
208 getParser().AddDirectiveHandler(this, Directive,
209 HandleDirective<GenericAsmParser, Handler>);
213 GenericAsmParser() {}
215 AsmParser &getParser() {
216 return (AsmParser&) this->MCAsmParserExtension::getParser();
219 virtual void Initialize(MCAsmParser &Parser) {
220 // Call the base implementation.
221 this->MCAsmParserExtension::Initialize(Parser);
223 // Debugging directives.
224 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
225 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
226 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
229 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
231 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
233 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
238 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
239 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
240 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
242 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
243 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
244 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
251 extern MCAsmParserExtension *createDarwinAsmParser();
252 extern MCAsmParserExtension *createELFAsmParser();
256 enum { DEFAULT_ADDRSPACE = 0 };
258 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
259 MCStreamer &_Out, const MCAsmInfo &_MAI)
260 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
261 GenericParser(new GenericAsmParser), PlatformParser(0),
262 CurBuffer(0), MacrosEnabled(true) {
263 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
265 // Initialize the generic parser.
266 GenericParser->Initialize(*this);
268 // Initialize the platform / file format parser.
270 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
272 if (_MAI.hasSubsectionsViaSymbols()) {
273 PlatformParser = createDarwinAsmParser();
274 PlatformParser->Initialize(*this);
276 PlatformParser = createELFAsmParser();
277 PlatformParser->Initialize(*this);
281 AsmParser::~AsmParser() {
282 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
284 // Destroy any macros.
285 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
286 ie = MacroMap.end(); it != ie; ++it)
287 delete it->getValue();
289 delete PlatformParser;
290 delete GenericParser;
293 void AsmParser::PrintMacroInstantiations() {
294 // Print the active macro instantiation stack.
295 for (std::vector<MacroInstantiation*>::const_reverse_iterator
296 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
297 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
301 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
302 PrintMessage(L, Msg.str(), "warning");
303 PrintMacroInstantiations();
306 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
307 PrintMessage(L, Msg.str(), "error");
308 PrintMacroInstantiations();
312 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
313 const char *Type) const {
314 SrcMgr.PrintMessage(Loc, Msg, Type);
317 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
318 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
324 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
329 void AsmParser::JumpToLoc(SMLoc Loc) {
330 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
331 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
334 const AsmToken &AsmParser::Lex() {
335 const AsmToken *tok = &Lexer.Lex();
337 if (tok->is(AsmToken::Eof)) {
338 // If this is the end of an included file, pop the parent file off the
340 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
341 if (ParentIncludeLoc != SMLoc()) {
342 JumpToLoc(ParentIncludeLoc);
347 if (tok->is(AsmToken::Error))
348 Error(Lexer.getErrLoc(), Lexer.getErr());
353 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
354 // Create the initial section, if requested.
356 // FIXME: Target hook & command line option for initial section.
357 if (!NoInitialTextSection)
358 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
359 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
360 0, SectionKind::getText()));
365 bool HadError = false;
367 AsmCond StartingCondState = TheCondState;
369 // While we have input, parse each statement.
370 while (Lexer.isNot(AsmToken::Eof)) {
371 if (!ParseStatement()) continue;
373 // We had an error, remember it and recover by skipping to the next line.
375 EatToEndOfStatement();
378 if (TheCondState.TheCond != StartingCondState.TheCond ||
379 TheCondState.Ignore != StartingCondState.Ignore)
380 return TokError("unmatched .ifs or .elses");
382 // Check to see there are no empty DwarfFile slots.
383 const std::vector<MCDwarfFile *> &MCDwarfFiles =
384 getContext().getMCDwarfFiles();
385 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
386 if (!MCDwarfFiles[i]){
387 TokError("unassigned file number: " + Twine(i) + " for .file directives");
392 // Finalize the output stream if there are no errors and if the client wants
394 if (!HadError && !NoFinalize)
400 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
401 void AsmParser::EatToEndOfStatement() {
402 while (Lexer.isNot(AsmToken::EndOfStatement) &&
403 Lexer.isNot(AsmToken::Eof))
407 if (Lexer.is(AsmToken::EndOfStatement))
411 StringRef AsmParser::ParseStringToEndOfStatement() {
412 const char *Start = getTok().getLoc().getPointer();
414 while (Lexer.isNot(AsmToken::EndOfStatement) &&
415 Lexer.isNot(AsmToken::Eof))
418 const char *End = getTok().getLoc().getPointer();
419 return StringRef(Start, End - Start);
422 /// ParseParenExpr - Parse a paren expression and return it.
423 /// NOTE: This assumes the leading '(' has already been consumed.
425 /// parenexpr ::= expr)
427 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
428 if (ParseExpression(Res)) return true;
429 if (Lexer.isNot(AsmToken::RParen))
430 return TokError("expected ')' in parentheses expression");
431 EndLoc = Lexer.getLoc();
436 /// ParsePrimaryExpr - Parse a primary expression and return it.
437 /// primaryexpr ::= (parenexpr
438 /// primaryexpr ::= symbol
439 /// primaryexpr ::= number
440 /// primaryexpr ::= '.'
441 /// primaryexpr ::= ~,+,- primaryexpr
442 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
443 switch (Lexer.getKind()) {
445 return TokError("unknown token in expression");
446 case AsmToken::Exclaim:
447 Lex(); // Eat the operator.
448 if (ParsePrimaryExpr(Res, EndLoc))
450 Res = MCUnaryExpr::CreateLNot(Res, getContext());
452 case AsmToken::String:
453 case AsmToken::Identifier: {
454 // This is a symbol reference.
455 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
456 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
458 // Mark the symbol as used in an expression.
459 Sym->setUsedInExpr(true);
461 // Lookup the symbol variant if used.
462 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
463 if (Split.first.size() != getTok().getIdentifier().size())
464 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
466 EndLoc = Lexer.getLoc();
467 Lex(); // Eat identifier.
469 // If this is an absolute variable reference, substitute it now to preserve
470 // semantics in the face of reassignment.
471 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
473 return Error(EndLoc, "unexpected modified on variable reference");
475 Res = Sym->getVariableValue();
479 // Otherwise create a symbol ref.
480 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
483 case AsmToken::Integer: {
484 SMLoc Loc = getTok().getLoc();
485 int64_t IntVal = getTok().getIntVal();
486 Res = MCConstantExpr::Create(IntVal, getContext());
487 EndLoc = Lexer.getLoc();
489 // Look for 'b' or 'f' following an Integer as a directional label
490 if (Lexer.getKind() == AsmToken::Identifier) {
491 StringRef IDVal = getTok().getString();
492 if (IDVal == "f" || IDVal == "b"){
493 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
494 IDVal == "f" ? 1 : 0);
495 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
497 if(IDVal == "b" && Sym->isUndefined())
498 return Error(Loc, "invalid reference to undefined symbol");
499 EndLoc = Lexer.getLoc();
500 Lex(); // Eat identifier.
505 case AsmToken::Dot: {
506 // This is a '.' reference, which references the current PC. Emit a
507 // temporary label to the streamer and refer to it.
508 MCSymbol *Sym = Ctx.CreateTempSymbol();
510 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
511 EndLoc = Lexer.getLoc();
512 Lex(); // Eat identifier.
516 case AsmToken::LParen:
517 Lex(); // Eat the '('.
518 return ParseParenExpr(Res, EndLoc);
519 case AsmToken::Minus:
520 Lex(); // Eat the operator.
521 if (ParsePrimaryExpr(Res, EndLoc))
523 Res = MCUnaryExpr::CreateMinus(Res, getContext());
526 Lex(); // Eat the operator.
527 if (ParsePrimaryExpr(Res, EndLoc))
529 Res = MCUnaryExpr::CreatePlus(Res, getContext());
531 case AsmToken::Tilde:
532 Lex(); // Eat the operator.
533 if (ParsePrimaryExpr(Res, EndLoc))
535 Res = MCUnaryExpr::CreateNot(Res, getContext());
540 bool AsmParser::ParseExpression(const MCExpr *&Res) {
542 return ParseExpression(Res, EndLoc);
545 /// ParseExpression - Parse an expression and return it.
547 /// expr ::= expr +,- expr -> lowest.
548 /// expr ::= expr |,^,&,! expr -> middle.
549 /// expr ::= expr *,/,%,<<,>> expr -> highest.
550 /// expr ::= primaryexpr
552 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
553 // Parse the expression.
555 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
558 // Try to constant fold it up front, if possible.
560 if (Res->EvaluateAsAbsolute(Value))
561 Res = MCConstantExpr::Create(Value, getContext());
566 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
568 return ParseParenExpr(Res, EndLoc) ||
569 ParseBinOpRHS(1, Res, EndLoc);
572 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
575 SMLoc StartLoc = Lexer.getLoc();
576 if (ParseExpression(Expr))
579 if (!Expr->EvaluateAsAbsolute(Res))
580 return Error(StartLoc, "expected absolute expression");
585 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
586 MCBinaryExpr::Opcode &Kind) {
589 return 0; // not a binop.
591 // Lowest Precedence: &&, ||
592 case AsmToken::AmpAmp:
593 Kind = MCBinaryExpr::LAnd;
595 case AsmToken::PipePipe:
596 Kind = MCBinaryExpr::LOr;
599 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
601 Kind = MCBinaryExpr::Add;
603 case AsmToken::Minus:
604 Kind = MCBinaryExpr::Sub;
606 case AsmToken::EqualEqual:
607 Kind = MCBinaryExpr::EQ;
609 case AsmToken::ExclaimEqual:
610 case AsmToken::LessGreater:
611 Kind = MCBinaryExpr::NE;
614 Kind = MCBinaryExpr::LT;
616 case AsmToken::LessEqual:
617 Kind = MCBinaryExpr::LTE;
619 case AsmToken::Greater:
620 Kind = MCBinaryExpr::GT;
622 case AsmToken::GreaterEqual:
623 Kind = MCBinaryExpr::GTE;
626 // Intermediate Precedence: |, &, ^
628 // FIXME: gas seems to support '!' as an infix operator?
630 Kind = MCBinaryExpr::Or;
632 case AsmToken::Caret:
633 Kind = MCBinaryExpr::Xor;
636 Kind = MCBinaryExpr::And;
639 // Highest Precedence: *, /, %, <<, >>
641 Kind = MCBinaryExpr::Mul;
643 case AsmToken::Slash:
644 Kind = MCBinaryExpr::Div;
646 case AsmToken::Percent:
647 Kind = MCBinaryExpr::Mod;
649 case AsmToken::LessLess:
650 Kind = MCBinaryExpr::Shl;
652 case AsmToken::GreaterGreater:
653 Kind = MCBinaryExpr::Shr;
659 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
660 /// Res contains the LHS of the expression on input.
661 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
664 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
665 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
667 // If the next token is lower precedence than we are allowed to eat, return
668 // successfully with what we ate already.
669 if (TokPrec < Precedence)
674 // Eat the next primary expression.
676 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
678 // If BinOp binds less tightly with RHS than the operator after RHS, let
679 // the pending operator take RHS as its LHS.
680 MCBinaryExpr::Opcode Dummy;
681 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
682 if (TokPrec < NextTokPrec) {
683 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
686 // Merge LHS and RHS according to operator.
687 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
695 /// ::= EndOfStatement
696 /// ::= Label* Directive ...Operands... EndOfStatement
697 /// ::= Label* Identifier OperandList* EndOfStatement
698 bool AsmParser::ParseStatement() {
699 if (Lexer.is(AsmToken::EndOfStatement)) {
705 // Statements always start with an identifier.
706 AsmToken ID = getTok();
707 SMLoc IDLoc = ID.getLoc();
709 int64_t LocalLabelVal = -1;
710 // GUESS allow an integer followed by a ':' as a directional local label
711 if (Lexer.is(AsmToken::Integer)) {
712 LocalLabelVal = getTok().getIntVal();
713 if (LocalLabelVal < 0) {
714 if (!TheCondState.Ignore)
715 return TokError("unexpected token at start of statement");
719 IDVal = getTok().getString();
720 Lex(); // Consume the integer token to be used as an identifier token.
721 if (Lexer.getKind() != AsmToken::Colon) {
722 if (!TheCondState.Ignore)
723 return TokError("unexpected token at start of statement");
727 else if (ParseIdentifier(IDVal)) {
728 if (!TheCondState.Ignore)
729 return TokError("unexpected token at start of statement");
733 // Handle conditional assembly here before checking for skipping. We
734 // have to do this so that .endif isn't skipped in a ".if 0" block for
737 return ParseDirectiveIf(IDLoc);
738 if (IDVal == ".elseif")
739 return ParseDirectiveElseIf(IDLoc);
740 if (IDVal == ".else")
741 return ParseDirectiveElse(IDLoc);
742 if (IDVal == ".endif")
743 return ParseDirectiveEndIf(IDLoc);
745 // If we are in a ".if 0" block, ignore this statement.
746 if (TheCondState.Ignore) {
747 EatToEndOfStatement();
751 // FIXME: Recurse on local labels?
753 // See what kind of statement we have.
754 switch (Lexer.getKind()) {
755 case AsmToken::Colon: {
756 // identifier ':' -> Label.
759 // Diagnose attempt to use a variable as a label.
761 // FIXME: Diagnostics. Note the location of the definition as a label.
762 // FIXME: This doesn't diagnose assignment to a symbol which has been
763 // implicitly marked as external.
765 if (LocalLabelVal == -1)
766 Sym = getContext().GetOrCreateSymbol(IDVal);
768 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
769 if (!Sym->isUndefined() || Sym->isVariable())
770 return Error(IDLoc, "invalid symbol redefinition");
775 // Consume any end of statement token, if present, to avoid spurious
776 // AddBlankLine calls().
777 if (Lexer.is(AsmToken::EndOfStatement)) {
779 if (Lexer.is(AsmToken::Eof))
783 return ParseStatement();
786 case AsmToken::Equal:
787 // identifier '=' ... -> assignment statement
790 return ParseAssignment(IDVal);
792 default: // Normal instruction or directive.
796 // If macros are enabled, check to see if this is a macro instantiation.
798 if (const Macro *M = MacroMap.lookup(IDVal))
799 return HandleMacroEntry(IDVal, IDLoc, M);
801 // Otherwise, we have a normal instruction or directive.
802 if (IDVal[0] == '.') {
803 // Assembler features
805 return ParseDirectiveSet();
809 if (IDVal == ".ascii")
810 return ParseDirectiveAscii(false);
811 if (IDVal == ".asciz")
812 return ParseDirectiveAscii(true);
814 if (IDVal == ".byte")
815 return ParseDirectiveValue(1);
816 if (IDVal == ".short")
817 return ParseDirectiveValue(2);
818 if (IDVal == ".long")
819 return ParseDirectiveValue(4);
820 if (IDVal == ".quad")
821 return ParseDirectiveValue(8);
823 if (IDVal == ".align") {
824 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
825 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
827 if (IDVal == ".align32") {
828 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
829 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
831 if (IDVal == ".balign")
832 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
833 if (IDVal == ".balignw")
834 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
835 if (IDVal == ".balignl")
836 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
837 if (IDVal == ".p2align")
838 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
839 if (IDVal == ".p2alignw")
840 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
841 if (IDVal == ".p2alignl")
842 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
845 return ParseDirectiveOrg();
847 if (IDVal == ".fill")
848 return ParseDirectiveFill();
849 if (IDVal == ".space")
850 return ParseDirectiveSpace();
852 // Symbol attribute directives
854 if (IDVal == ".globl" || IDVal == ".global")
855 return ParseDirectiveSymbolAttribute(MCSA_Global);
856 if (IDVal == ".hidden")
857 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
858 if (IDVal == ".indirect_symbol")
859 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
860 if (IDVal == ".internal")
861 return ParseDirectiveSymbolAttribute(MCSA_Internal);
862 if (IDVal == ".lazy_reference")
863 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
864 if (IDVal == ".no_dead_strip")
865 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
866 if (IDVal == ".private_extern")
867 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
868 if (IDVal == ".protected")
869 return ParseDirectiveSymbolAttribute(MCSA_Protected);
870 if (IDVal == ".reference")
871 return ParseDirectiveSymbolAttribute(MCSA_Reference);
872 if (IDVal == ".type")
873 return ParseDirectiveELFType();
874 if (IDVal == ".weak")
875 return ParseDirectiveSymbolAttribute(MCSA_Weak);
876 if (IDVal == ".weak_definition")
877 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
878 if (IDVal == ".weak_reference")
879 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
880 if (IDVal == ".weak_def_can_be_hidden")
881 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
883 if (IDVal == ".comm")
884 return ParseDirectiveComm(/*IsLocal=*/false);
885 if (IDVal == ".lcomm")
886 return ParseDirectiveComm(/*IsLocal=*/true);
888 if (IDVal == ".abort")
889 return ParseDirectiveAbort();
890 if (IDVal == ".include")
891 return ParseDirectiveInclude();
893 // Look up the handler in the handler table.
894 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
895 DirectiveMap.lookup(IDVal);
897 return (*Handler.second)(Handler.first, IDVal, IDLoc);
899 // Target hook for parsing target specific directives.
900 if (!getTargetParser().ParseDirective(ID))
903 Warning(IDLoc, "ignoring directive for now");
904 EatToEndOfStatement();
908 // Canonicalize the opcode to lower case.
909 SmallString<128> Opcode;
910 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
911 Opcode.push_back(tolower(IDVal[i]));
913 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
914 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
916 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
917 HadError = TokError("unexpected token in argument list");
919 // Dump the parsed representation, if requested.
920 if (getShowParsedOperands()) {
921 SmallString<256> Str;
922 raw_svector_ostream OS(Str);
923 OS << "parsed instruction: [";
924 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
927 ParsedOperands[i]->dump(OS);
931 PrintMessage(IDLoc, OS.str(), "note");
934 // If parsing succeeded, match the instruction.
937 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
938 // Emit the instruction on success.
939 Out.EmitInstruction(Inst);
944 // If there was no error, consume the end-of-statement token. Otherwise this
945 // will be done by our caller.
949 // Free any parsed operands.
950 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
951 delete ParsedOperands[i];
956 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
957 const std::vector<std::vector<AsmToken> > &A)
958 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
960 // Macro instantiation is lexical, unfortunately. We construct a new buffer
961 // to hold the macro body with substitutions.
962 SmallString<256> Buf;
963 raw_svector_ostream OS(Buf);
965 StringRef Body = M->Body;
966 while (!Body.empty()) {
967 // Scan for the next substitution.
968 std::size_t End = Body.size(), Pos = 0;
969 for (; Pos != End; ++Pos) {
970 // Check for a substitution or escape.
971 if (Body[Pos] != '$' || Pos + 1 == End)
974 char Next = Body[Pos + 1];
975 if (Next == '$' || Next == 'n' || isdigit(Next))
980 OS << Body.slice(0, Pos);
982 // Check if we reached the end.
986 switch (Body[Pos+1]) {
992 // $n => number of arguments
997 // $[0-9] => argument
999 // Missing arguments are ignored.
1000 unsigned Index = Body[Pos+1] - '0';
1001 if (Index >= A.size())
1004 // Otherwise substitute with the token values, with spaces eliminated.
1005 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1006 ie = A[Index].end(); it != ie; ++it)
1007 OS << it->getString();
1012 // Update the scan point.
1013 Body = Body.substr(Pos + 2);
1016 // We include the .endmacro in the buffer as our queue to exit the macro
1018 OS << ".endmacro\n";
1020 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1023 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1025 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1026 // this, although we should protect against infinite loops.
1027 if (ActiveMacros.size() == 20)
1028 return TokError("macros cannot be nested more than 20 levels deep");
1030 // Parse the macro instantiation arguments.
1031 std::vector<std::vector<AsmToken> > MacroArguments;
1032 MacroArguments.push_back(std::vector<AsmToken>());
1033 unsigned ParenLevel = 0;
1035 if (Lexer.is(AsmToken::Eof))
1036 return TokError("unexpected token in macro instantiation");
1037 if (Lexer.is(AsmToken::EndOfStatement))
1040 // If we aren't inside parentheses and this is a comma, start a new token
1042 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1043 MacroArguments.push_back(std::vector<AsmToken>());
1045 // Adjust the current parentheses level.
1046 if (Lexer.is(AsmToken::LParen))
1048 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1051 // Append the token to the current argument list.
1052 MacroArguments.back().push_back(getTok());
1057 // Create the macro instantiation object and add to the current macro
1058 // instantiation stack.
1059 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1062 ActiveMacros.push_back(MI);
1064 // Jump to the macro instantiation and prime the lexer.
1065 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1066 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1072 void AsmParser::HandleMacroExit() {
1073 // Jump to the EndOfStatement we should return to, and consume it.
1074 JumpToLoc(ActiveMacros.back()->ExitLoc);
1077 // Pop the instantiation entry.
1078 delete ActiveMacros.back();
1079 ActiveMacros.pop_back();
1082 bool AsmParser::ParseAssignment(StringRef Name) {
1083 // FIXME: Use better location, we should use proper tokens.
1084 SMLoc EqualLoc = Lexer.getLoc();
1086 const MCExpr *Value;
1087 if (ParseExpression(Value))
1090 if (Lexer.isNot(AsmToken::EndOfStatement))
1091 return TokError("unexpected token in assignment");
1093 // Eat the end of statement marker.
1096 // Validate that the LHS is allowed to be a variable (either it has not been
1097 // used as a symbol, or it is an absolute symbol).
1098 MCSymbol *Sym = getContext().LookupSymbol(Name);
1100 // Diagnose assignment to a label.
1102 // FIXME: Diagnostics. Note the location of the definition as a label.
1103 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1104 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1105 ; // Allow redefinitions of undefined symbols only used in directives.
1106 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1107 return Error(EqualLoc, "redefinition of '" + Name + "'");
1108 else if (!Sym->isVariable())
1109 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1110 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1111 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1114 Sym = getContext().GetOrCreateSymbol(Name);
1116 // FIXME: Handle '.'.
1118 Sym->setUsedInExpr(true);
1120 // Do the assignment.
1121 Out.EmitAssignment(Sym, Value);
1126 /// ParseIdentifier:
1129 bool AsmParser::ParseIdentifier(StringRef &Res) {
1130 // The assembler has relaxed rules for accepting identifiers, in particular we
1131 // allow things like '.globl $foo', which would normally be separate
1132 // tokens. At this level, we have already lexed so we cannot (currently)
1133 // handle this as a context dependent token, instead we detect adjacent tokens
1134 // and return the combined identifier.
1135 if (Lexer.is(AsmToken::Dollar)) {
1136 SMLoc DollarLoc = getLexer().getLoc();
1138 // Consume the dollar sign, and check for a following identifier.
1140 if (Lexer.isNot(AsmToken::Identifier))
1143 // We have a '$' followed by an identifier, make sure they are adjacent.
1144 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1147 // Construct the joined identifier and consume the token.
1148 Res = StringRef(DollarLoc.getPointer(),
1149 getTok().getIdentifier().size() + 1);
1154 if (Lexer.isNot(AsmToken::Identifier) &&
1155 Lexer.isNot(AsmToken::String))
1158 Res = getTok().getIdentifier();
1160 Lex(); // Consume the identifier token.
1165 /// ParseDirectiveSet:
1166 /// ::= .set identifier ',' expression
1167 bool AsmParser::ParseDirectiveSet() {
1170 if (ParseIdentifier(Name))
1171 return TokError("expected identifier after '.set' directive");
1173 if (getLexer().isNot(AsmToken::Comma))
1174 return TokError("unexpected token in '.set'");
1177 return ParseAssignment(Name);
1180 bool AsmParser::ParseEscapedString(std::string &Data) {
1181 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1184 StringRef Str = getTok().getStringContents();
1185 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1186 if (Str[i] != '\\') {
1191 // Recognize escaped characters. Note that this escape semantics currently
1192 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1195 return TokError("unexpected backslash at end of string");
1197 // Recognize octal sequences.
1198 if ((unsigned) (Str[i] - '0') <= 7) {
1199 // Consume up to three octal characters.
1200 unsigned Value = Str[i] - '0';
1202 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1204 Value = Value * 8 + (Str[i] - '0');
1206 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1208 Value = Value * 8 + (Str[i] - '0');
1213 return TokError("invalid octal escape sequence (out of range)");
1215 Data += (unsigned char) Value;
1219 // Otherwise recognize individual escapes.
1222 // Just reject invalid escape sequences for now.
1223 return TokError("invalid escape sequence (unrecognized character)");
1225 case 'b': Data += '\b'; break;
1226 case 'f': Data += '\f'; break;
1227 case 'n': Data += '\n'; break;
1228 case 'r': Data += '\r'; break;
1229 case 't': Data += '\t'; break;
1230 case '"': Data += '"'; break;
1231 case '\\': Data += '\\'; break;
1238 /// ParseDirectiveAscii:
1239 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1240 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1241 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1243 if (getLexer().isNot(AsmToken::String))
1244 return TokError("expected string in '.ascii' or '.asciz' directive");
1247 if (ParseEscapedString(Data))
1250 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1252 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1256 if (getLexer().is(AsmToken::EndOfStatement))
1259 if (getLexer().isNot(AsmToken::Comma))
1260 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1269 /// ParseDirectiveValue
1270 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1271 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1272 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1274 const MCExpr *Value;
1275 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1276 if (ParseExpression(Value))
1279 // Special case constant expressions to match code generator.
1280 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1281 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1283 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1285 if (getLexer().is(AsmToken::EndOfStatement))
1288 // FIXME: Improve diagnostic.
1289 if (getLexer().isNot(AsmToken::Comma))
1290 return TokError("unexpected token in directive");
1299 /// ParseDirectiveSpace
1300 /// ::= .space expression [ , expression ]
1301 bool AsmParser::ParseDirectiveSpace() {
1303 if (ParseAbsoluteExpression(NumBytes))
1306 int64_t FillExpr = 0;
1307 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1308 if (getLexer().isNot(AsmToken::Comma))
1309 return TokError("unexpected token in '.space' directive");
1312 if (ParseAbsoluteExpression(FillExpr))
1315 if (getLexer().isNot(AsmToken::EndOfStatement))
1316 return TokError("unexpected token in '.space' directive");
1322 return TokError("invalid number of bytes in '.space' directive");
1324 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1325 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1330 /// ParseDirectiveFill
1331 /// ::= .fill expression , expression , expression
1332 bool AsmParser::ParseDirectiveFill() {
1334 if (ParseAbsoluteExpression(NumValues))
1337 if (getLexer().isNot(AsmToken::Comma))
1338 return TokError("unexpected token in '.fill' directive");
1342 if (ParseAbsoluteExpression(FillSize))
1345 if (getLexer().isNot(AsmToken::Comma))
1346 return TokError("unexpected token in '.fill' directive");
1350 if (ParseAbsoluteExpression(FillExpr))
1353 if (getLexer().isNot(AsmToken::EndOfStatement))
1354 return TokError("unexpected token in '.fill' directive");
1358 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1359 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1361 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1362 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1367 /// ParseDirectiveOrg
1368 /// ::= .org expression [ , expression ]
1369 bool AsmParser::ParseDirectiveOrg() {
1370 const MCExpr *Offset;
1371 if (ParseExpression(Offset))
1374 // Parse optional fill expression.
1375 int64_t FillExpr = 0;
1376 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1377 if (getLexer().isNot(AsmToken::Comma))
1378 return TokError("unexpected token in '.org' directive");
1381 if (ParseAbsoluteExpression(FillExpr))
1384 if (getLexer().isNot(AsmToken::EndOfStatement))
1385 return TokError("unexpected token in '.org' directive");
1390 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1391 // has to be relative to the current section.
1392 getStreamer().EmitValueToOffset(Offset, FillExpr);
1397 /// ParseDirectiveAlign
1398 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1399 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1400 SMLoc AlignmentLoc = getLexer().getLoc();
1402 if (ParseAbsoluteExpression(Alignment))
1406 bool HasFillExpr = false;
1407 int64_t FillExpr = 0;
1408 int64_t MaxBytesToFill = 0;
1409 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1410 if (getLexer().isNot(AsmToken::Comma))
1411 return TokError("unexpected token in directive");
1414 // The fill expression can be omitted while specifying a maximum number of
1415 // alignment bytes, e.g:
1417 if (getLexer().isNot(AsmToken::Comma)) {
1419 if (ParseAbsoluteExpression(FillExpr))
1423 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1424 if (getLexer().isNot(AsmToken::Comma))
1425 return TokError("unexpected token in directive");
1428 MaxBytesLoc = getLexer().getLoc();
1429 if (ParseAbsoluteExpression(MaxBytesToFill))
1432 if (getLexer().isNot(AsmToken::EndOfStatement))
1433 return TokError("unexpected token in directive");
1442 // Compute alignment in bytes.
1444 // FIXME: Diagnose overflow.
1445 if (Alignment >= 32) {
1446 Error(AlignmentLoc, "invalid alignment value");
1450 Alignment = 1ULL << Alignment;
1453 // Diagnose non-sensical max bytes to align.
1454 if (MaxBytesLoc.isValid()) {
1455 if (MaxBytesToFill < 1) {
1456 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1457 "many bytes, ignoring maximum bytes expression");
1461 if (MaxBytesToFill >= Alignment) {
1462 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1468 // Check whether we should use optimal code alignment for this .align
1471 // FIXME: This should be using a target hook.
1472 bool UseCodeAlign = false;
1473 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1474 getStreamer().getCurrentSection()))
1475 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1476 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1477 ValueSize == 1 && UseCodeAlign) {
1478 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1480 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1481 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1488 /// ParseDirectiveSymbolAttribute
1489 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1490 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1491 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1495 if (ParseIdentifier(Name))
1496 return TokError("expected identifier in directive");
1498 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1500 getStreamer().EmitSymbolAttribute(Sym, Attr);
1502 if (getLexer().is(AsmToken::EndOfStatement))
1505 if (getLexer().isNot(AsmToken::Comma))
1506 return TokError("unexpected token in directive");
1515 /// ParseDirectiveELFType
1516 /// ::= .type identifier , @attribute
1517 bool AsmParser::ParseDirectiveELFType() {
1519 if (ParseIdentifier(Name))
1520 return TokError("expected identifier in directive");
1522 // Handle the identifier as the key symbol.
1523 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1525 if (getLexer().isNot(AsmToken::Comma))
1526 return TokError("unexpected token in '.type' directive");
1529 if (getLexer().isNot(AsmToken::At))
1530 return TokError("expected '@' before type");
1536 TypeLoc = getLexer().getLoc();
1537 if (ParseIdentifier(Type))
1538 return TokError("expected symbol type in directive");
1540 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1541 .Case("function", MCSA_ELF_TypeFunction)
1542 .Case("object", MCSA_ELF_TypeObject)
1543 .Case("tls_object", MCSA_ELF_TypeTLS)
1544 .Case("common", MCSA_ELF_TypeCommon)
1545 .Case("notype", MCSA_ELF_TypeNoType)
1546 .Default(MCSA_Invalid);
1548 if (Attr == MCSA_Invalid)
1549 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1551 if (getLexer().isNot(AsmToken::EndOfStatement))
1552 return TokError("unexpected token in '.type' directive");
1556 getStreamer().EmitSymbolAttribute(Sym, Attr);
1561 /// ParseDirectiveComm
1562 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1563 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1564 SMLoc IDLoc = getLexer().getLoc();
1566 if (ParseIdentifier(Name))
1567 return TokError("expected identifier in directive");
1569 // Handle the identifier as the key symbol.
1570 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1572 if (getLexer().isNot(AsmToken::Comma))
1573 return TokError("unexpected token in directive");
1577 SMLoc SizeLoc = getLexer().getLoc();
1578 if (ParseAbsoluteExpression(Size))
1581 int64_t Pow2Alignment = 0;
1582 SMLoc Pow2AlignmentLoc;
1583 if (getLexer().is(AsmToken::Comma)) {
1585 Pow2AlignmentLoc = getLexer().getLoc();
1586 if (ParseAbsoluteExpression(Pow2Alignment))
1589 // If this target takes alignments in bytes (not log) validate and convert.
1590 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1591 if (!isPowerOf2_64(Pow2Alignment))
1592 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1593 Pow2Alignment = Log2_64(Pow2Alignment);
1597 if (getLexer().isNot(AsmToken::EndOfStatement))
1598 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1602 // NOTE: a size of zero for a .comm should create a undefined symbol
1603 // but a size of .lcomm creates a bss symbol of size zero.
1605 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1606 "be less than zero");
1608 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1609 // may internally end up wanting an alignment in bytes.
1610 // FIXME: Diagnose overflow.
1611 if (Pow2Alignment < 0)
1612 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1613 "alignment, can't be less than zero");
1615 if (!Sym->isUndefined())
1616 return Error(IDLoc, "invalid symbol redefinition");
1618 // '.lcomm' is equivalent to '.zerofill'.
1619 // Create the Symbol as a common or local common with Size and Pow2Alignment
1621 getStreamer().EmitZerofill(Ctx.getMachOSection(
1622 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1623 0, SectionKind::getBSS()),
1624 Sym, Size, 1 << Pow2Alignment);
1628 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1632 /// ParseDirectiveAbort
1633 /// ::= .abort [... message ...]
1634 bool AsmParser::ParseDirectiveAbort() {
1635 // FIXME: Use loc from directive.
1636 SMLoc Loc = getLexer().getLoc();
1638 StringRef Str = ParseStringToEndOfStatement();
1639 if (getLexer().isNot(AsmToken::EndOfStatement))
1640 return TokError("unexpected token in '.abort' directive");
1645 Error(Loc, ".abort detected. Assembly stopping.");
1647 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1648 // FIXME: Actually abort assembly here.
1653 /// ParseDirectiveInclude
1654 /// ::= .include "filename"
1655 bool AsmParser::ParseDirectiveInclude() {
1656 if (getLexer().isNot(AsmToken::String))
1657 return TokError("expected string in '.include' directive");
1659 std::string Filename = getTok().getString();
1660 SMLoc IncludeLoc = getLexer().getLoc();
1663 if (getLexer().isNot(AsmToken::EndOfStatement))
1664 return TokError("unexpected token in '.include' directive");
1666 // Strip the quotes.
1667 Filename = Filename.substr(1, Filename.size()-2);
1669 // Attempt to switch the lexer to the included file before consuming the end
1670 // of statement to avoid losing it when we switch.
1671 if (EnterIncludeFile(Filename)) {
1672 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1679 /// ParseDirectiveIf
1680 /// ::= .if expression
1681 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1682 TheCondStack.push_back(TheCondState);
1683 TheCondState.TheCond = AsmCond::IfCond;
1684 if(TheCondState.Ignore) {
1685 EatToEndOfStatement();
1689 if (ParseAbsoluteExpression(ExprValue))
1692 if (getLexer().isNot(AsmToken::EndOfStatement))
1693 return TokError("unexpected token in '.if' directive");
1697 TheCondState.CondMet = ExprValue;
1698 TheCondState.Ignore = !TheCondState.CondMet;
1704 /// ParseDirectiveElseIf
1705 /// ::= .elseif expression
1706 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1707 if (TheCondState.TheCond != AsmCond::IfCond &&
1708 TheCondState.TheCond != AsmCond::ElseIfCond)
1709 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1711 TheCondState.TheCond = AsmCond::ElseIfCond;
1713 bool LastIgnoreState = false;
1714 if (!TheCondStack.empty())
1715 LastIgnoreState = TheCondStack.back().Ignore;
1716 if (LastIgnoreState || TheCondState.CondMet) {
1717 TheCondState.Ignore = true;
1718 EatToEndOfStatement();
1722 if (ParseAbsoluteExpression(ExprValue))
1725 if (getLexer().isNot(AsmToken::EndOfStatement))
1726 return TokError("unexpected token in '.elseif' directive");
1729 TheCondState.CondMet = ExprValue;
1730 TheCondState.Ignore = !TheCondState.CondMet;
1736 /// ParseDirectiveElse
1738 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1739 if (getLexer().isNot(AsmToken::EndOfStatement))
1740 return TokError("unexpected token in '.else' directive");
1744 if (TheCondState.TheCond != AsmCond::IfCond &&
1745 TheCondState.TheCond != AsmCond::ElseIfCond)
1746 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1748 TheCondState.TheCond = AsmCond::ElseCond;
1749 bool LastIgnoreState = false;
1750 if (!TheCondStack.empty())
1751 LastIgnoreState = TheCondStack.back().Ignore;
1752 if (LastIgnoreState || TheCondState.CondMet)
1753 TheCondState.Ignore = true;
1755 TheCondState.Ignore = false;
1760 /// ParseDirectiveEndIf
1762 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1763 if (getLexer().isNot(AsmToken::EndOfStatement))
1764 return TokError("unexpected token in '.endif' directive");
1768 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1769 TheCondStack.empty())
1770 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1772 if (!TheCondStack.empty()) {
1773 TheCondState = TheCondStack.back();
1774 TheCondStack.pop_back();
1780 /// ParseDirectiveFile
1781 /// ::= .file [number] string
1782 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1783 // FIXME: I'm not sure what this is.
1784 int64_t FileNumber = -1;
1785 SMLoc FileNumberLoc = getLexer().getLoc();
1786 if (getLexer().is(AsmToken::Integer)) {
1787 FileNumber = getTok().getIntVal();
1791 return TokError("file number less than one");
1794 if (getLexer().isNot(AsmToken::String))
1795 return TokError("unexpected token in '.file' directive");
1797 StringRef Filename = getTok().getString();
1798 Filename = Filename.substr(1, Filename.size()-2);
1801 if (getLexer().isNot(AsmToken::EndOfStatement))
1802 return TokError("unexpected token in '.file' directive");
1804 if (FileNumber == -1)
1805 getStreamer().EmitFileDirective(Filename);
1807 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1808 Error(FileNumberLoc, "file number already allocated");
1809 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1815 /// ParseDirectiveLine
1816 /// ::= .line [number]
1817 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1818 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1819 if (getLexer().isNot(AsmToken::Integer))
1820 return TokError("unexpected token in '.line' directive");
1822 int64_t LineNumber = getTok().getIntVal();
1826 // FIXME: Do something with the .line.
1829 if (getLexer().isNot(AsmToken::EndOfStatement))
1830 return TokError("unexpected token in '.line' directive");
1836 /// ParseDirectiveLoc
1837 /// ::= .loc number [number [number]]
1838 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1839 if (getLexer().isNot(AsmToken::Integer))
1840 return TokError("unexpected token in '.loc' directive");
1842 // FIXME: What are these fields?
1843 int64_t FileNumber = getTok().getIntVal();
1845 // FIXME: Validate file.
1848 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1849 if (getLexer().isNot(AsmToken::Integer))
1850 return TokError("unexpected token in '.loc' directive");
1852 int64_t Param2 = getTok().getIntVal();
1856 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1857 if (getLexer().isNot(AsmToken::Integer))
1858 return TokError("unexpected token in '.loc' directive");
1860 int64_t Param3 = getTok().getIntVal();
1864 // FIXME: Do something with the .loc.
1868 if (getLexer().isNot(AsmToken::EndOfStatement))
1869 return TokError("unexpected token in '.file' directive");
1874 /// ParseDirectiveMacrosOnOff
1877 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1878 SMLoc DirectiveLoc) {
1879 if (getLexer().isNot(AsmToken::EndOfStatement))
1880 return Error(getLexer().getLoc(),
1881 "unexpected token in '" + Directive + "' directive");
1883 getParser().MacrosEnabled = Directive == ".macros_on";
1888 /// ParseDirectiveMacro
1890 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1891 SMLoc DirectiveLoc) {
1893 if (getParser().ParseIdentifier(Name))
1894 return TokError("expected identifier in directive");
1896 if (getLexer().isNot(AsmToken::EndOfStatement))
1897 return TokError("unexpected token in '.macro' directive");
1899 // Eat the end of statement.
1902 AsmToken EndToken, StartToken = getTok();
1904 // Lex the macro definition.
1906 // Check whether we have reached the end of the file.
1907 if (getLexer().is(AsmToken::Eof))
1908 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1910 // Otherwise, check whether we have reach the .endmacro.
1911 if (getLexer().is(AsmToken::Identifier) &&
1912 (getTok().getIdentifier() == ".endm" ||
1913 getTok().getIdentifier() == ".endmacro")) {
1914 EndToken = getTok();
1916 if (getLexer().isNot(AsmToken::EndOfStatement))
1917 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1922 // Otherwise, scan til the end of the statement.
1923 getParser().EatToEndOfStatement();
1926 if (getParser().MacroMap.lookup(Name)) {
1927 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1930 const char *BodyStart = StartToken.getLoc().getPointer();
1931 const char *BodyEnd = EndToken.getLoc().getPointer();
1932 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1933 getParser().MacroMap[Name] = new Macro(Name, Body);
1937 /// ParseDirectiveEndMacro
1940 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1941 SMLoc DirectiveLoc) {
1942 if (getLexer().isNot(AsmToken::EndOfStatement))
1943 return TokError("unexpected token in '" + Directive + "' directive");
1945 // If we are inside a macro instantiation, terminate the current
1947 if (!getParser().ActiveMacros.empty()) {
1948 getParser().HandleMacroExit();
1952 // Otherwise, this .endmacro is a stray entry in the file; well formed
1953 // .endmacro directives are handled during the macro definition parsing.
1954 return TokError("unexpected '" + Directive + "' in file, "
1955 "no current macro definition");
1958 /// \brief Create an MCAsmParser instance.
1959 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1960 MCContext &C, MCStreamer &Out,
1961 const MCAsmInfo &MAI) {
1962 return new AsmParser(T, SM, C, Out, MAI);