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 bool ParseAssignment(StringRef Name);
159 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
160 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
161 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
163 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
164 /// and set \arg Res to the identifier contents.
165 bool ParseIdentifier(StringRef &Res);
167 // Directive Parsing.
168 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
169 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
170 bool ParseDirectiveFill(); // ".fill"
171 bool ParseDirectiveSpace(); // ".space"
172 bool ParseDirectiveSet(); // ".set"
173 bool ParseDirectiveOrg(); // ".org"
174 // ".align{,32}", ".p2align{,w,l}"
175 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
177 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
178 /// accepts a single symbol (which should be a label or an external).
179 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
180 bool ParseDirectiveELFType(); // ELF specific ".type"
182 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
184 bool ParseDirectiveAbort(); // ".abort"
185 bool ParseDirectiveInclude(); // ".include"
187 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
188 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
189 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
190 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
192 /// ParseEscapedString - Parse the current token as a string which may include
193 /// escaped characters and return the string contents.
194 bool ParseEscapedString(std::string &Data);
197 /// \brief Generic implementations of directive handling, etc. which is shared
198 /// (or the default, at least) for all assembler parser.
199 class GenericAsmParser : public MCAsmParserExtension {
201 GenericAsmParser() {}
203 AsmParser &getParser() {
204 return (AsmParser&) this->MCAsmParserExtension::getParser();
207 virtual void Initialize(MCAsmParser &Parser) {
208 // Call the base implementation.
209 this->MCAsmParserExtension::Initialize(Parser);
211 // Debugging directives.
212 Parser.AddDirectiveHandler(this, ".file", MCAsmParser::DirectiveHandler(
213 &GenericAsmParser::ParseDirectiveFile));
214 Parser.AddDirectiveHandler(this, ".line", MCAsmParser::DirectiveHandler(
215 &GenericAsmParser::ParseDirectiveLine));
216 Parser.AddDirectiveHandler(this, ".loc", MCAsmParser::DirectiveHandler(
217 &GenericAsmParser::ParseDirectiveLoc));
220 Parser.AddDirectiveHandler(this, ".macros_on",
221 MCAsmParser::DirectiveHandler(
222 &GenericAsmParser::ParseDirectiveMacrosOnOff));
223 Parser.AddDirectiveHandler(this, ".macros_off",
224 MCAsmParser::DirectiveHandler(
225 &GenericAsmParser::ParseDirectiveMacrosOnOff));
226 Parser.AddDirectiveHandler(this, ".macro", MCAsmParser::DirectiveHandler(
227 &GenericAsmParser::ParseDirectiveMacro));
228 Parser.AddDirectiveHandler(this, ".endm", MCAsmParser::DirectiveHandler(
229 &GenericAsmParser::ParseDirectiveEndMacro));
230 Parser.AddDirectiveHandler(this, ".endmacro", MCAsmParser::DirectiveHandler(
231 &GenericAsmParser::ParseDirectiveEndMacro));
234 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
235 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
236 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
238 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
239 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
240 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
247 extern MCAsmParserExtension *createDarwinAsmParser();
248 extern MCAsmParserExtension *createELFAsmParser();
252 enum { DEFAULT_ADDRSPACE = 0 };
254 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
255 MCStreamer &_Out, const MCAsmInfo &_MAI)
256 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
257 GenericParser(new GenericAsmParser), PlatformParser(0),
258 CurBuffer(0), MacrosEnabled(true) {
259 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
261 // Initialize the generic parser.
262 GenericParser->Initialize(*this);
264 // Initialize the platform / file format parser.
266 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
268 if (_MAI.hasSubsectionsViaSymbols()) {
269 PlatformParser = createDarwinAsmParser();
270 PlatformParser->Initialize(*this);
272 PlatformParser = createELFAsmParser();
273 PlatformParser->Initialize(*this);
277 AsmParser::~AsmParser() {
278 delete PlatformParser;
279 delete GenericParser;
282 void AsmParser::PrintMacroInstantiations() {
283 // Print the active macro instantiation stack.
284 for (std::vector<MacroInstantiation*>::const_reverse_iterator
285 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
286 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
290 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
291 PrintMessage(L, Msg.str(), "warning");
292 PrintMacroInstantiations();
295 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
296 PrintMessage(L, Msg.str(), "error");
297 PrintMacroInstantiations();
301 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
302 const char *Type) const {
303 SrcMgr.PrintMessage(Loc, Msg, Type);
306 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
307 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
313 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
318 void AsmParser::JumpToLoc(SMLoc Loc) {
319 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
320 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
323 const AsmToken &AsmParser::Lex() {
324 const AsmToken *tok = &Lexer.Lex();
326 if (tok->is(AsmToken::Eof)) {
327 // If this is the end of an included file, pop the parent file off the
329 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
330 if (ParentIncludeLoc != SMLoc()) {
331 JumpToLoc(ParentIncludeLoc);
336 if (tok->is(AsmToken::Error))
337 Error(Lexer.getErrLoc(), Lexer.getErr());
342 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
343 // Create the initial section, if requested.
345 // FIXME: Target hook & command line option for initial section.
346 if (!NoInitialTextSection)
347 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
348 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
349 0, SectionKind::getText()));
354 bool HadError = false;
356 AsmCond StartingCondState = TheCondState;
358 // While we have input, parse each statement.
359 while (Lexer.isNot(AsmToken::Eof)) {
360 if (!ParseStatement()) continue;
362 // We had an error, remember it and recover by skipping to the next line.
364 EatToEndOfStatement();
367 if (TheCondState.TheCond != StartingCondState.TheCond ||
368 TheCondState.Ignore != StartingCondState.Ignore)
369 return TokError("unmatched .ifs or .elses");
371 // Finalize the output stream if there are no errors and if the client wants
373 if (!HadError && !NoFinalize)
379 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
380 void AsmParser::EatToEndOfStatement() {
381 while (Lexer.isNot(AsmToken::EndOfStatement) &&
382 Lexer.isNot(AsmToken::Eof))
386 if (Lexer.is(AsmToken::EndOfStatement))
391 /// ParseParenExpr - Parse a paren expression and return it.
392 /// NOTE: This assumes the leading '(' has already been consumed.
394 /// parenexpr ::= expr)
396 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
397 if (ParseExpression(Res)) return true;
398 if (Lexer.isNot(AsmToken::RParen))
399 return TokError("expected ')' in parentheses expression");
400 EndLoc = Lexer.getLoc();
405 /// ParsePrimaryExpr - Parse a primary expression and return it.
406 /// primaryexpr ::= (parenexpr
407 /// primaryexpr ::= symbol
408 /// primaryexpr ::= number
409 /// primaryexpr ::= '.'
410 /// primaryexpr ::= ~,+,- primaryexpr
411 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
412 switch (Lexer.getKind()) {
414 return TokError("unknown token in expression");
415 case AsmToken::Exclaim:
416 Lex(); // Eat the operator.
417 if (ParsePrimaryExpr(Res, EndLoc))
419 Res = MCUnaryExpr::CreateLNot(Res, getContext());
421 case AsmToken::String:
422 case AsmToken::Identifier: {
423 // This is a symbol reference.
424 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
425 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
427 // Mark the symbol as used in an expression.
428 Sym->setUsedInExpr(true);
430 // Lookup the symbol variant if used.
431 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
432 if (Split.first.size() != getTok().getIdentifier().size())
433 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
435 EndLoc = Lexer.getLoc();
436 Lex(); // Eat identifier.
438 // If this is an absolute variable reference, substitute it now to preserve
439 // semantics in the face of reassignment.
440 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
442 return Error(EndLoc, "unexpected modified on variable reference");
444 Res = Sym->getVariableValue();
448 // Otherwise create a symbol ref.
449 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
452 case AsmToken::Integer: {
453 SMLoc Loc = getTok().getLoc();
454 int64_t IntVal = getTok().getIntVal();
455 Res = MCConstantExpr::Create(IntVal, getContext());
456 EndLoc = Lexer.getLoc();
458 // Look for 'b' or 'f' following an Integer as a directional label
459 if (Lexer.getKind() == AsmToken::Identifier) {
460 StringRef IDVal = getTok().getString();
461 if (IDVal == "f" || IDVal == "b"){
462 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
463 IDVal == "f" ? 1 : 0);
464 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
466 if(IDVal == "b" && Sym->isUndefined())
467 return Error(Loc, "invalid reference to undefined symbol");
468 EndLoc = Lexer.getLoc();
469 Lex(); // Eat identifier.
474 case AsmToken::Dot: {
475 // This is a '.' reference, which references the current PC. Emit a
476 // temporary label to the streamer and refer to it.
477 MCSymbol *Sym = Ctx.CreateTempSymbol();
479 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
480 EndLoc = Lexer.getLoc();
481 Lex(); // Eat identifier.
485 case AsmToken::LParen:
486 Lex(); // Eat the '('.
487 return ParseParenExpr(Res, EndLoc);
488 case AsmToken::Minus:
489 Lex(); // Eat the operator.
490 if (ParsePrimaryExpr(Res, EndLoc))
492 Res = MCUnaryExpr::CreateMinus(Res, getContext());
495 Lex(); // Eat the operator.
496 if (ParsePrimaryExpr(Res, EndLoc))
498 Res = MCUnaryExpr::CreatePlus(Res, getContext());
500 case AsmToken::Tilde:
501 Lex(); // Eat the operator.
502 if (ParsePrimaryExpr(Res, EndLoc))
504 Res = MCUnaryExpr::CreateNot(Res, getContext());
509 bool AsmParser::ParseExpression(const MCExpr *&Res) {
511 return ParseExpression(Res, EndLoc);
514 /// ParseExpression - Parse an expression and return it.
516 /// expr ::= expr +,- expr -> lowest.
517 /// expr ::= expr |,^,&,! expr -> middle.
518 /// expr ::= expr *,/,%,<<,>> expr -> highest.
519 /// expr ::= primaryexpr
521 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
522 // Parse the expression.
524 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
527 // Try to constant fold it up front, if possible.
529 if (Res->EvaluateAsAbsolute(Value))
530 Res = MCConstantExpr::Create(Value, getContext());
535 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
537 return ParseParenExpr(Res, EndLoc) ||
538 ParseBinOpRHS(1, Res, EndLoc);
541 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
544 SMLoc StartLoc = Lexer.getLoc();
545 if (ParseExpression(Expr))
548 if (!Expr->EvaluateAsAbsolute(Res))
549 return Error(StartLoc, "expected absolute expression");
554 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
555 MCBinaryExpr::Opcode &Kind) {
558 return 0; // not a binop.
560 // Lowest Precedence: &&, ||
561 case AsmToken::AmpAmp:
562 Kind = MCBinaryExpr::LAnd;
564 case AsmToken::PipePipe:
565 Kind = MCBinaryExpr::LOr;
568 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
570 Kind = MCBinaryExpr::Add;
572 case AsmToken::Minus:
573 Kind = MCBinaryExpr::Sub;
575 case AsmToken::EqualEqual:
576 Kind = MCBinaryExpr::EQ;
578 case AsmToken::ExclaimEqual:
579 case AsmToken::LessGreater:
580 Kind = MCBinaryExpr::NE;
583 Kind = MCBinaryExpr::LT;
585 case AsmToken::LessEqual:
586 Kind = MCBinaryExpr::LTE;
588 case AsmToken::Greater:
589 Kind = MCBinaryExpr::GT;
591 case AsmToken::GreaterEqual:
592 Kind = MCBinaryExpr::GTE;
595 // Intermediate Precedence: |, &, ^
597 // FIXME: gas seems to support '!' as an infix operator?
599 Kind = MCBinaryExpr::Or;
601 case AsmToken::Caret:
602 Kind = MCBinaryExpr::Xor;
605 Kind = MCBinaryExpr::And;
608 // Highest Precedence: *, /, %, <<, >>
610 Kind = MCBinaryExpr::Mul;
612 case AsmToken::Slash:
613 Kind = MCBinaryExpr::Div;
615 case AsmToken::Percent:
616 Kind = MCBinaryExpr::Mod;
618 case AsmToken::LessLess:
619 Kind = MCBinaryExpr::Shl;
621 case AsmToken::GreaterGreater:
622 Kind = MCBinaryExpr::Shr;
628 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
629 /// Res contains the LHS of the expression on input.
630 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
633 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
634 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
636 // If the next token is lower precedence than we are allowed to eat, return
637 // successfully with what we ate already.
638 if (TokPrec < Precedence)
643 // Eat the next primary expression.
645 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
647 // If BinOp binds less tightly with RHS than the operator after RHS, let
648 // the pending operator take RHS as its LHS.
649 MCBinaryExpr::Opcode Dummy;
650 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
651 if (TokPrec < NextTokPrec) {
652 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
655 // Merge LHS and RHS according to operator.
656 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
664 /// ::= EndOfStatement
665 /// ::= Label* Directive ...Operands... EndOfStatement
666 /// ::= Label* Identifier OperandList* EndOfStatement
667 bool AsmParser::ParseStatement() {
668 if (Lexer.is(AsmToken::EndOfStatement)) {
674 // Statements always start with an identifier.
675 AsmToken ID = getTok();
676 SMLoc IDLoc = ID.getLoc();
678 int64_t LocalLabelVal = -1;
679 // GUESS allow an integer followed by a ':' as a directional local label
680 if (Lexer.is(AsmToken::Integer)) {
681 LocalLabelVal = getTok().getIntVal();
682 if (LocalLabelVal < 0) {
683 if (!TheCondState.Ignore)
684 return TokError("unexpected token at start of statement");
688 IDVal = getTok().getString();
689 Lex(); // Consume the integer token to be used as an identifier token.
690 if (Lexer.getKind() != AsmToken::Colon) {
691 if (!TheCondState.Ignore)
692 return TokError("unexpected token at start of statement");
696 else if (ParseIdentifier(IDVal)) {
697 if (!TheCondState.Ignore)
698 return TokError("unexpected token at start of statement");
702 // Handle conditional assembly here before checking for skipping. We
703 // have to do this so that .endif isn't skipped in a ".if 0" block for
706 return ParseDirectiveIf(IDLoc);
707 if (IDVal == ".elseif")
708 return ParseDirectiveElseIf(IDLoc);
709 if (IDVal == ".else")
710 return ParseDirectiveElse(IDLoc);
711 if (IDVal == ".endif")
712 return ParseDirectiveEndIf(IDLoc);
714 // If we are in a ".if 0" block, ignore this statement.
715 if (TheCondState.Ignore) {
716 EatToEndOfStatement();
720 // FIXME: Recurse on local labels?
722 // See what kind of statement we have.
723 switch (Lexer.getKind()) {
724 case AsmToken::Colon: {
725 // identifier ':' -> Label.
728 // Diagnose attempt to use a variable as a label.
730 // FIXME: Diagnostics. Note the location of the definition as a label.
731 // FIXME: This doesn't diagnose assignment to a symbol which has been
732 // implicitly marked as external.
734 if (LocalLabelVal == -1)
735 Sym = getContext().GetOrCreateSymbol(IDVal);
737 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
738 if (!Sym->isUndefined() || Sym->isVariable())
739 return Error(IDLoc, "invalid symbol redefinition");
744 // Consume any end of statement token, if present, to avoid spurious
745 // AddBlankLine calls().
746 if (Lexer.is(AsmToken::EndOfStatement)) {
748 if (Lexer.is(AsmToken::Eof))
752 return ParseStatement();
755 case AsmToken::Equal:
756 // identifier '=' ... -> assignment statement
759 return ParseAssignment(IDVal);
761 default: // Normal instruction or directive.
765 // If macros are enabled, check to see if this is a macro instantiation.
767 if (const Macro *M = MacroMap.lookup(IDVal))
768 return HandleMacroEntry(IDVal, IDLoc, M);
770 // Otherwise, we have a normal instruction or directive.
771 if (IDVal[0] == '.') {
772 // Assembler features
774 return ParseDirectiveSet();
778 if (IDVal == ".ascii")
779 return ParseDirectiveAscii(false);
780 if (IDVal == ".asciz")
781 return ParseDirectiveAscii(true);
783 if (IDVal == ".byte")
784 return ParseDirectiveValue(1);
785 if (IDVal == ".short")
786 return ParseDirectiveValue(2);
787 if (IDVal == ".long")
788 return ParseDirectiveValue(4);
789 if (IDVal == ".quad")
790 return ParseDirectiveValue(8);
792 // FIXME: Target hooks for IsPow2.
793 if (IDVal == ".align")
794 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
795 if (IDVal == ".align32")
796 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
797 if (IDVal == ".balign")
798 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
799 if (IDVal == ".balignw")
800 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
801 if (IDVal == ".balignl")
802 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
803 if (IDVal == ".p2align")
804 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
805 if (IDVal == ".p2alignw")
806 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
807 if (IDVal == ".p2alignl")
808 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
811 return ParseDirectiveOrg();
813 if (IDVal == ".fill")
814 return ParseDirectiveFill();
815 if (IDVal == ".space")
816 return ParseDirectiveSpace();
818 // Symbol attribute directives
820 if (IDVal == ".globl" || IDVal == ".global")
821 return ParseDirectiveSymbolAttribute(MCSA_Global);
822 if (IDVal == ".hidden")
823 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
824 if (IDVal == ".indirect_symbol")
825 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
826 if (IDVal == ".internal")
827 return ParseDirectiveSymbolAttribute(MCSA_Internal);
828 if (IDVal == ".lazy_reference")
829 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
830 if (IDVal == ".no_dead_strip")
831 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
832 if (IDVal == ".private_extern")
833 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
834 if (IDVal == ".protected")
835 return ParseDirectiveSymbolAttribute(MCSA_Protected);
836 if (IDVal == ".reference")
837 return ParseDirectiveSymbolAttribute(MCSA_Reference);
838 if (IDVal == ".type")
839 return ParseDirectiveELFType();
840 if (IDVal == ".weak")
841 return ParseDirectiveSymbolAttribute(MCSA_Weak);
842 if (IDVal == ".weak_definition")
843 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
844 if (IDVal == ".weak_reference")
845 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
846 if (IDVal == ".weak_def_can_be_hidden")
847 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
849 if (IDVal == ".comm")
850 return ParseDirectiveComm(/*IsLocal=*/false);
851 if (IDVal == ".lcomm")
852 return ParseDirectiveComm(/*IsLocal=*/true);
854 if (IDVal == ".abort")
855 return ParseDirectiveAbort();
856 if (IDVal == ".include")
857 return ParseDirectiveInclude();
859 // Look up the handler in the handler table.
860 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
861 DirectiveMap.lookup(IDVal);
863 return (Handler.first->*Handler.second)(IDVal, IDLoc);
865 // Target hook for parsing target specific directives.
866 if (!getTargetParser().ParseDirective(ID))
869 Warning(IDLoc, "ignoring directive for now");
870 EatToEndOfStatement();
874 // Canonicalize the opcode to lower case.
875 SmallString<128> Opcode;
876 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
877 Opcode.push_back(tolower(IDVal[i]));
879 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
880 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
882 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
883 HadError = TokError("unexpected token in argument list");
885 // If parsing succeeded, match the instruction.
888 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
889 // Emit the instruction on success.
890 Out.EmitInstruction(Inst);
892 // Otherwise emit a diagnostic about the match failure and set the error
895 // FIXME: We should give nicer diagnostics about the exact failure.
896 Error(IDLoc, "unrecognized instruction");
901 // If there was no error, consume the end-of-statement token. Otherwise this
902 // will be done by our caller.
906 // Free any parsed operands.
907 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
908 delete ParsedOperands[i];
913 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
914 const std::vector<std::vector<AsmToken> > &A)
915 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
917 // Macro instantiation is lexical, unfortunately. We construct a new buffer
918 // to hold the macro body with substitutions.
919 SmallString<256> Buf;
920 raw_svector_ostream OS(Buf);
922 StringRef Body = M->Body;
923 while (!Body.empty()) {
924 // Scan for the next substitution.
925 std::size_t End = Body.size(), Pos = 0;
926 for (; Pos != End; ++Pos) {
927 // Check for a substitution or escape.
928 if (Body[Pos] != '$' || Pos + 1 == End)
931 char Next = Body[Pos + 1];
932 if (Next == '$' || Next == 'n' || isdigit(Next))
937 OS << Body.slice(0, Pos);
939 // Check if we reached the end.
943 switch (Body[Pos+1]) {
949 // $n => number of arguments
954 // $[0-9] => argument
956 // Missing arguments are ignored.
957 unsigned Index = Body[Pos+1] - '0';
958 if (Index >= A.size())
961 // Otherwise substitute with the token values, with spaces eliminated.
962 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
963 ie = A[Index].end(); it != ie; ++it)
964 OS << it->getString();
969 // Update the scan point.
970 Body = Body.substr(Pos + 2);
973 // We include the .endmacro in the buffer as our queue to exit the macro
977 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
980 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
982 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
983 // this, although we should protect against infinite loops.
984 if (ActiveMacros.size() == 20)
985 return TokError("macros cannot be nested more than 20 levels deep");
987 // Parse the macro instantiation arguments.
988 std::vector<std::vector<AsmToken> > MacroArguments;
989 MacroArguments.push_back(std::vector<AsmToken>());
990 unsigned ParenLevel = 0;
992 if (Lexer.is(AsmToken::Eof))
993 return TokError("unexpected token in macro instantiation");
994 if (Lexer.is(AsmToken::EndOfStatement))
997 // If we aren't inside parentheses and this is a comma, start a new token
999 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1000 MacroArguments.push_back(std::vector<AsmToken>());
1001 } else if (Lexer.is(AsmToken::LParen)) {
1003 } else if (Lexer.is(AsmToken::RParen)) {
1007 MacroArguments.back().push_back(getTok());
1012 // Create the macro instantiation object and add to the current macro
1013 // instantiation stack.
1014 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1017 ActiveMacros.push_back(MI);
1019 // Jump to the macro instantiation and prime the lexer.
1020 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1021 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1027 void AsmParser::HandleMacroExit() {
1028 // Jump to the EndOfStatement we should return to, and consume it.
1029 JumpToLoc(ActiveMacros.back()->ExitLoc);
1032 // Pop the instantiation entry.
1033 delete ActiveMacros.back();
1034 ActiveMacros.pop_back();
1037 bool AsmParser::ParseAssignment(StringRef Name) {
1038 // FIXME: Use better location, we should use proper tokens.
1039 SMLoc EqualLoc = Lexer.getLoc();
1041 const MCExpr *Value;
1042 if (ParseExpression(Value))
1045 if (Lexer.isNot(AsmToken::EndOfStatement))
1046 return TokError("unexpected token in assignment");
1048 // Eat the end of statement marker.
1051 // Validate that the LHS is allowed to be a variable (either it has not been
1052 // used as a symbol, or it is an absolute symbol).
1053 MCSymbol *Sym = getContext().LookupSymbol(Name);
1055 // Diagnose assignment to a label.
1057 // FIXME: Diagnostics. Note the location of the definition as a label.
1058 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1059 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1060 ; // Allow redefinitions of undefined symbols only used in directives.
1061 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1062 return Error(EqualLoc, "redefinition of '" + Name + "'");
1063 else if (!Sym->isVariable())
1064 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1065 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1066 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1069 Sym = getContext().GetOrCreateSymbol(Name);
1071 // FIXME: Handle '.'.
1073 Sym->setUsedInExpr(true);
1075 // Do the assignment.
1076 Out.EmitAssignment(Sym, Value);
1081 /// ParseIdentifier:
1084 bool AsmParser::ParseIdentifier(StringRef &Res) {
1085 if (Lexer.isNot(AsmToken::Identifier) &&
1086 Lexer.isNot(AsmToken::String))
1089 Res = getTok().getIdentifier();
1091 Lex(); // Consume the identifier token.
1096 /// ParseDirectiveSet:
1097 /// ::= .set identifier ',' expression
1098 bool AsmParser::ParseDirectiveSet() {
1101 if (ParseIdentifier(Name))
1102 return TokError("expected identifier after '.set' directive");
1104 if (getLexer().isNot(AsmToken::Comma))
1105 return TokError("unexpected token in '.set'");
1108 return ParseAssignment(Name);
1111 bool AsmParser::ParseEscapedString(std::string &Data) {
1112 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1115 StringRef Str = getTok().getStringContents();
1116 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1117 if (Str[i] != '\\') {
1122 // Recognize escaped characters. Note that this escape semantics currently
1123 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1126 return TokError("unexpected backslash at end of string");
1128 // Recognize octal sequences.
1129 if ((unsigned) (Str[i] - '0') <= 7) {
1130 // Consume up to three octal characters.
1131 unsigned Value = Str[i] - '0';
1133 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1135 Value = Value * 8 + (Str[i] - '0');
1137 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1139 Value = Value * 8 + (Str[i] - '0');
1144 return TokError("invalid octal escape sequence (out of range)");
1146 Data += (unsigned char) Value;
1150 // Otherwise recognize individual escapes.
1153 // Just reject invalid escape sequences for now.
1154 return TokError("invalid escape sequence (unrecognized character)");
1156 case 'b': Data += '\b'; break;
1157 case 'f': Data += '\f'; break;
1158 case 'n': Data += '\n'; break;
1159 case 'r': Data += '\r'; break;
1160 case 't': Data += '\t'; break;
1161 case '"': Data += '"'; break;
1162 case '\\': Data += '\\'; break;
1169 /// ParseDirectiveAscii:
1170 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1171 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1172 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1174 if (getLexer().isNot(AsmToken::String))
1175 return TokError("expected string in '.ascii' or '.asciz' directive");
1178 if (ParseEscapedString(Data))
1181 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1183 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1187 if (getLexer().is(AsmToken::EndOfStatement))
1190 if (getLexer().isNot(AsmToken::Comma))
1191 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1200 /// ParseDirectiveValue
1201 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1202 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1203 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1205 const MCExpr *Value;
1206 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1207 if (ParseExpression(Value))
1210 // Special case constant expressions to match code generator.
1211 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1212 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1214 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1216 if (getLexer().is(AsmToken::EndOfStatement))
1219 // FIXME: Improve diagnostic.
1220 if (getLexer().isNot(AsmToken::Comma))
1221 return TokError("unexpected token in directive");
1230 /// ParseDirectiveSpace
1231 /// ::= .space expression [ , expression ]
1232 bool AsmParser::ParseDirectiveSpace() {
1234 if (ParseAbsoluteExpression(NumBytes))
1237 int64_t FillExpr = 0;
1238 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1239 if (getLexer().isNot(AsmToken::Comma))
1240 return TokError("unexpected token in '.space' directive");
1243 if (ParseAbsoluteExpression(FillExpr))
1246 if (getLexer().isNot(AsmToken::EndOfStatement))
1247 return TokError("unexpected token in '.space' directive");
1253 return TokError("invalid number of bytes in '.space' directive");
1255 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1256 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1261 /// ParseDirectiveFill
1262 /// ::= .fill expression , expression , expression
1263 bool AsmParser::ParseDirectiveFill() {
1265 if (ParseAbsoluteExpression(NumValues))
1268 if (getLexer().isNot(AsmToken::Comma))
1269 return TokError("unexpected token in '.fill' directive");
1273 if (ParseAbsoluteExpression(FillSize))
1276 if (getLexer().isNot(AsmToken::Comma))
1277 return TokError("unexpected token in '.fill' directive");
1281 if (ParseAbsoluteExpression(FillExpr))
1284 if (getLexer().isNot(AsmToken::EndOfStatement))
1285 return TokError("unexpected token in '.fill' directive");
1289 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1290 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1292 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1293 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1298 /// ParseDirectiveOrg
1299 /// ::= .org expression [ , expression ]
1300 bool AsmParser::ParseDirectiveOrg() {
1301 const MCExpr *Offset;
1302 if (ParseExpression(Offset))
1305 // Parse optional fill expression.
1306 int64_t FillExpr = 0;
1307 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1308 if (getLexer().isNot(AsmToken::Comma))
1309 return TokError("unexpected token in '.org' directive");
1312 if (ParseAbsoluteExpression(FillExpr))
1315 if (getLexer().isNot(AsmToken::EndOfStatement))
1316 return TokError("unexpected token in '.org' directive");
1321 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1322 // has to be relative to the current section.
1323 getStreamer().EmitValueToOffset(Offset, FillExpr);
1328 /// ParseDirectiveAlign
1329 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1330 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1331 SMLoc AlignmentLoc = getLexer().getLoc();
1333 if (ParseAbsoluteExpression(Alignment))
1337 bool HasFillExpr = false;
1338 int64_t FillExpr = 0;
1339 int64_t MaxBytesToFill = 0;
1340 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1341 if (getLexer().isNot(AsmToken::Comma))
1342 return TokError("unexpected token in directive");
1345 // The fill expression can be omitted while specifying a maximum number of
1346 // alignment bytes, e.g:
1348 if (getLexer().isNot(AsmToken::Comma)) {
1350 if (ParseAbsoluteExpression(FillExpr))
1354 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1355 if (getLexer().isNot(AsmToken::Comma))
1356 return TokError("unexpected token in directive");
1359 MaxBytesLoc = getLexer().getLoc();
1360 if (ParseAbsoluteExpression(MaxBytesToFill))
1363 if (getLexer().isNot(AsmToken::EndOfStatement))
1364 return TokError("unexpected token in directive");
1373 // Compute alignment in bytes.
1375 // FIXME: Diagnose overflow.
1376 if (Alignment >= 32) {
1377 Error(AlignmentLoc, "invalid alignment value");
1381 Alignment = 1ULL << Alignment;
1384 // Diagnose non-sensical max bytes to align.
1385 if (MaxBytesLoc.isValid()) {
1386 if (MaxBytesToFill < 1) {
1387 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1388 "many bytes, ignoring maximum bytes expression");
1392 if (MaxBytesToFill >= Alignment) {
1393 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1399 // Check whether we should use optimal code alignment for this .align
1402 // FIXME: This should be using a target hook.
1403 bool UseCodeAlign = false;
1404 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1405 getStreamer().getCurrentSection()))
1406 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1407 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1408 ValueSize == 1 && UseCodeAlign) {
1409 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1411 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1412 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1419 /// ParseDirectiveSymbolAttribute
1420 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1421 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1422 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1426 if (ParseIdentifier(Name))
1427 return TokError("expected identifier in directive");
1429 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1431 getStreamer().EmitSymbolAttribute(Sym, Attr);
1433 if (getLexer().is(AsmToken::EndOfStatement))
1436 if (getLexer().isNot(AsmToken::Comma))
1437 return TokError("unexpected token in directive");
1446 /// ParseDirectiveELFType
1447 /// ::= .type identifier , @attribute
1448 bool AsmParser::ParseDirectiveELFType() {
1450 if (ParseIdentifier(Name))
1451 return TokError("expected identifier in directive");
1453 // Handle the identifier as the key symbol.
1454 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1456 if (getLexer().isNot(AsmToken::Comma))
1457 return TokError("unexpected token in '.type' directive");
1460 if (getLexer().isNot(AsmToken::At))
1461 return TokError("expected '@' before type");
1467 TypeLoc = getLexer().getLoc();
1468 if (ParseIdentifier(Type))
1469 return TokError("expected symbol type in directive");
1471 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1472 .Case("function", MCSA_ELF_TypeFunction)
1473 .Case("object", MCSA_ELF_TypeObject)
1474 .Case("tls_object", MCSA_ELF_TypeTLS)
1475 .Case("common", MCSA_ELF_TypeCommon)
1476 .Case("notype", MCSA_ELF_TypeNoType)
1477 .Default(MCSA_Invalid);
1479 if (Attr == MCSA_Invalid)
1480 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1482 if (getLexer().isNot(AsmToken::EndOfStatement))
1483 return TokError("unexpected token in '.type' directive");
1487 getStreamer().EmitSymbolAttribute(Sym, Attr);
1492 /// ParseDirectiveComm
1493 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1494 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1495 SMLoc IDLoc = getLexer().getLoc();
1497 if (ParseIdentifier(Name))
1498 return TokError("expected identifier in directive");
1500 // Handle the identifier as the key symbol.
1501 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1503 if (getLexer().isNot(AsmToken::Comma))
1504 return TokError("unexpected token in directive");
1508 SMLoc SizeLoc = getLexer().getLoc();
1509 if (ParseAbsoluteExpression(Size))
1512 int64_t Pow2Alignment = 0;
1513 SMLoc Pow2AlignmentLoc;
1514 if (getLexer().is(AsmToken::Comma)) {
1516 Pow2AlignmentLoc = getLexer().getLoc();
1517 if (ParseAbsoluteExpression(Pow2Alignment))
1520 // If this target takes alignments in bytes (not log) validate and convert.
1521 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1522 if (!isPowerOf2_64(Pow2Alignment))
1523 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1524 Pow2Alignment = Log2_64(Pow2Alignment);
1528 if (getLexer().isNot(AsmToken::EndOfStatement))
1529 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1533 // NOTE: a size of zero for a .comm should create a undefined symbol
1534 // but a size of .lcomm creates a bss symbol of size zero.
1536 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1537 "be less than zero");
1539 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1540 // may internally end up wanting an alignment in bytes.
1541 // FIXME: Diagnose overflow.
1542 if (Pow2Alignment < 0)
1543 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1544 "alignment, can't be less than zero");
1546 if (!Sym->isUndefined())
1547 return Error(IDLoc, "invalid symbol redefinition");
1549 // '.lcomm' is equivalent to '.zerofill'.
1550 // Create the Symbol as a common or local common with Size and Pow2Alignment
1552 getStreamer().EmitZerofill(Ctx.getMachOSection(
1553 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1554 0, SectionKind::getBSS()),
1555 Sym, Size, 1 << Pow2Alignment);
1559 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1563 /// ParseDirectiveAbort
1564 /// ::= .abort [ "abort_string" ]
1565 bool AsmParser::ParseDirectiveAbort() {
1566 // FIXME: Use loc from directive.
1567 SMLoc Loc = getLexer().getLoc();
1570 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1571 if (getLexer().isNot(AsmToken::String))
1572 return TokError("expected string in '.abort' directive");
1574 Str = getTok().getString();
1579 if (getLexer().isNot(AsmToken::EndOfStatement))
1580 return TokError("unexpected token in '.abort' directive");
1584 // FIXME: Handle here.
1586 Error(Loc, ".abort detected. Assembly stopping.");
1588 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1593 /// ParseDirectiveInclude
1594 /// ::= .include "filename"
1595 bool AsmParser::ParseDirectiveInclude() {
1596 if (getLexer().isNot(AsmToken::String))
1597 return TokError("expected string in '.include' directive");
1599 std::string Filename = getTok().getString();
1600 SMLoc IncludeLoc = getLexer().getLoc();
1603 if (getLexer().isNot(AsmToken::EndOfStatement))
1604 return TokError("unexpected token in '.include' directive");
1606 // Strip the quotes.
1607 Filename = Filename.substr(1, Filename.size()-2);
1609 // Attempt to switch the lexer to the included file before consuming the end
1610 // of statement to avoid losing it when we switch.
1611 if (EnterIncludeFile(Filename)) {
1612 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1619 /// ParseDirectiveIf
1620 /// ::= .if expression
1621 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1622 TheCondStack.push_back(TheCondState);
1623 TheCondState.TheCond = AsmCond::IfCond;
1624 if(TheCondState.Ignore) {
1625 EatToEndOfStatement();
1629 if (ParseAbsoluteExpression(ExprValue))
1632 if (getLexer().isNot(AsmToken::EndOfStatement))
1633 return TokError("unexpected token in '.if' directive");
1637 TheCondState.CondMet = ExprValue;
1638 TheCondState.Ignore = !TheCondState.CondMet;
1644 /// ParseDirectiveElseIf
1645 /// ::= .elseif expression
1646 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1647 if (TheCondState.TheCond != AsmCond::IfCond &&
1648 TheCondState.TheCond != AsmCond::ElseIfCond)
1649 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1651 TheCondState.TheCond = AsmCond::ElseIfCond;
1653 bool LastIgnoreState = false;
1654 if (!TheCondStack.empty())
1655 LastIgnoreState = TheCondStack.back().Ignore;
1656 if (LastIgnoreState || TheCondState.CondMet) {
1657 TheCondState.Ignore = true;
1658 EatToEndOfStatement();
1662 if (ParseAbsoluteExpression(ExprValue))
1665 if (getLexer().isNot(AsmToken::EndOfStatement))
1666 return TokError("unexpected token in '.elseif' directive");
1669 TheCondState.CondMet = ExprValue;
1670 TheCondState.Ignore = !TheCondState.CondMet;
1676 /// ParseDirectiveElse
1678 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1679 if (getLexer().isNot(AsmToken::EndOfStatement))
1680 return TokError("unexpected token in '.else' directive");
1684 if (TheCondState.TheCond != AsmCond::IfCond &&
1685 TheCondState.TheCond != AsmCond::ElseIfCond)
1686 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1688 TheCondState.TheCond = AsmCond::ElseCond;
1689 bool LastIgnoreState = false;
1690 if (!TheCondStack.empty())
1691 LastIgnoreState = TheCondStack.back().Ignore;
1692 if (LastIgnoreState || TheCondState.CondMet)
1693 TheCondState.Ignore = true;
1695 TheCondState.Ignore = false;
1700 /// ParseDirectiveEndIf
1702 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1703 if (getLexer().isNot(AsmToken::EndOfStatement))
1704 return TokError("unexpected token in '.endif' directive");
1708 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1709 TheCondStack.empty())
1710 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1712 if (!TheCondStack.empty()) {
1713 TheCondState = TheCondStack.back();
1714 TheCondStack.pop_back();
1720 /// ParseDirectiveFile
1721 /// ::= .file [number] string
1722 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1723 // FIXME: I'm not sure what this is.
1724 int64_t FileNumber = -1;
1725 if (getLexer().is(AsmToken::Integer)) {
1726 FileNumber = getTok().getIntVal();
1730 return TokError("file number less than one");
1733 if (getLexer().isNot(AsmToken::String))
1734 return TokError("unexpected token in '.file' directive");
1736 StringRef Filename = getTok().getString();
1737 Filename = Filename.substr(1, Filename.size()-2);
1740 if (getLexer().isNot(AsmToken::EndOfStatement))
1741 return TokError("unexpected token in '.file' directive");
1743 if (FileNumber == -1)
1744 getStreamer().EmitFileDirective(Filename);
1746 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1751 /// ParseDirectiveLine
1752 /// ::= .line [number]
1753 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1754 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1755 if (getLexer().isNot(AsmToken::Integer))
1756 return TokError("unexpected token in '.line' directive");
1758 int64_t LineNumber = getTok().getIntVal();
1762 // FIXME: Do something with the .line.
1765 if (getLexer().isNot(AsmToken::EndOfStatement))
1766 return TokError("unexpected token in '.line' directive");
1772 /// ParseDirectiveLoc
1773 /// ::= .loc number [number [number]]
1774 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1775 if (getLexer().isNot(AsmToken::Integer))
1776 return TokError("unexpected token in '.loc' directive");
1778 // FIXME: What are these fields?
1779 int64_t FileNumber = getTok().getIntVal();
1781 // FIXME: Validate file.
1784 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1785 if (getLexer().isNot(AsmToken::Integer))
1786 return TokError("unexpected token in '.loc' directive");
1788 int64_t Param2 = getTok().getIntVal();
1792 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1793 if (getLexer().isNot(AsmToken::Integer))
1794 return TokError("unexpected token in '.loc' directive");
1796 int64_t Param3 = getTok().getIntVal();
1800 // FIXME: Do something with the .loc.
1804 if (getLexer().isNot(AsmToken::EndOfStatement))
1805 return TokError("unexpected token in '.file' directive");
1810 /// ParseDirectiveMacrosOnOff
1813 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1814 SMLoc DirectiveLoc) {
1815 if (getLexer().isNot(AsmToken::EndOfStatement))
1816 return Error(getLexer().getLoc(),
1817 "unexpected token in '" + Directive + "' directive");
1819 getParser().MacrosEnabled = Directive == ".macros_on";
1824 /// ParseDirectiveMacro
1826 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1827 SMLoc DirectiveLoc) {
1829 if (getParser().ParseIdentifier(Name))
1830 return TokError("expected identifier in directive");
1832 if (getLexer().isNot(AsmToken::EndOfStatement))
1833 return TokError("unexpected token in '.macro' directive");
1835 // Eat the end of statement.
1838 AsmToken EndToken, StartToken = getTok();
1840 // Lex the macro definition.
1842 // Check whether we have reached the end of the file.
1843 if (getLexer().is(AsmToken::Eof))
1844 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
1846 // Otherwise, check whether we have reach the .endmacro.
1847 if (getLexer().is(AsmToken::Identifier) &&
1848 (getTok().getIdentifier() == ".endm" ||
1849 getTok().getIdentifier() == ".endmacro")) {
1850 EndToken = getTok();
1852 if (getLexer().isNot(AsmToken::EndOfStatement))
1853 return TokError("unexpected token in '" + EndToken.getIdentifier() +
1858 // Otherwise, scan til the end of the statement.
1859 getParser().EatToEndOfStatement();
1862 if (getParser().MacroMap.lookup(Name)) {
1863 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
1866 const char *BodyStart = StartToken.getLoc().getPointer();
1867 const char *BodyEnd = EndToken.getLoc().getPointer();
1868 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
1869 getParser().MacroMap[Name] = new Macro(Name, Body);
1873 /// ParseDirectiveEndMacro
1876 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
1877 SMLoc DirectiveLoc) {
1878 if (getLexer().isNot(AsmToken::EndOfStatement))
1879 return TokError("unexpected token in '" + Directive + "' directive");
1881 // If we are inside a macro instantiation, terminate the current
1883 if (!getParser().ActiveMacros.empty()) {
1884 getParser().HandleMacroExit();
1888 // Otherwise, this .endmacro is a stray entry in the file; well formed
1889 // .endmacro directives are handled during the macro definition parsing.
1890 return TokError("unexpected '" + Directive + "' in file, "
1891 "no current macro definition");
1894 /// \brief Create an MCAsmParser instance.
1895 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
1896 MCContext &C, MCStreamer &Out,
1897 const MCAsmInfo &MAI) {
1898 return new AsmParser(T, SM, C, Out, MAI);