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;
105 /// Flag tracking whether any errors have been encountered.
106 unsigned HadError : 1;
109 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
110 const MCAsmInfo &MAI);
113 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
115 void AddDirectiveHandler(MCAsmParserExtension *Object,
117 DirectiveHandler Handler) {
118 DirectiveMap[Directive] = std::make_pair(Object, Handler);
122 /// @name MCAsmParser Interface
125 virtual SourceMgr &getSourceManager() { return SrcMgr; }
126 virtual MCAsmLexer &getLexer() { return Lexer; }
127 virtual MCContext &getContext() { return Ctx; }
128 virtual MCStreamer &getStreamer() { return Out; }
130 virtual void Warning(SMLoc L, const Twine &Meg);
131 virtual bool Error(SMLoc L, const Twine &Msg);
133 const AsmToken &Lex();
135 bool ParseExpression(const MCExpr *&Res);
136 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseAbsoluteExpression(int64_t &Res);
143 void CheckForValidSection();
145 bool ParseStatement();
147 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
148 void HandleMacroExit();
150 void PrintMacroInstantiations();
151 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
153 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
154 bool EnterIncludeFile(const std::string &Filename);
156 /// \brief Reset the current lexer position to that given by \arg Loc. The
157 /// current token is not set; clients should ensure Lex() is called
159 void JumpToLoc(SMLoc Loc);
161 void EatToEndOfStatement();
163 /// \brief Parse up to the end of statement and a return the contents from the
164 /// current token until the end of the statement; the current token on exit
165 /// will be either the EndOfStatement or EOF.
166 StringRef ParseStringToEndOfStatement();
168 bool ParseAssignment(StringRef Name);
170 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
171 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
174 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
175 /// and set \arg Res to the identifier contents.
176 bool ParseIdentifier(StringRef &Res);
178 // Directive Parsing.
179 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
180 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
181 bool ParseDirectiveFill(); // ".fill"
182 bool ParseDirectiveSpace(); // ".space"
183 bool ParseDirectiveSet(); // ".set"
184 bool ParseDirectiveOrg(); // ".org"
185 // ".align{,32}", ".p2align{,w,l}"
186 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
188 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
189 /// accepts a single symbol (which should be a label or an external).
190 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
191 bool ParseDirectiveELFType(); // ELF specific ".type"
193 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
195 bool ParseDirectiveAbort(); // ".abort"
196 bool ParseDirectiveInclude(); // ".include"
198 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
199 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
200 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
201 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
203 /// ParseEscapedString - Parse the current token as a string which may include
204 /// escaped characters and return the string contents.
205 bool ParseEscapedString(std::string &Data);
208 /// \brief Generic implementations of directive handling, etc. which is shared
209 /// (or the default, at least) for all assembler parser.
210 class GenericAsmParser : public MCAsmParserExtension {
211 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
212 void AddDirectiveHandler(StringRef Directive) {
213 getParser().AddDirectiveHandler(this, Directive,
214 HandleDirective<GenericAsmParser, Handler>);
218 GenericAsmParser() {}
220 AsmParser &getParser() {
221 return (AsmParser&) this->MCAsmParserExtension::getParser();
224 virtual void Initialize(MCAsmParser &Parser) {
225 // Call the base implementation.
226 this->MCAsmParserExtension::Initialize(Parser);
228 // Debugging directives.
229 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
230 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
231 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
234 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
246 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
247 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
248 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
250 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
251 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
252 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
254 void ParseUleb128(uint64_t Value);
255 void ParseSleb128(int64_t Value);
256 bool ParseDirectiveLEB128(StringRef, SMLoc);
263 extern MCAsmParserExtension *createDarwinAsmParser();
264 extern MCAsmParserExtension *createELFAsmParser();
268 enum { DEFAULT_ADDRSPACE = 0 };
270 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
271 MCStreamer &_Out, const MCAsmInfo &_MAI)
272 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
273 GenericParser(new GenericAsmParser), PlatformParser(0),
274 CurBuffer(0), MacrosEnabled(true) {
275 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
277 // Initialize the generic parser.
278 GenericParser->Initialize(*this);
280 // Initialize the platform / file format parser.
282 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
284 if (_MAI.hasSubsectionsViaSymbols()) {
285 PlatformParser = createDarwinAsmParser();
286 PlatformParser->Initialize(*this);
288 PlatformParser = createELFAsmParser();
289 PlatformParser->Initialize(*this);
293 AsmParser::~AsmParser() {
294 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
296 // Destroy any macros.
297 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
298 ie = MacroMap.end(); it != ie; ++it)
299 delete it->getValue();
301 delete PlatformParser;
302 delete GenericParser;
305 void AsmParser::PrintMacroInstantiations() {
306 // Print the active macro instantiation stack.
307 for (std::vector<MacroInstantiation*>::const_reverse_iterator
308 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
309 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
313 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
314 PrintMessage(L, Msg.str(), "warning");
315 PrintMacroInstantiations();
318 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
320 PrintMessage(L, Msg.str(), "error");
321 PrintMacroInstantiations();
325 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
326 const char *Type) const {
327 SrcMgr.PrintMessage(Loc, Msg, Type);
330 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
331 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
337 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
342 void AsmParser::JumpToLoc(SMLoc Loc) {
343 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
344 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
347 const AsmToken &AsmParser::Lex() {
348 const AsmToken *tok = &Lexer.Lex();
350 if (tok->is(AsmToken::Eof)) {
351 // If this is the end of an included file, pop the parent file off the
353 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
354 if (ParentIncludeLoc != SMLoc()) {
355 JumpToLoc(ParentIncludeLoc);
360 if (tok->is(AsmToken::Error))
361 Error(Lexer.getErrLoc(), Lexer.getErr());
366 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
367 // Create the initial section, if requested.
369 // FIXME: Target hook & command line option for initial section.
370 if (!NoInitialTextSection)
371 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
372 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
373 0, SectionKind::getText()));
379 AsmCond StartingCondState = TheCondState;
381 // While we have input, parse each statement.
382 while (Lexer.isNot(AsmToken::Eof)) {
383 if (!ParseStatement()) continue;
385 // We had an error, validate that one was emitted and recover by skipping to
387 assert(HadError && "Parse statement returned an error, but none emitted!");
388 EatToEndOfStatement();
391 if (TheCondState.TheCond != StartingCondState.TheCond ||
392 TheCondState.Ignore != StartingCondState.Ignore)
393 return TokError("unmatched .ifs or .elses");
395 // Check to see there are no empty DwarfFile slots.
396 const std::vector<MCDwarfFile *> &MCDwarfFiles =
397 getContext().getMCDwarfFiles();
398 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
399 if (!MCDwarfFiles[i])
400 TokError("unassigned file number: " + Twine(i) + " for .file directives");
403 // Finalize the output stream if there are no errors and if the client wants
405 if (!HadError && !NoFinalize)
411 void AsmParser::CheckForValidSection() {
412 if (!getStreamer().getCurrentSection()) {
413 TokError("expected section directive before assembly directive");
414 Out.SwitchSection(Ctx.getMachOSection(
416 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
417 0, SectionKind::getText()));
421 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
422 void AsmParser::EatToEndOfStatement() {
423 while (Lexer.isNot(AsmToken::EndOfStatement) &&
424 Lexer.isNot(AsmToken::Eof))
428 if (Lexer.is(AsmToken::EndOfStatement))
432 StringRef AsmParser::ParseStringToEndOfStatement() {
433 const char *Start = getTok().getLoc().getPointer();
435 while (Lexer.isNot(AsmToken::EndOfStatement) &&
436 Lexer.isNot(AsmToken::Eof))
439 const char *End = getTok().getLoc().getPointer();
440 return StringRef(Start, End - Start);
443 /// ParseParenExpr - Parse a paren expression and return it.
444 /// NOTE: This assumes the leading '(' has already been consumed.
446 /// parenexpr ::= expr)
448 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
449 if (ParseExpression(Res)) return true;
450 if (Lexer.isNot(AsmToken::RParen))
451 return TokError("expected ')' in parentheses expression");
452 EndLoc = Lexer.getLoc();
457 /// ParsePrimaryExpr - Parse a primary expression and return it.
458 /// primaryexpr ::= (parenexpr
459 /// primaryexpr ::= symbol
460 /// primaryexpr ::= number
461 /// primaryexpr ::= '.'
462 /// primaryexpr ::= ~,+,- primaryexpr
463 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
464 switch (Lexer.getKind()) {
466 return TokError("unknown token in expression");
467 case AsmToken::Exclaim:
468 Lex(); // Eat the operator.
469 if (ParsePrimaryExpr(Res, EndLoc))
471 Res = MCUnaryExpr::CreateLNot(Res, getContext());
473 case AsmToken::Dollar:
474 case AsmToken::String:
475 case AsmToken::Identifier: {
476 EndLoc = Lexer.getLoc();
478 StringRef Identifier;
479 if (ParseIdentifier(Identifier))
482 // This is a symbol reference.
483 std::pair<StringRef, StringRef> Split = Identifier.split('@');
484 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
486 // Mark the symbol as used in an expression.
487 Sym->setUsedInExpr(true);
489 // Lookup the symbol variant if used.
490 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
491 if (Split.first.size() != Identifier.size())
492 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
494 // If this is an absolute variable reference, substitute it now to preserve
495 // semantics in the face of reassignment.
496 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
498 return Error(EndLoc, "unexpected modified on variable reference");
500 Res = Sym->getVariableValue();
504 // Otherwise create a symbol ref.
505 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
508 case AsmToken::Integer: {
509 SMLoc Loc = getTok().getLoc();
510 int64_t IntVal = getTok().getIntVal();
511 Res = MCConstantExpr::Create(IntVal, getContext());
512 EndLoc = Lexer.getLoc();
514 // Look for 'b' or 'f' following an Integer as a directional label
515 if (Lexer.getKind() == AsmToken::Identifier) {
516 StringRef IDVal = getTok().getString();
517 if (IDVal == "f" || IDVal == "b"){
518 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
519 IDVal == "f" ? 1 : 0);
520 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
522 if(IDVal == "b" && Sym->isUndefined())
523 return Error(Loc, "invalid reference to undefined symbol");
524 EndLoc = Lexer.getLoc();
525 Lex(); // Eat identifier.
530 case AsmToken::Dot: {
531 // This is a '.' reference, which references the current PC. Emit a
532 // temporary label to the streamer and refer to it.
533 MCSymbol *Sym = Ctx.CreateTempSymbol();
535 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
536 EndLoc = Lexer.getLoc();
537 Lex(); // Eat identifier.
541 case AsmToken::LParen:
542 Lex(); // Eat the '('.
543 return ParseParenExpr(Res, EndLoc);
544 case AsmToken::Minus:
545 Lex(); // Eat the operator.
546 if (ParsePrimaryExpr(Res, EndLoc))
548 Res = MCUnaryExpr::CreateMinus(Res, getContext());
551 Lex(); // Eat the operator.
552 if (ParsePrimaryExpr(Res, EndLoc))
554 Res = MCUnaryExpr::CreatePlus(Res, getContext());
556 case AsmToken::Tilde:
557 Lex(); // Eat the operator.
558 if (ParsePrimaryExpr(Res, EndLoc))
560 Res = MCUnaryExpr::CreateNot(Res, getContext());
565 bool AsmParser::ParseExpression(const MCExpr *&Res) {
567 return ParseExpression(Res, EndLoc);
570 /// ParseExpression - Parse an expression and return it.
572 /// expr ::= expr +,- expr -> lowest.
573 /// expr ::= expr |,^,&,! expr -> middle.
574 /// expr ::= expr *,/,%,<<,>> expr -> highest.
575 /// expr ::= primaryexpr
577 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
578 // Parse the expression.
580 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
583 // Try to constant fold it up front, if possible.
585 if (Res->EvaluateAsAbsolute(Value))
586 Res = MCConstantExpr::Create(Value, getContext());
591 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
593 return ParseParenExpr(Res, EndLoc) ||
594 ParseBinOpRHS(1, Res, EndLoc);
597 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
600 SMLoc StartLoc = Lexer.getLoc();
601 if (ParseExpression(Expr))
604 if (!Expr->EvaluateAsAbsolute(Res))
605 return Error(StartLoc, "expected absolute expression");
610 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
611 MCBinaryExpr::Opcode &Kind) {
614 return 0; // not a binop.
616 // Lowest Precedence: &&, ||
617 case AsmToken::AmpAmp:
618 Kind = MCBinaryExpr::LAnd;
620 case AsmToken::PipePipe:
621 Kind = MCBinaryExpr::LOr;
624 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
626 Kind = MCBinaryExpr::Add;
628 case AsmToken::Minus:
629 Kind = MCBinaryExpr::Sub;
631 case AsmToken::EqualEqual:
632 Kind = MCBinaryExpr::EQ;
634 case AsmToken::ExclaimEqual:
635 case AsmToken::LessGreater:
636 Kind = MCBinaryExpr::NE;
639 Kind = MCBinaryExpr::LT;
641 case AsmToken::LessEqual:
642 Kind = MCBinaryExpr::LTE;
644 case AsmToken::Greater:
645 Kind = MCBinaryExpr::GT;
647 case AsmToken::GreaterEqual:
648 Kind = MCBinaryExpr::GTE;
651 // Intermediate Precedence: |, &, ^
653 // FIXME: gas seems to support '!' as an infix operator?
655 Kind = MCBinaryExpr::Or;
657 case AsmToken::Caret:
658 Kind = MCBinaryExpr::Xor;
661 Kind = MCBinaryExpr::And;
664 // Highest Precedence: *, /, %, <<, >>
666 Kind = MCBinaryExpr::Mul;
668 case AsmToken::Slash:
669 Kind = MCBinaryExpr::Div;
671 case AsmToken::Percent:
672 Kind = MCBinaryExpr::Mod;
674 case AsmToken::LessLess:
675 Kind = MCBinaryExpr::Shl;
677 case AsmToken::GreaterGreater:
678 Kind = MCBinaryExpr::Shr;
684 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
685 /// Res contains the LHS of the expression on input.
686 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
689 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
690 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
692 // If the next token is lower precedence than we are allowed to eat, return
693 // successfully with what we ate already.
694 if (TokPrec < Precedence)
699 // Eat the next primary expression.
701 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
703 // If BinOp binds less tightly with RHS than the operator after RHS, let
704 // the pending operator take RHS as its LHS.
705 MCBinaryExpr::Opcode Dummy;
706 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
707 if (TokPrec < NextTokPrec) {
708 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
711 // Merge LHS and RHS according to operator.
712 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
720 /// ::= EndOfStatement
721 /// ::= Label* Directive ...Operands... EndOfStatement
722 /// ::= Label* Identifier OperandList* EndOfStatement
723 bool AsmParser::ParseStatement() {
724 if (Lexer.is(AsmToken::EndOfStatement)) {
730 // Statements always start with an identifier.
731 AsmToken ID = getTok();
732 SMLoc IDLoc = ID.getLoc();
734 int64_t LocalLabelVal = -1;
735 // GUESS allow an integer followed by a ':' as a directional local label
736 if (Lexer.is(AsmToken::Integer)) {
737 LocalLabelVal = getTok().getIntVal();
738 if (LocalLabelVal < 0) {
739 if (!TheCondState.Ignore)
740 return TokError("unexpected token at start of statement");
744 IDVal = getTok().getString();
745 Lex(); // Consume the integer token to be used as an identifier token.
746 if (Lexer.getKind() != AsmToken::Colon) {
747 if (!TheCondState.Ignore)
748 return TokError("unexpected token at start of statement");
752 else if (ParseIdentifier(IDVal)) {
753 if (!TheCondState.Ignore)
754 return TokError("unexpected token at start of statement");
758 // Handle conditional assembly here before checking for skipping. We
759 // have to do this so that .endif isn't skipped in a ".if 0" block for
762 return ParseDirectiveIf(IDLoc);
763 if (IDVal == ".elseif")
764 return ParseDirectiveElseIf(IDLoc);
765 if (IDVal == ".else")
766 return ParseDirectiveElse(IDLoc);
767 if (IDVal == ".endif")
768 return ParseDirectiveEndIf(IDLoc);
770 // If we are in a ".if 0" block, ignore this statement.
771 if (TheCondState.Ignore) {
772 EatToEndOfStatement();
776 // FIXME: Recurse on local labels?
778 // See what kind of statement we have.
779 switch (Lexer.getKind()) {
780 case AsmToken::Colon: {
781 CheckForValidSection();
783 // identifier ':' -> Label.
786 // Diagnose attempt to use a variable as a label.
788 // FIXME: Diagnostics. Note the location of the definition as a label.
789 // FIXME: This doesn't diagnose assignment to a symbol which has been
790 // implicitly marked as external.
792 if (LocalLabelVal == -1)
793 Sym = getContext().GetOrCreateSymbol(IDVal);
795 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
796 if (!Sym->isUndefined() || Sym->isVariable())
797 return Error(IDLoc, "invalid symbol redefinition");
802 // Consume any end of statement token, if present, to avoid spurious
803 // AddBlankLine calls().
804 if (Lexer.is(AsmToken::EndOfStatement)) {
806 if (Lexer.is(AsmToken::Eof))
810 return ParseStatement();
813 case AsmToken::Equal:
814 // identifier '=' ... -> assignment statement
817 return ParseAssignment(IDVal);
819 default: // Normal instruction or directive.
823 // If macros are enabled, check to see if this is a macro instantiation.
825 if (const Macro *M = MacroMap.lookup(IDVal))
826 return HandleMacroEntry(IDVal, IDLoc, M);
828 // Otherwise, we have a normal instruction or directive.
829 if (IDVal[0] == '.') {
830 // Assembler features
832 return ParseDirectiveSet();
836 if (IDVal == ".ascii")
837 return ParseDirectiveAscii(false);
838 if (IDVal == ".asciz")
839 return ParseDirectiveAscii(true);
841 if (IDVal == ".byte")
842 return ParseDirectiveValue(1);
843 if (IDVal == ".short")
844 return ParseDirectiveValue(2);
845 if (IDVal == ".long")
846 return ParseDirectiveValue(4);
847 if (IDVal == ".quad")
848 return ParseDirectiveValue(8);
850 if (IDVal == ".align") {
851 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
852 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
854 if (IDVal == ".align32") {
855 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
856 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
858 if (IDVal == ".balign")
859 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
860 if (IDVal == ".balignw")
861 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
862 if (IDVal == ".balignl")
863 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
864 if (IDVal == ".p2align")
865 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
866 if (IDVal == ".p2alignw")
867 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
868 if (IDVal == ".p2alignl")
869 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
872 return ParseDirectiveOrg();
874 if (IDVal == ".fill")
875 return ParseDirectiveFill();
876 if (IDVal == ".space")
877 return ParseDirectiveSpace();
879 // Symbol attribute directives
881 if (IDVal == ".globl" || IDVal == ".global")
882 return ParseDirectiveSymbolAttribute(MCSA_Global);
883 if (IDVal == ".hidden")
884 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
885 if (IDVal == ".indirect_symbol")
886 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
887 if (IDVal == ".internal")
888 return ParseDirectiveSymbolAttribute(MCSA_Internal);
889 if (IDVal == ".lazy_reference")
890 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
891 if (IDVal == ".no_dead_strip")
892 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
893 if (IDVal == ".private_extern")
894 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
895 if (IDVal == ".protected")
896 return ParseDirectiveSymbolAttribute(MCSA_Protected);
897 if (IDVal == ".reference")
898 return ParseDirectiveSymbolAttribute(MCSA_Reference);
899 if (IDVal == ".type")
900 return ParseDirectiveELFType();
901 if (IDVal == ".weak")
902 return ParseDirectiveSymbolAttribute(MCSA_Weak);
903 if (IDVal == ".weak_definition")
904 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
905 if (IDVal == ".weak_reference")
906 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
907 if (IDVal == ".weak_def_can_be_hidden")
908 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
910 if (IDVal == ".comm")
911 return ParseDirectiveComm(/*IsLocal=*/false);
912 if (IDVal == ".lcomm")
913 return ParseDirectiveComm(/*IsLocal=*/true);
915 if (IDVal == ".abort")
916 return ParseDirectiveAbort();
917 if (IDVal == ".include")
918 return ParseDirectiveInclude();
920 // Look up the handler in the handler table.
921 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
922 DirectiveMap.lookup(IDVal);
924 return (*Handler.second)(Handler.first, IDVal, IDLoc);
926 // Target hook for parsing target specific directives.
927 if (!getTargetParser().ParseDirective(ID))
930 Warning(IDLoc, "ignoring directive for now");
931 EatToEndOfStatement();
935 CheckForValidSection();
937 // Canonicalize the opcode to lower case.
938 SmallString<128> Opcode;
939 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
940 Opcode.push_back(tolower(IDVal[i]));
942 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
943 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
946 // Dump the parsed representation, if requested.
947 if (getShowParsedOperands()) {
948 SmallString<256> Str;
949 raw_svector_ostream OS(Str);
950 OS << "parsed instruction: [";
951 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
954 ParsedOperands[i]->dump(OS);
958 PrintMessage(IDLoc, OS.str(), "note");
961 // If parsing succeeded, match the instruction.
964 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
965 // Emit the instruction on success.
966 Out.EmitInstruction(Inst);
971 // Free any parsed operands.
972 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
973 delete ParsedOperands[i];
975 // Don't skip the rest of the line, the instruction parser is responsible for
980 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
981 const std::vector<std::vector<AsmToken> > &A)
982 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
984 // Macro instantiation is lexical, unfortunately. We construct a new buffer
985 // to hold the macro body with substitutions.
986 SmallString<256> Buf;
987 raw_svector_ostream OS(Buf);
989 StringRef Body = M->Body;
990 while (!Body.empty()) {
991 // Scan for the next substitution.
992 std::size_t End = Body.size(), Pos = 0;
993 for (; Pos != End; ++Pos) {
994 // Check for a substitution or escape.
995 if (Body[Pos] != '$' || Pos + 1 == End)
998 char Next = Body[Pos + 1];
999 if (Next == '$' || Next == 'n' || isdigit(Next))
1004 OS << Body.slice(0, Pos);
1006 // Check if we reached the end.
1010 switch (Body[Pos+1]) {
1016 // $n => number of arguments
1021 // $[0-9] => argument
1023 // Missing arguments are ignored.
1024 unsigned Index = Body[Pos+1] - '0';
1025 if (Index >= A.size())
1028 // Otherwise substitute with the token values, with spaces eliminated.
1029 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1030 ie = A[Index].end(); it != ie; ++it)
1031 OS << it->getString();
1036 // Update the scan point.
1037 Body = Body.substr(Pos + 2);
1040 // We include the .endmacro in the buffer as our queue to exit the macro
1042 OS << ".endmacro\n";
1044 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1047 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1049 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1050 // this, although we should protect against infinite loops.
1051 if (ActiveMacros.size() == 20)
1052 return TokError("macros cannot be nested more than 20 levels deep");
1054 // Parse the macro instantiation arguments.
1055 std::vector<std::vector<AsmToken> > MacroArguments;
1056 MacroArguments.push_back(std::vector<AsmToken>());
1057 unsigned ParenLevel = 0;
1059 if (Lexer.is(AsmToken::Eof))
1060 return TokError("unexpected token in macro instantiation");
1061 if (Lexer.is(AsmToken::EndOfStatement))
1064 // If we aren't inside parentheses and this is a comma, start a new token
1066 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1067 MacroArguments.push_back(std::vector<AsmToken>());
1069 // Adjust the current parentheses level.
1070 if (Lexer.is(AsmToken::LParen))
1072 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1075 // Append the token to the current argument list.
1076 MacroArguments.back().push_back(getTok());
1081 // Create the macro instantiation object and add to the current macro
1082 // instantiation stack.
1083 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1086 ActiveMacros.push_back(MI);
1088 // Jump to the macro instantiation and prime the lexer.
1089 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1090 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1096 void AsmParser::HandleMacroExit() {
1097 // Jump to the EndOfStatement we should return to, and consume it.
1098 JumpToLoc(ActiveMacros.back()->ExitLoc);
1101 // Pop the instantiation entry.
1102 delete ActiveMacros.back();
1103 ActiveMacros.pop_back();
1106 bool AsmParser::ParseAssignment(StringRef Name) {
1107 // FIXME: Use better location, we should use proper tokens.
1108 SMLoc EqualLoc = Lexer.getLoc();
1110 const MCExpr *Value;
1111 if (ParseExpression(Value))
1114 if (Lexer.isNot(AsmToken::EndOfStatement))
1115 return TokError("unexpected token in assignment");
1117 // Eat the end of statement marker.
1120 // Validate that the LHS is allowed to be a variable (either it has not been
1121 // used as a symbol, or it is an absolute symbol).
1122 MCSymbol *Sym = getContext().LookupSymbol(Name);
1124 // Diagnose assignment to a label.
1126 // FIXME: Diagnostics. Note the location of the definition as a label.
1127 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1128 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1129 ; // Allow redefinitions of undefined symbols only used in directives.
1130 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1131 return Error(EqualLoc, "redefinition of '" + Name + "'");
1132 else if (!Sym->isVariable())
1133 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1134 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1135 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1138 Sym = getContext().GetOrCreateSymbol(Name);
1140 // FIXME: Handle '.'.
1142 Sym->setUsedInExpr(true);
1144 // Do the assignment.
1145 Out.EmitAssignment(Sym, Value);
1150 /// ParseIdentifier:
1153 bool AsmParser::ParseIdentifier(StringRef &Res) {
1154 // The assembler has relaxed rules for accepting identifiers, in particular we
1155 // allow things like '.globl $foo', which would normally be separate
1156 // tokens. At this level, we have already lexed so we cannot (currently)
1157 // handle this as a context dependent token, instead we detect adjacent tokens
1158 // and return the combined identifier.
1159 if (Lexer.is(AsmToken::Dollar)) {
1160 SMLoc DollarLoc = getLexer().getLoc();
1162 // Consume the dollar sign, and check for a following identifier.
1164 if (Lexer.isNot(AsmToken::Identifier))
1167 // We have a '$' followed by an identifier, make sure they are adjacent.
1168 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1171 // Construct the joined identifier and consume the token.
1172 Res = StringRef(DollarLoc.getPointer(),
1173 getTok().getIdentifier().size() + 1);
1178 if (Lexer.isNot(AsmToken::Identifier) &&
1179 Lexer.isNot(AsmToken::String))
1182 Res = getTok().getIdentifier();
1184 Lex(); // Consume the identifier token.
1189 /// ParseDirectiveSet:
1190 /// ::= .set identifier ',' expression
1191 bool AsmParser::ParseDirectiveSet() {
1194 if (ParseIdentifier(Name))
1195 return TokError("expected identifier after '.set' directive");
1197 if (getLexer().isNot(AsmToken::Comma))
1198 return TokError("unexpected token in '.set'");
1201 return ParseAssignment(Name);
1204 bool AsmParser::ParseEscapedString(std::string &Data) {
1205 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1208 StringRef Str = getTok().getStringContents();
1209 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1210 if (Str[i] != '\\') {
1215 // Recognize escaped characters. Note that this escape semantics currently
1216 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1219 return TokError("unexpected backslash at end of string");
1221 // Recognize octal sequences.
1222 if ((unsigned) (Str[i] - '0') <= 7) {
1223 // Consume up to three octal characters.
1224 unsigned Value = Str[i] - '0';
1226 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1228 Value = Value * 8 + (Str[i] - '0');
1230 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1232 Value = Value * 8 + (Str[i] - '0');
1237 return TokError("invalid octal escape sequence (out of range)");
1239 Data += (unsigned char) Value;
1243 // Otherwise recognize individual escapes.
1246 // Just reject invalid escape sequences for now.
1247 return TokError("invalid escape sequence (unrecognized character)");
1249 case 'b': Data += '\b'; break;
1250 case 'f': Data += '\f'; break;
1251 case 'n': Data += '\n'; break;
1252 case 'r': Data += '\r'; break;
1253 case 't': Data += '\t'; break;
1254 case '"': Data += '"'; break;
1255 case '\\': Data += '\\'; break;
1262 /// ParseDirectiveAscii:
1263 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1264 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1265 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1266 CheckForValidSection();
1269 if (getLexer().isNot(AsmToken::String))
1270 return TokError("expected string in '.ascii' or '.asciz' directive");
1273 if (ParseEscapedString(Data))
1276 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1278 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1282 if (getLexer().is(AsmToken::EndOfStatement))
1285 if (getLexer().isNot(AsmToken::Comma))
1286 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1295 /// ParseDirectiveValue
1296 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1297 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1298 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1299 CheckForValidSection();
1302 const MCExpr *Value;
1303 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1304 if (ParseExpression(Value))
1307 // Special case constant expressions to match code generator.
1308 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1309 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1311 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1313 if (getLexer().is(AsmToken::EndOfStatement))
1316 // FIXME: Improve diagnostic.
1317 if (getLexer().isNot(AsmToken::Comma))
1318 return TokError("unexpected token in directive");
1327 /// ParseDirectiveSpace
1328 /// ::= .space expression [ , expression ]
1329 bool AsmParser::ParseDirectiveSpace() {
1330 CheckForValidSection();
1333 if (ParseAbsoluteExpression(NumBytes))
1336 int64_t FillExpr = 0;
1337 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1338 if (getLexer().isNot(AsmToken::Comma))
1339 return TokError("unexpected token in '.space' directive");
1342 if (ParseAbsoluteExpression(FillExpr))
1345 if (getLexer().isNot(AsmToken::EndOfStatement))
1346 return TokError("unexpected token in '.space' directive");
1352 return TokError("invalid number of bytes in '.space' directive");
1354 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1355 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1360 /// ParseDirectiveFill
1361 /// ::= .fill expression , expression , expression
1362 bool AsmParser::ParseDirectiveFill() {
1363 CheckForValidSection();
1366 if (ParseAbsoluteExpression(NumValues))
1369 if (getLexer().isNot(AsmToken::Comma))
1370 return TokError("unexpected token in '.fill' directive");
1374 if (ParseAbsoluteExpression(FillSize))
1377 if (getLexer().isNot(AsmToken::Comma))
1378 return TokError("unexpected token in '.fill' directive");
1382 if (ParseAbsoluteExpression(FillExpr))
1385 if (getLexer().isNot(AsmToken::EndOfStatement))
1386 return TokError("unexpected token in '.fill' directive");
1390 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1391 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1393 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1394 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1399 /// ParseDirectiveOrg
1400 /// ::= .org expression [ , expression ]
1401 bool AsmParser::ParseDirectiveOrg() {
1402 CheckForValidSection();
1404 const MCExpr *Offset;
1405 if (ParseExpression(Offset))
1408 // Parse optional fill expression.
1409 int64_t FillExpr = 0;
1410 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1411 if (getLexer().isNot(AsmToken::Comma))
1412 return TokError("unexpected token in '.org' directive");
1415 if (ParseAbsoluteExpression(FillExpr))
1418 if (getLexer().isNot(AsmToken::EndOfStatement))
1419 return TokError("unexpected token in '.org' directive");
1424 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1425 // has to be relative to the current section.
1426 getStreamer().EmitValueToOffset(Offset, FillExpr);
1431 /// ParseDirectiveAlign
1432 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1433 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1434 CheckForValidSection();
1436 SMLoc AlignmentLoc = getLexer().getLoc();
1438 if (ParseAbsoluteExpression(Alignment))
1442 bool HasFillExpr = false;
1443 int64_t FillExpr = 0;
1444 int64_t MaxBytesToFill = 0;
1445 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1446 if (getLexer().isNot(AsmToken::Comma))
1447 return TokError("unexpected token in directive");
1450 // The fill expression can be omitted while specifying a maximum number of
1451 // alignment bytes, e.g:
1453 if (getLexer().isNot(AsmToken::Comma)) {
1455 if (ParseAbsoluteExpression(FillExpr))
1459 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1460 if (getLexer().isNot(AsmToken::Comma))
1461 return TokError("unexpected token in directive");
1464 MaxBytesLoc = getLexer().getLoc();
1465 if (ParseAbsoluteExpression(MaxBytesToFill))
1468 if (getLexer().isNot(AsmToken::EndOfStatement))
1469 return TokError("unexpected token in directive");
1478 // Compute alignment in bytes.
1480 // FIXME: Diagnose overflow.
1481 if (Alignment >= 32) {
1482 Error(AlignmentLoc, "invalid alignment value");
1486 Alignment = 1ULL << Alignment;
1489 // Diagnose non-sensical max bytes to align.
1490 if (MaxBytesLoc.isValid()) {
1491 if (MaxBytesToFill < 1) {
1492 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1493 "many bytes, ignoring maximum bytes expression");
1497 if (MaxBytesToFill >= Alignment) {
1498 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1504 // Check whether we should use optimal code alignment for this .align
1507 // FIXME: This should be using a target hook.
1508 bool UseCodeAlign = false;
1509 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1510 getStreamer().getCurrentSection()))
1511 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1512 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1513 ValueSize == 1 && UseCodeAlign) {
1514 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1516 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1517 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1524 /// ParseDirectiveSymbolAttribute
1525 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1526 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1527 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1531 if (ParseIdentifier(Name))
1532 return TokError("expected identifier in directive");
1534 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1536 getStreamer().EmitSymbolAttribute(Sym, Attr);
1538 if (getLexer().is(AsmToken::EndOfStatement))
1541 if (getLexer().isNot(AsmToken::Comma))
1542 return TokError("unexpected token in directive");
1551 /// ParseDirectiveELFType
1552 /// ::= .type identifier , @attribute
1553 bool AsmParser::ParseDirectiveELFType() {
1555 if (ParseIdentifier(Name))
1556 return TokError("expected identifier in directive");
1558 // Handle the identifier as the key symbol.
1559 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1561 if (getLexer().isNot(AsmToken::Comma))
1562 return TokError("unexpected token in '.type' directive");
1565 if (getLexer().isNot(AsmToken::At))
1566 return TokError("expected '@' before type");
1572 TypeLoc = getLexer().getLoc();
1573 if (ParseIdentifier(Type))
1574 return TokError("expected symbol type in directive");
1576 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1577 .Case("function", MCSA_ELF_TypeFunction)
1578 .Case("object", MCSA_ELF_TypeObject)
1579 .Case("tls_object", MCSA_ELF_TypeTLS)
1580 .Case("common", MCSA_ELF_TypeCommon)
1581 .Case("notype", MCSA_ELF_TypeNoType)
1582 .Default(MCSA_Invalid);
1584 if (Attr == MCSA_Invalid)
1585 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1587 if (getLexer().isNot(AsmToken::EndOfStatement))
1588 return TokError("unexpected token in '.type' directive");
1592 getStreamer().EmitSymbolAttribute(Sym, Attr);
1597 /// ParseDirectiveComm
1598 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1599 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1600 CheckForValidSection();
1602 SMLoc IDLoc = getLexer().getLoc();
1604 if (ParseIdentifier(Name))
1605 return TokError("expected identifier in directive");
1607 // Handle the identifier as the key symbol.
1608 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1610 if (getLexer().isNot(AsmToken::Comma))
1611 return TokError("unexpected token in directive");
1615 SMLoc SizeLoc = getLexer().getLoc();
1616 if (ParseAbsoluteExpression(Size))
1619 int64_t Pow2Alignment = 0;
1620 SMLoc Pow2AlignmentLoc;
1621 if (getLexer().is(AsmToken::Comma)) {
1623 Pow2AlignmentLoc = getLexer().getLoc();
1624 if (ParseAbsoluteExpression(Pow2Alignment))
1627 // If this target takes alignments in bytes (not log) validate and convert.
1628 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1629 if (!isPowerOf2_64(Pow2Alignment))
1630 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1631 Pow2Alignment = Log2_64(Pow2Alignment);
1635 if (getLexer().isNot(AsmToken::EndOfStatement))
1636 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1640 // NOTE: a size of zero for a .comm should create a undefined symbol
1641 // but a size of .lcomm creates a bss symbol of size zero.
1643 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1644 "be less than zero");
1646 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1647 // may internally end up wanting an alignment in bytes.
1648 // FIXME: Diagnose overflow.
1649 if (Pow2Alignment < 0)
1650 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1651 "alignment, can't be less than zero");
1653 if (!Sym->isUndefined())
1654 return Error(IDLoc, "invalid symbol redefinition");
1656 // '.lcomm' is equivalent to '.zerofill'.
1657 // Create the Symbol as a common or local common with Size and Pow2Alignment
1659 getStreamer().EmitZerofill(Ctx.getMachOSection(
1660 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1661 0, SectionKind::getBSS()),
1662 Sym, Size, 1 << Pow2Alignment);
1666 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1670 /// ParseDirectiveAbort
1671 /// ::= .abort [... message ...]
1672 bool AsmParser::ParseDirectiveAbort() {
1673 // FIXME: Use loc from directive.
1674 SMLoc Loc = getLexer().getLoc();
1676 StringRef Str = ParseStringToEndOfStatement();
1677 if (getLexer().isNot(AsmToken::EndOfStatement))
1678 return TokError("unexpected token in '.abort' directive");
1683 Error(Loc, ".abort detected. Assembly stopping.");
1685 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1686 // FIXME: Actually abort assembly here.
1691 /// ParseDirectiveInclude
1692 /// ::= .include "filename"
1693 bool AsmParser::ParseDirectiveInclude() {
1694 if (getLexer().isNot(AsmToken::String))
1695 return TokError("expected string in '.include' directive");
1697 std::string Filename = getTok().getString();
1698 SMLoc IncludeLoc = getLexer().getLoc();
1701 if (getLexer().isNot(AsmToken::EndOfStatement))
1702 return TokError("unexpected token in '.include' directive");
1704 // Strip the quotes.
1705 Filename = Filename.substr(1, Filename.size()-2);
1707 // Attempt to switch the lexer to the included file before consuming the end
1708 // of statement to avoid losing it when we switch.
1709 if (EnterIncludeFile(Filename)) {
1710 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1717 /// ParseDirectiveIf
1718 /// ::= .if expression
1719 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1720 TheCondStack.push_back(TheCondState);
1721 TheCondState.TheCond = AsmCond::IfCond;
1722 if(TheCondState.Ignore) {
1723 EatToEndOfStatement();
1727 if (ParseAbsoluteExpression(ExprValue))
1730 if (getLexer().isNot(AsmToken::EndOfStatement))
1731 return TokError("unexpected token in '.if' directive");
1735 TheCondState.CondMet = ExprValue;
1736 TheCondState.Ignore = !TheCondState.CondMet;
1742 /// ParseDirectiveElseIf
1743 /// ::= .elseif expression
1744 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1745 if (TheCondState.TheCond != AsmCond::IfCond &&
1746 TheCondState.TheCond != AsmCond::ElseIfCond)
1747 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1749 TheCondState.TheCond = AsmCond::ElseIfCond;
1751 bool LastIgnoreState = false;
1752 if (!TheCondStack.empty())
1753 LastIgnoreState = TheCondStack.back().Ignore;
1754 if (LastIgnoreState || TheCondState.CondMet) {
1755 TheCondState.Ignore = true;
1756 EatToEndOfStatement();
1760 if (ParseAbsoluteExpression(ExprValue))
1763 if (getLexer().isNot(AsmToken::EndOfStatement))
1764 return TokError("unexpected token in '.elseif' directive");
1767 TheCondState.CondMet = ExprValue;
1768 TheCondState.Ignore = !TheCondState.CondMet;
1774 /// ParseDirectiveElse
1776 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1777 if (getLexer().isNot(AsmToken::EndOfStatement))
1778 return TokError("unexpected token in '.else' directive");
1782 if (TheCondState.TheCond != AsmCond::IfCond &&
1783 TheCondState.TheCond != AsmCond::ElseIfCond)
1784 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1786 TheCondState.TheCond = AsmCond::ElseCond;
1787 bool LastIgnoreState = false;
1788 if (!TheCondStack.empty())
1789 LastIgnoreState = TheCondStack.back().Ignore;
1790 if (LastIgnoreState || TheCondState.CondMet)
1791 TheCondState.Ignore = true;
1793 TheCondState.Ignore = false;
1798 /// ParseDirectiveEndIf
1800 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1801 if (getLexer().isNot(AsmToken::EndOfStatement))
1802 return TokError("unexpected token in '.endif' directive");
1806 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1807 TheCondStack.empty())
1808 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1810 if (!TheCondStack.empty()) {
1811 TheCondState = TheCondStack.back();
1812 TheCondStack.pop_back();
1818 /// ParseDirectiveFile
1819 /// ::= .file [number] string
1820 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1821 // FIXME: I'm not sure what this is.
1822 int64_t FileNumber = -1;
1823 SMLoc FileNumberLoc = getLexer().getLoc();
1824 if (getLexer().is(AsmToken::Integer)) {
1825 FileNumber = getTok().getIntVal();
1829 return TokError("file number less than one");
1832 if (getLexer().isNot(AsmToken::String))
1833 return TokError("unexpected token in '.file' directive");
1835 StringRef Filename = getTok().getString();
1836 Filename = Filename.substr(1, Filename.size()-2);
1839 if (getLexer().isNot(AsmToken::EndOfStatement))
1840 return TokError("unexpected token in '.file' directive");
1842 if (FileNumber == -1)
1843 getStreamer().EmitFileDirective(Filename);
1845 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1846 Error(FileNumberLoc, "file number already allocated");
1847 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1853 /// ParseDirectiveLine
1854 /// ::= .line [number]
1855 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1856 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1857 if (getLexer().isNot(AsmToken::Integer))
1858 return TokError("unexpected token in '.line' directive");
1860 int64_t LineNumber = getTok().getIntVal();
1864 // FIXME: Do something with the .line.
1867 if (getLexer().isNot(AsmToken::EndOfStatement))
1868 return TokError("unexpected token in '.line' directive");
1874 /// ParseDirectiveLoc
1875 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1876 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1877 /// The first number is a file number, must have been previously assigned with
1878 /// a .file directive, the second number is the line number and optionally the
1879 /// third number is a column position (zero if not specified). The remaining
1880 /// optional items are .loc sub-directives.
1881 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1883 if (getLexer().isNot(AsmToken::Integer))
1884 return TokError("unexpected token in '.loc' directive");
1885 int64_t FileNumber = getTok().getIntVal();
1887 return TokError("file number less than one in '.loc' directive");
1888 if (!getContext().ValidateDwarfFileNumber(FileNumber))
1889 return TokError("unassigned file number in '.loc' directive");
1892 int64_t LineNumber = 0;
1893 if (getLexer().is(AsmToken::Integer)) {
1894 LineNumber = getTok().getIntVal();
1896 return TokError("line number less than one in '.loc' directive");
1900 int64_t ColumnPos = 0;
1901 if (getLexer().is(AsmToken::Integer)) {
1902 ColumnPos = getTok().getIntVal();
1904 return TokError("column position less than zero in '.loc' directive");
1910 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1912 if (getLexer().is(AsmToken::EndOfStatement))
1916 SMLoc Loc = getTok().getLoc();
1917 if (getParser().ParseIdentifier(Name))
1918 return TokError("unexpected token in '.loc' directive");
1920 if (Name == "basic_block")
1921 Flags |= DWARF2_FLAG_BASIC_BLOCK;
1922 else if (Name == "prologue_end")
1923 Flags |= DWARF2_FLAG_PROLOGUE_END;
1924 else if (Name == "epilogue_begin")
1925 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
1926 else if (Name == "is_stmt") {
1927 SMLoc Loc = getTok().getLoc();
1928 const MCExpr *Value;
1929 if (getParser().ParseExpression(Value))
1931 // The expression must be the constant 0 or 1.
1932 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1933 int Value = MCE->getValue();
1935 Flags &= ~DWARF2_FLAG_IS_STMT;
1936 else if (Value == 1)
1937 Flags |= DWARF2_FLAG_IS_STMT;
1939 return Error(Loc, "is_stmt value not 0 or 1");
1942 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
1945 else if (Name == "isa") {
1946 SMLoc Loc = getTok().getLoc();
1947 const MCExpr *Value;
1948 if (getParser().ParseExpression(Value))
1950 // The expression must be a constant greater or equal to 0.
1951 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1952 int Value = MCE->getValue();
1954 return Error(Loc, "isa number less than zero");
1958 return Error(Loc, "isa number not a constant value");
1962 return Error(Loc, "unknown sub-directive in '.loc' directive");
1965 if (getLexer().is(AsmToken::EndOfStatement))
1970 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
1975 /// ParseDirectiveMacrosOnOff
1978 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
1979 SMLoc DirectiveLoc) {
1980 if (getLexer().isNot(AsmToken::EndOfStatement))
1981 return Error(getLexer().getLoc(),
1982 "unexpected token in '" + Directive + "' directive");
1984 getParser().MacrosEnabled = Directive == ".macros_on";
1989 /// ParseDirectiveMacro
1991 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
1992 SMLoc DirectiveLoc) {
1994 if (getParser().ParseIdentifier(Name))
1995 return TokError("expected identifier in directive");
1997 if (getLexer().isNot(AsmToken::EndOfStatement))
1998 return TokError("unexpected token in '.macro' directive");
2000 // Eat the end of statement.
2003 AsmToken EndToken, StartToken = getTok();
2005 // Lex the macro definition.
2007 // Check whether we have reached the end of the file.
2008 if (getLexer().is(AsmToken::Eof))
2009 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2011 // Otherwise, check whether we have reach the .endmacro.
2012 if (getLexer().is(AsmToken::Identifier) &&
2013 (getTok().getIdentifier() == ".endm" ||
2014 getTok().getIdentifier() == ".endmacro")) {
2015 EndToken = getTok();
2017 if (getLexer().isNot(AsmToken::EndOfStatement))
2018 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2023 // Otherwise, scan til the end of the statement.
2024 getParser().EatToEndOfStatement();
2027 if (getParser().MacroMap.lookup(Name)) {
2028 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2031 const char *BodyStart = StartToken.getLoc().getPointer();
2032 const char *BodyEnd = EndToken.getLoc().getPointer();
2033 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2034 getParser().MacroMap[Name] = new Macro(Name, Body);
2038 /// ParseDirectiveEndMacro
2041 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2042 SMLoc DirectiveLoc) {
2043 if (getLexer().isNot(AsmToken::EndOfStatement))
2044 return TokError("unexpected token in '" + Directive + "' directive");
2046 // If we are inside a macro instantiation, terminate the current
2048 if (!getParser().ActiveMacros.empty()) {
2049 getParser().HandleMacroExit();
2053 // Otherwise, this .endmacro is a stray entry in the file; well formed
2054 // .endmacro directives are handled during the macro definition parsing.
2055 return TokError("unexpected '" + Directive + "' in file, "
2056 "no current macro definition");
2059 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2060 const uint64_t Mask = (1 << 7) - 1;
2062 unsigned Byte = Value & Mask;
2064 if (Value) // Not the last one
2066 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2070 void GenericAsmParser::ParseSleb128(int64_t Value) {
2071 const int64_t Mask = (1 << 7) - 1;
2073 unsigned Byte = Value & Mask;
2075 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2076 (Value == -1 && (Byte & 0x40) != 0));
2079 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2085 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2087 if (getParser().ParseAbsoluteExpression(Value))
2090 if (getLexer().isNot(AsmToken::EndOfStatement))
2091 return TokError("unexpected token in directive");
2093 if (DirName[1] == 's')
2094 ParseSleb128(Value);
2096 ParseUleb128(Value);
2101 /// \brief Create an MCAsmParser instance.
2102 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2103 MCContext &C, MCStreamer &Out,
2104 const MCAsmInfo &MAI) {
2105 return new AsmParser(T, SM, C, Out, MAI);