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/APFloat.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetAsmParser.h"
41 /// \brief Helper class for tracking macro definitions.
47 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
50 /// \brief Helper class for storing information about an active macro
52 struct MacroInstantiation {
53 /// The macro being instantiated.
54 const Macro *TheMacro;
56 /// The macro instantiation with substitutions.
57 MemoryBuffer *Instantiation;
59 /// The location of the instantiation.
60 SMLoc InstantiationLoc;
62 /// The location where parsing should resume upon instantiation completion.
66 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
67 const std::vector<std::vector<AsmToken> > &A);
70 /// \brief The concrete assembly parser instance.
71 class AsmParser : public MCAsmParser {
72 friend class GenericAsmParser;
74 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
75 void operator=(const AsmParser &); // DO NOT IMPLEMENT
81 MCAsmParserExtension *GenericParser;
82 MCAsmParserExtension *PlatformParser;
84 /// This is the current buffer index we're lexing from as managed by the
89 std::vector<AsmCond> TheCondStack;
91 /// DirectiveMap - This is a table handlers for directives. Each handler is
92 /// invoked after the directive identifier is read and is responsible for
93 /// parsing and validating the rest of the directive. The handler is passed
94 /// in the directive name and the location of the directive keyword.
95 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
97 /// MacroMap - Map of currently defined macros.
98 StringMap<Macro*> MacroMap;
100 /// ActiveMacros - Stack of active macro instantiations.
101 std::vector<MacroInstantiation*> ActiveMacros;
103 /// Boolean tracking whether macro substitution is enabled.
104 unsigned MacrosEnabled : 1;
106 /// Flag tracking whether any errors have been encountered.
107 unsigned HadError : 1;
110 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
111 const MCAsmInfo &MAI);
114 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
116 void AddDirectiveHandler(MCAsmParserExtension *Object,
118 DirectiveHandler Handler) {
119 DirectiveMap[Directive] = std::make_pair(Object, Handler);
123 /// @name MCAsmParser Interface
126 virtual SourceMgr &getSourceManager() { return SrcMgr; }
127 virtual MCAsmLexer &getLexer() { return Lexer; }
128 virtual MCContext &getContext() { return Ctx; }
129 virtual MCStreamer &getStreamer() { return Out; }
131 virtual void Warning(SMLoc L, const Twine &Meg);
132 virtual bool Error(SMLoc L, const Twine &Msg);
134 const AsmToken &Lex();
136 bool ParseExpression(const MCExpr *&Res);
137 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
138 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
139 virtual bool ParseAbsoluteExpression(int64_t &Res);
144 void CheckForValidSection();
146 bool ParseStatement();
148 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
149 void HandleMacroExit();
151 void PrintMacroInstantiations();
152 void PrintMessage(SMLoc Loc, const std::string &Msg, const char *Type) const;
154 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
155 bool EnterIncludeFile(const std::string &Filename);
157 /// \brief Reset the current lexer position to that given by \arg Loc. The
158 /// current token is not set; clients should ensure Lex() is called
160 void JumpToLoc(SMLoc Loc);
162 void EatToEndOfStatement();
164 /// \brief Parse up to the end of statement and a return the contents from the
165 /// current token until the end of the statement; the current token on exit
166 /// will be either the EndOfStatement or EOF.
167 StringRef ParseStringToEndOfStatement();
169 bool ParseAssignment(StringRef Name);
171 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
172 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
173 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
175 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
176 /// and set \arg Res to the identifier contents.
177 bool ParseIdentifier(StringRef &Res);
179 // Directive Parsing.
180 bool ParseDirectiveAscii(bool ZeroTerminated); // ".ascii", ".asciiz"
181 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
182 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
183 bool ParseDirectiveFill(); // ".fill"
184 bool ParseDirectiveSpace(); // ".space"
185 bool ParseDirectiveZero(); // ".zero"
186 bool ParseDirectiveSet(); // ".set"
187 bool ParseDirectiveOrg(); // ".org"
188 // ".align{,32}", ".p2align{,w,l}"
189 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
191 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
192 /// accepts a single symbol (which should be a label or an external).
193 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
194 bool ParseDirectiveELFType(); // ELF specific ".type"
196 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
198 bool ParseDirectiveAbort(); // ".abort"
199 bool ParseDirectiveInclude(); // ".include"
201 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
202 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
203 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
204 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
206 /// ParseEscapedString - Parse the current token as a string which may include
207 /// escaped characters and return the string contents.
208 bool ParseEscapedString(std::string &Data);
210 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
211 MCSymbolRefExpr::VariantKind Variant);
214 /// \brief Generic implementations of directive handling, etc. which is shared
215 /// (or the default, at least) for all assembler parser.
216 class GenericAsmParser : public MCAsmParserExtension {
217 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
218 void AddDirectiveHandler(StringRef Directive) {
219 getParser().AddDirectiveHandler(this, Directive,
220 HandleDirective<GenericAsmParser, Handler>);
224 GenericAsmParser() {}
226 AsmParser &getParser() {
227 return (AsmParser&) this->MCAsmParserExtension::getParser();
230 virtual void Initialize(MCAsmParser &Parser) {
231 // Call the base implementation.
232 this->MCAsmParserExtension::Initialize(Parser);
234 // Debugging directives.
235 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
252 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
253 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
254 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
256 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
257 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
258 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
260 void ParseUleb128(uint64_t Value);
261 void ParseSleb128(int64_t Value);
262 bool ParseDirectiveLEB128(StringRef, SMLoc);
269 extern MCAsmParserExtension *createDarwinAsmParser();
270 extern MCAsmParserExtension *createELFAsmParser();
274 enum { DEFAULT_ADDRSPACE = 0 };
276 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
277 MCStreamer &_Out, const MCAsmInfo &_MAI)
278 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
279 GenericParser(new GenericAsmParser), PlatformParser(0),
280 CurBuffer(0), MacrosEnabled(true) {
281 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
283 // Initialize the generic parser.
284 GenericParser->Initialize(*this);
286 // Initialize the platform / file format parser.
288 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
290 if (_MAI.hasSubsectionsViaSymbols()) {
291 PlatformParser = createDarwinAsmParser();
292 PlatformParser->Initialize(*this);
294 PlatformParser = createELFAsmParser();
295 PlatformParser->Initialize(*this);
299 AsmParser::~AsmParser() {
300 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
302 // Destroy any macros.
303 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
304 ie = MacroMap.end(); it != ie; ++it)
305 delete it->getValue();
307 delete PlatformParser;
308 delete GenericParser;
311 void AsmParser::PrintMacroInstantiations() {
312 // Print the active macro instantiation stack.
313 for (std::vector<MacroInstantiation*>::const_reverse_iterator
314 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
315 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
319 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
320 PrintMessage(L, Msg.str(), "warning");
321 PrintMacroInstantiations();
324 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
326 PrintMessage(L, Msg.str(), "error");
327 PrintMacroInstantiations();
331 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
332 const char *Type) const {
333 SrcMgr.PrintMessage(Loc, Msg, Type);
336 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
337 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
343 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
348 void AsmParser::JumpToLoc(SMLoc Loc) {
349 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
350 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
353 const AsmToken &AsmParser::Lex() {
354 const AsmToken *tok = &Lexer.Lex();
356 if (tok->is(AsmToken::Eof)) {
357 // If this is the end of an included file, pop the parent file off the
359 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
360 if (ParentIncludeLoc != SMLoc()) {
361 JumpToLoc(ParentIncludeLoc);
366 if (tok->is(AsmToken::Error))
367 Error(Lexer.getErrLoc(), Lexer.getErr());
372 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
373 // Create the initial section, if requested.
374 if (!NoInitialTextSection)
381 AsmCond StartingCondState = TheCondState;
383 // While we have input, parse each statement.
384 while (Lexer.isNot(AsmToken::Eof)) {
385 if (!ParseStatement()) continue;
387 // We had an error, validate that one was emitted and recover by skipping to
389 assert(HadError && "Parse statement returned an error, but none emitted!");
390 EatToEndOfStatement();
393 if (TheCondState.TheCond != StartingCondState.TheCond ||
394 TheCondState.Ignore != StartingCondState.Ignore)
395 return TokError("unmatched .ifs or .elses");
397 // Check to see there are no empty DwarfFile slots.
398 const std::vector<MCDwarfFile *> &MCDwarfFiles =
399 getContext().getMCDwarfFiles();
400 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
401 if (!MCDwarfFiles[i])
402 TokError("unassigned file number: " + Twine(i) + " for .file directives");
405 // Finalize the output stream if there are no errors and if the client wants
407 if (!HadError && !NoFinalize)
413 void AsmParser::CheckForValidSection() {
414 if (!getStreamer().getCurrentSection()) {
415 TokError("expected section directive before assembly directive");
416 Out.SwitchSection(Ctx.getMachOSection(
418 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
419 0, SectionKind::getText()));
423 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
424 void AsmParser::EatToEndOfStatement() {
425 while (Lexer.isNot(AsmToken::EndOfStatement) &&
426 Lexer.isNot(AsmToken::Eof))
430 if (Lexer.is(AsmToken::EndOfStatement))
434 StringRef AsmParser::ParseStringToEndOfStatement() {
435 const char *Start = getTok().getLoc().getPointer();
437 while (Lexer.isNot(AsmToken::EndOfStatement) &&
438 Lexer.isNot(AsmToken::Eof))
441 const char *End = getTok().getLoc().getPointer();
442 return StringRef(Start, End - Start);
445 /// ParseParenExpr - Parse a paren expression and return it.
446 /// NOTE: This assumes the leading '(' has already been consumed.
448 /// parenexpr ::= expr)
450 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
451 if (ParseExpression(Res)) return true;
452 if (Lexer.isNot(AsmToken::RParen))
453 return TokError("expected ')' in parentheses expression");
454 EndLoc = Lexer.getLoc();
459 /// ParsePrimaryExpr - Parse a primary expression and return it.
460 /// primaryexpr ::= (parenexpr
461 /// primaryexpr ::= symbol
462 /// primaryexpr ::= number
463 /// primaryexpr ::= '.'
464 /// primaryexpr ::= ~,+,- primaryexpr
465 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
466 switch (Lexer.getKind()) {
468 return TokError("unknown token in expression");
469 case AsmToken::Exclaim:
470 Lex(); // Eat the operator.
471 if (ParsePrimaryExpr(Res, EndLoc))
473 Res = MCUnaryExpr::CreateLNot(Res, getContext());
475 case AsmToken::Dollar:
476 case AsmToken::String:
477 case AsmToken::Identifier: {
478 EndLoc = Lexer.getLoc();
480 StringRef Identifier;
481 if (ParseIdentifier(Identifier))
484 // This is a symbol reference.
485 std::pair<StringRef, StringRef> Split = Identifier.split('@');
486 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
488 // Mark the symbol as used in an expression.
489 Sym->setUsedInExpr(true);
491 // Lookup the symbol variant if used.
492 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
493 if (Split.first.size() != Identifier.size()) {
494 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
495 if (Variant == MCSymbolRefExpr::VK_Invalid) {
496 Variant = MCSymbolRefExpr::VK_None;
497 TokError("invalid variant '" + Split.second + "'");
501 // If this is an absolute variable reference, substitute it now to preserve
502 // semantics in the face of reassignment.
503 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
505 return Error(EndLoc, "unexpected modified on variable reference");
507 Res = Sym->getVariableValue();
511 // Otherwise create a symbol ref.
512 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
515 case AsmToken::Integer: {
516 SMLoc Loc = getTok().getLoc();
517 int64_t IntVal = getTok().getIntVal();
518 Res = MCConstantExpr::Create(IntVal, getContext());
519 EndLoc = Lexer.getLoc();
521 // Look for 'b' or 'f' following an Integer as a directional label
522 if (Lexer.getKind() == AsmToken::Identifier) {
523 StringRef IDVal = getTok().getString();
524 if (IDVal == "f" || IDVal == "b"){
525 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
526 IDVal == "f" ? 1 : 0);
527 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
529 if(IDVal == "b" && Sym->isUndefined())
530 return Error(Loc, "invalid reference to undefined symbol");
531 EndLoc = Lexer.getLoc();
532 Lex(); // Eat identifier.
537 case AsmToken::Dot: {
538 // This is a '.' reference, which references the current PC. Emit a
539 // temporary label to the streamer and refer to it.
540 MCSymbol *Sym = Ctx.CreateTempSymbol();
542 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
543 EndLoc = Lexer.getLoc();
544 Lex(); // Eat identifier.
548 case AsmToken::LParen:
549 Lex(); // Eat the '('.
550 return ParseParenExpr(Res, EndLoc);
551 case AsmToken::Minus:
552 Lex(); // Eat the operator.
553 if (ParsePrimaryExpr(Res, EndLoc))
555 Res = MCUnaryExpr::CreateMinus(Res, getContext());
558 Lex(); // Eat the operator.
559 if (ParsePrimaryExpr(Res, EndLoc))
561 Res = MCUnaryExpr::CreatePlus(Res, getContext());
563 case AsmToken::Tilde:
564 Lex(); // Eat the operator.
565 if (ParsePrimaryExpr(Res, EndLoc))
567 Res = MCUnaryExpr::CreateNot(Res, getContext());
572 bool AsmParser::ParseExpression(const MCExpr *&Res) {
574 return ParseExpression(Res, EndLoc);
578 AsmParser::ApplyModifierToExpr(const MCExpr *E,
579 MCSymbolRefExpr::VariantKind Variant) {
580 // Recurse over the given expression, rebuilding it to apply the given variant
581 // if there is exactly one symbol.
582 switch (E->getKind()) {
584 case MCExpr::Constant:
587 case MCExpr::SymbolRef: {
588 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
590 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
591 TokError("invalid variant on expression '" +
592 getTok().getIdentifier() + "' (already modified)");
596 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
599 case MCExpr::Unary: {
600 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
601 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
604 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
607 case MCExpr::Binary: {
608 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
609 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
610 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
615 if (!LHS) LHS = BE->getLHS();
616 if (!RHS) RHS = BE->getRHS();
618 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
622 assert(0 && "Invalid expression kind!");
626 /// ParseExpression - Parse an expression and return it.
628 /// expr ::= expr +,- expr -> lowest.
629 /// expr ::= expr |,^,&,! expr -> middle.
630 /// expr ::= expr *,/,%,<<,>> expr -> highest.
631 /// expr ::= primaryexpr
633 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
634 // Parse the expression.
636 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
639 // As a special case, we support 'a op b @ modifier' by rewriting the
640 // expression to include the modifier. This is inefficient, but in general we
641 // expect users to use 'a@modifier op b'.
642 if (Lexer.getKind() == AsmToken::At) {
645 if (Lexer.isNot(AsmToken::Identifier))
646 return TokError("unexpected symbol modifier following '@'");
648 MCSymbolRefExpr::VariantKind Variant =
649 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
650 if (Variant == MCSymbolRefExpr::VK_Invalid)
651 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
653 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
655 return TokError("invalid modifier '" + getTok().getIdentifier() +
656 "' (no symbols present)");
664 // Try to constant fold it up front, if possible.
666 if (Res->EvaluateAsAbsolute(Value))
667 Res = MCConstantExpr::Create(Value, getContext());
672 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
674 return ParseParenExpr(Res, EndLoc) ||
675 ParseBinOpRHS(1, Res, EndLoc);
678 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
681 SMLoc StartLoc = Lexer.getLoc();
682 if (ParseExpression(Expr))
685 if (!Expr->EvaluateAsAbsolute(Res))
686 return Error(StartLoc, "expected absolute expression");
691 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
692 MCBinaryExpr::Opcode &Kind) {
695 return 0; // not a binop.
697 // Lowest Precedence: &&, ||, @
698 case AsmToken::AmpAmp:
699 Kind = MCBinaryExpr::LAnd;
701 case AsmToken::PipePipe:
702 Kind = MCBinaryExpr::LOr;
706 // Low Precedence: |, &, ^
708 // FIXME: gas seems to support '!' as an infix operator?
710 Kind = MCBinaryExpr::Or;
712 case AsmToken::Caret:
713 Kind = MCBinaryExpr::Xor;
716 Kind = MCBinaryExpr::And;
719 // Intermediate Precedence: +, -, ==, !=, <>, <, <=, >, >=
721 Kind = MCBinaryExpr::Add;
723 case AsmToken::Minus:
724 Kind = MCBinaryExpr::Sub;
726 case AsmToken::EqualEqual:
727 Kind = MCBinaryExpr::EQ;
729 case AsmToken::ExclaimEqual:
730 case AsmToken::LessGreater:
731 Kind = MCBinaryExpr::NE;
734 Kind = MCBinaryExpr::LT;
736 case AsmToken::LessEqual:
737 Kind = MCBinaryExpr::LTE;
739 case AsmToken::Greater:
740 Kind = MCBinaryExpr::GT;
742 case AsmToken::GreaterEqual:
743 Kind = MCBinaryExpr::GTE;
746 // Highest Precedence: *, /, %, <<, >>
748 Kind = MCBinaryExpr::Mul;
750 case AsmToken::Slash:
751 Kind = MCBinaryExpr::Div;
753 case AsmToken::Percent:
754 Kind = MCBinaryExpr::Mod;
756 case AsmToken::LessLess:
757 Kind = MCBinaryExpr::Shl;
759 case AsmToken::GreaterGreater:
760 Kind = MCBinaryExpr::Shr;
766 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
767 /// Res contains the LHS of the expression on input.
768 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
771 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
772 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
774 // If the next token is lower precedence than we are allowed to eat, return
775 // successfully with what we ate already.
776 if (TokPrec < Precedence)
781 // Eat the next primary expression.
783 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
785 // If BinOp binds less tightly with RHS than the operator after RHS, let
786 // the pending operator take RHS as its LHS.
787 MCBinaryExpr::Opcode Dummy;
788 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
789 if (TokPrec < NextTokPrec) {
790 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
793 // Merge LHS and RHS according to operator.
794 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
802 /// ::= EndOfStatement
803 /// ::= Label* Directive ...Operands... EndOfStatement
804 /// ::= Label* Identifier OperandList* EndOfStatement
805 bool AsmParser::ParseStatement() {
806 if (Lexer.is(AsmToken::EndOfStatement)) {
812 // Statements always start with an identifier.
813 AsmToken ID = getTok();
814 SMLoc IDLoc = ID.getLoc();
816 int64_t LocalLabelVal = -1;
817 // GUESS allow an integer followed by a ':' as a directional local label
818 if (Lexer.is(AsmToken::Integer)) {
819 LocalLabelVal = getTok().getIntVal();
820 if (LocalLabelVal < 0) {
821 if (!TheCondState.Ignore)
822 return TokError("unexpected token at start of statement");
826 IDVal = getTok().getString();
827 Lex(); // Consume the integer token to be used as an identifier token.
828 if (Lexer.getKind() != AsmToken::Colon) {
829 if (!TheCondState.Ignore)
830 return TokError("unexpected token at start of statement");
834 else if (ParseIdentifier(IDVal)) {
835 if (!TheCondState.Ignore)
836 return TokError("unexpected token at start of statement");
840 // Handle conditional assembly here before checking for skipping. We
841 // have to do this so that .endif isn't skipped in a ".if 0" block for
844 return ParseDirectiveIf(IDLoc);
845 if (IDVal == ".elseif")
846 return ParseDirectiveElseIf(IDLoc);
847 if (IDVal == ".else")
848 return ParseDirectiveElse(IDLoc);
849 if (IDVal == ".endif")
850 return ParseDirectiveEndIf(IDLoc);
852 // If we are in a ".if 0" block, ignore this statement.
853 if (TheCondState.Ignore) {
854 EatToEndOfStatement();
858 // FIXME: Recurse on local labels?
860 // See what kind of statement we have.
861 switch (Lexer.getKind()) {
862 case AsmToken::Colon: {
863 CheckForValidSection();
865 // identifier ':' -> Label.
868 // Diagnose attempt to use a variable as a label.
870 // FIXME: Diagnostics. Note the location of the definition as a label.
871 // FIXME: This doesn't diagnose assignment to a symbol which has been
872 // implicitly marked as external.
874 if (LocalLabelVal == -1)
875 Sym = getContext().GetOrCreateSymbol(IDVal);
877 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
878 if (!Sym->isUndefined() || Sym->isVariable())
879 return Error(IDLoc, "invalid symbol redefinition");
884 // Consume any end of statement token, if present, to avoid spurious
885 // AddBlankLine calls().
886 if (Lexer.is(AsmToken::EndOfStatement)) {
888 if (Lexer.is(AsmToken::Eof))
892 return ParseStatement();
895 case AsmToken::Equal:
896 // identifier '=' ... -> assignment statement
899 return ParseAssignment(IDVal);
901 default: // Normal instruction or directive.
905 // If macros are enabled, check to see if this is a macro instantiation.
907 if (const Macro *M = MacroMap.lookup(IDVal))
908 return HandleMacroEntry(IDVal, IDLoc, M);
910 // Otherwise, we have a normal instruction or directive.
911 if (IDVal[0] == '.') {
912 // Assembler features
914 return ParseDirectiveSet();
918 if (IDVal == ".ascii")
919 return ParseDirectiveAscii(false);
920 if (IDVal == ".asciz")
921 return ParseDirectiveAscii(true);
923 if (IDVal == ".byte")
924 return ParseDirectiveValue(1);
925 if (IDVal == ".short")
926 return ParseDirectiveValue(2);
927 if (IDVal == ".long")
928 return ParseDirectiveValue(4);
929 if (IDVal == ".quad")
930 return ParseDirectiveValue(8);
931 if (IDVal == ".single")
932 return ParseDirectiveRealValue(APFloat::IEEEsingle);
933 if (IDVal == ".double")
934 return ParseDirectiveRealValue(APFloat::IEEEdouble);
936 if (IDVal == ".align") {
937 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
938 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
940 if (IDVal == ".align32") {
941 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
942 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
944 if (IDVal == ".balign")
945 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
946 if (IDVal == ".balignw")
947 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
948 if (IDVal == ".balignl")
949 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
950 if (IDVal == ".p2align")
951 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
952 if (IDVal == ".p2alignw")
953 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
954 if (IDVal == ".p2alignl")
955 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
958 return ParseDirectiveOrg();
960 if (IDVal == ".fill")
961 return ParseDirectiveFill();
962 if (IDVal == ".space")
963 return ParseDirectiveSpace();
964 if (IDVal == ".zero")
965 return ParseDirectiveZero();
967 // Symbol attribute directives
969 if (IDVal == ".globl" || IDVal == ".global")
970 return ParseDirectiveSymbolAttribute(MCSA_Global);
971 // ELF only? Should it be here?
972 if (IDVal == ".local")
973 return ParseDirectiveSymbolAttribute(MCSA_Local);
974 if (IDVal == ".hidden")
975 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
976 if (IDVal == ".indirect_symbol")
977 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
978 if (IDVal == ".internal")
979 return ParseDirectiveSymbolAttribute(MCSA_Internal);
980 if (IDVal == ".lazy_reference")
981 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
982 if (IDVal == ".no_dead_strip")
983 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
984 if (IDVal == ".private_extern")
985 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
986 if (IDVal == ".protected")
987 return ParseDirectiveSymbolAttribute(MCSA_Protected);
988 if (IDVal == ".reference")
989 return ParseDirectiveSymbolAttribute(MCSA_Reference);
990 if (IDVal == ".type")
991 return ParseDirectiveELFType();
992 if (IDVal == ".weak")
993 return ParseDirectiveSymbolAttribute(MCSA_Weak);
994 if (IDVal == ".weak_definition")
995 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
996 if (IDVal == ".weak_reference")
997 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
998 if (IDVal == ".weak_def_can_be_hidden")
999 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1001 if (IDVal == ".comm")
1002 return ParseDirectiveComm(/*IsLocal=*/false);
1003 if (IDVal == ".lcomm")
1004 return ParseDirectiveComm(/*IsLocal=*/true);
1006 if (IDVal == ".abort")
1007 return ParseDirectiveAbort();
1008 if (IDVal == ".include")
1009 return ParseDirectiveInclude();
1011 // Look up the handler in the handler table.
1012 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1013 DirectiveMap.lookup(IDVal);
1015 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1017 // Target hook for parsing target specific directives.
1018 if (!getTargetParser().ParseDirective(ID))
1021 Warning(IDLoc, "ignoring directive for now");
1022 EatToEndOfStatement();
1026 CheckForValidSection();
1028 // Canonicalize the opcode to lower case.
1029 SmallString<128> Opcode;
1030 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1031 Opcode.push_back(tolower(IDVal[i]));
1033 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1034 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1037 // Dump the parsed representation, if requested.
1038 if (getShowParsedOperands()) {
1039 SmallString<256> Str;
1040 raw_svector_ostream OS(Str);
1041 OS << "parsed instruction: [";
1042 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1045 ParsedOperands[i]->dump(OS);
1049 PrintMessage(IDLoc, OS.str(), "note");
1052 // If parsing succeeded, match the instruction.
1055 if (!getTargetParser().MatchInstruction(IDLoc, ParsedOperands, Inst)) {
1056 // Emit the instruction on success.
1057 Out.EmitInstruction(Inst);
1062 // Free any parsed operands.
1063 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1064 delete ParsedOperands[i];
1066 // Don't skip the rest of the line, the instruction parser is responsible for
1071 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1072 const std::vector<std::vector<AsmToken> > &A)
1073 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1075 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1076 // to hold the macro body with substitutions.
1077 SmallString<256> Buf;
1078 raw_svector_ostream OS(Buf);
1080 StringRef Body = M->Body;
1081 while (!Body.empty()) {
1082 // Scan for the next substitution.
1083 std::size_t End = Body.size(), Pos = 0;
1084 for (; Pos != End; ++Pos) {
1085 // Check for a substitution or escape.
1086 if (Body[Pos] != '$' || Pos + 1 == End)
1089 char Next = Body[Pos + 1];
1090 if (Next == '$' || Next == 'n' || isdigit(Next))
1095 OS << Body.slice(0, Pos);
1097 // Check if we reached the end.
1101 switch (Body[Pos+1]) {
1107 // $n => number of arguments
1112 // $[0-9] => argument
1114 // Missing arguments are ignored.
1115 unsigned Index = Body[Pos+1] - '0';
1116 if (Index >= A.size())
1119 // Otherwise substitute with the token values, with spaces eliminated.
1120 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1121 ie = A[Index].end(); it != ie; ++it)
1122 OS << it->getString();
1127 // Update the scan point.
1128 Body = Body.substr(Pos + 2);
1131 // We include the .endmacro in the buffer as our queue to exit the macro
1133 OS << ".endmacro\n";
1135 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1138 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1140 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1141 // this, although we should protect against infinite loops.
1142 if (ActiveMacros.size() == 20)
1143 return TokError("macros cannot be nested more than 20 levels deep");
1145 // Parse the macro instantiation arguments.
1146 std::vector<std::vector<AsmToken> > MacroArguments;
1147 MacroArguments.push_back(std::vector<AsmToken>());
1148 unsigned ParenLevel = 0;
1150 if (Lexer.is(AsmToken::Eof))
1151 return TokError("unexpected token in macro instantiation");
1152 if (Lexer.is(AsmToken::EndOfStatement))
1155 // If we aren't inside parentheses and this is a comma, start a new token
1157 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1158 MacroArguments.push_back(std::vector<AsmToken>());
1160 // Adjust the current parentheses level.
1161 if (Lexer.is(AsmToken::LParen))
1163 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1166 // Append the token to the current argument list.
1167 MacroArguments.back().push_back(getTok());
1172 // Create the macro instantiation object and add to the current macro
1173 // instantiation stack.
1174 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1177 ActiveMacros.push_back(MI);
1179 // Jump to the macro instantiation and prime the lexer.
1180 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1181 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1187 void AsmParser::HandleMacroExit() {
1188 // Jump to the EndOfStatement we should return to, and consume it.
1189 JumpToLoc(ActiveMacros.back()->ExitLoc);
1192 // Pop the instantiation entry.
1193 delete ActiveMacros.back();
1194 ActiveMacros.pop_back();
1197 bool AsmParser::ParseAssignment(StringRef Name) {
1198 // FIXME: Use better location, we should use proper tokens.
1199 SMLoc EqualLoc = Lexer.getLoc();
1201 const MCExpr *Value;
1202 if (ParseExpression(Value))
1205 if (Lexer.isNot(AsmToken::EndOfStatement))
1206 return TokError("unexpected token in assignment");
1208 // Eat the end of statement marker.
1211 // Validate that the LHS is allowed to be a variable (either it has not been
1212 // used as a symbol, or it is an absolute symbol).
1213 MCSymbol *Sym = getContext().LookupSymbol(Name);
1215 // Diagnose assignment to a label.
1217 // FIXME: Diagnostics. Note the location of the definition as a label.
1218 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1219 if (Sym->isUndefined() && !Sym->isUsedInExpr())
1220 ; // Allow redefinitions of undefined symbols only used in directives.
1221 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1222 return Error(EqualLoc, "redefinition of '" + Name + "'");
1223 else if (!Sym->isVariable())
1224 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1225 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1226 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1229 Sym = getContext().GetOrCreateSymbol(Name);
1231 // FIXME: Handle '.'.
1233 Sym->setUsedInExpr(true);
1235 // Do the assignment.
1236 Out.EmitAssignment(Sym, Value);
1241 /// ParseIdentifier:
1244 bool AsmParser::ParseIdentifier(StringRef &Res) {
1245 // The assembler has relaxed rules for accepting identifiers, in particular we
1246 // allow things like '.globl $foo', which would normally be separate
1247 // tokens. At this level, we have already lexed so we cannot (currently)
1248 // handle this as a context dependent token, instead we detect adjacent tokens
1249 // and return the combined identifier.
1250 if (Lexer.is(AsmToken::Dollar)) {
1251 SMLoc DollarLoc = getLexer().getLoc();
1253 // Consume the dollar sign, and check for a following identifier.
1255 if (Lexer.isNot(AsmToken::Identifier))
1258 // We have a '$' followed by an identifier, make sure they are adjacent.
1259 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1262 // Construct the joined identifier and consume the token.
1263 Res = StringRef(DollarLoc.getPointer(),
1264 getTok().getIdentifier().size() + 1);
1269 if (Lexer.isNot(AsmToken::Identifier) &&
1270 Lexer.isNot(AsmToken::String))
1273 Res = getTok().getIdentifier();
1275 Lex(); // Consume the identifier token.
1280 /// ParseDirectiveSet:
1281 /// ::= .set identifier ',' expression
1282 bool AsmParser::ParseDirectiveSet() {
1285 if (ParseIdentifier(Name))
1286 return TokError("expected identifier after '.set' directive");
1288 if (getLexer().isNot(AsmToken::Comma))
1289 return TokError("unexpected token in '.set'");
1292 return ParseAssignment(Name);
1295 bool AsmParser::ParseEscapedString(std::string &Data) {
1296 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1299 StringRef Str = getTok().getStringContents();
1300 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1301 if (Str[i] != '\\') {
1306 // Recognize escaped characters. Note that this escape semantics currently
1307 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1310 return TokError("unexpected backslash at end of string");
1312 // Recognize octal sequences.
1313 if ((unsigned) (Str[i] - '0') <= 7) {
1314 // Consume up to three octal characters.
1315 unsigned Value = Str[i] - '0';
1317 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1319 Value = Value * 8 + (Str[i] - '0');
1321 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1323 Value = Value * 8 + (Str[i] - '0');
1328 return TokError("invalid octal escape sequence (out of range)");
1330 Data += (unsigned char) Value;
1334 // Otherwise recognize individual escapes.
1337 // Just reject invalid escape sequences for now.
1338 return TokError("invalid escape sequence (unrecognized character)");
1340 case 'b': Data += '\b'; break;
1341 case 'f': Data += '\f'; break;
1342 case 'n': Data += '\n'; break;
1343 case 'r': Data += '\r'; break;
1344 case 't': Data += '\t'; break;
1345 case '"': Data += '"'; break;
1346 case '\\': Data += '\\'; break;
1353 /// ParseDirectiveAscii:
1354 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1355 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1357 CheckForValidSection();
1360 if (getLexer().isNot(AsmToken::String))
1361 return TokError("expected string in '.ascii' or '.asciz' directive");
1364 if (ParseEscapedString(Data))
1367 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1369 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1373 if (getLexer().is(AsmToken::EndOfStatement))
1376 if (getLexer().isNot(AsmToken::Comma))
1377 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1386 /// ParseDirectiveValue
1387 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1388 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1389 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1390 CheckForValidSection();
1393 const MCExpr *Value;
1394 SMLoc ATTRIBUTE_UNUSED StartLoc = getLexer().getLoc();
1395 if (ParseExpression(Value))
1398 // Special case constant expressions to match code generator.
1399 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1400 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1402 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1404 if (getLexer().is(AsmToken::EndOfStatement))
1407 // FIXME: Improve diagnostic.
1408 if (getLexer().isNot(AsmToken::Comma))
1409 return TokError("unexpected token in directive");
1418 /// ParseDirectiveRealValue
1419 /// ::= (.single | .double) [ expression (, expression)* ]
1420 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1421 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1422 CheckForValidSection();
1425 // We don't truly support arithmetic on floating point expressions, so we
1426 // have to manually parse unary prefixes.
1428 if (getLexer().is(AsmToken::Minus)) {
1431 } else if (getLexer().is(AsmToken::Plus))
1434 if (getLexer().isNot(AsmToken::Integer) &&
1435 getLexer().isNot(AsmToken::Real))
1436 return TokError("unexpected token in directive");
1438 // Convert to an APFloat.
1439 APFloat Value(Semantics);
1440 if (Value.convertFromString(getTok().getString(),
1441 APFloat::rmNearestTiesToEven) ==
1442 APFloat::opInvalidOp)
1443 return TokError("invalid floating point literal");
1447 // Consume the numeric token.
1450 // Emit the value as an integer.
1451 APInt AsInt = Value.bitcastToAPInt();
1452 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1453 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1455 if (getLexer().is(AsmToken::EndOfStatement))
1458 if (getLexer().isNot(AsmToken::Comma))
1459 return TokError("unexpected token in directive");
1468 /// ParseDirectiveSpace
1469 /// ::= .space expression [ , expression ]
1470 bool AsmParser::ParseDirectiveSpace() {
1471 CheckForValidSection();
1474 if (ParseAbsoluteExpression(NumBytes))
1477 int64_t FillExpr = 0;
1478 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1479 if (getLexer().isNot(AsmToken::Comma))
1480 return TokError("unexpected token in '.space' directive");
1483 if (ParseAbsoluteExpression(FillExpr))
1486 if (getLexer().isNot(AsmToken::EndOfStatement))
1487 return TokError("unexpected token in '.space' directive");
1493 return TokError("invalid number of bytes in '.space' directive");
1495 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1496 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1501 /// ParseDirectiveZero
1502 /// ::= .zero expression
1503 bool AsmParser::ParseDirectiveZero() {
1504 CheckForValidSection();
1507 if (ParseAbsoluteExpression(NumBytes))
1510 if (getLexer().isNot(AsmToken::EndOfStatement))
1511 return TokError("unexpected token in '.zero' directive");
1515 getStreamer().EmitFill(NumBytes, 0, DEFAULT_ADDRSPACE);
1520 /// ParseDirectiveFill
1521 /// ::= .fill expression , expression , expression
1522 bool AsmParser::ParseDirectiveFill() {
1523 CheckForValidSection();
1526 if (ParseAbsoluteExpression(NumValues))
1529 if (getLexer().isNot(AsmToken::Comma))
1530 return TokError("unexpected token in '.fill' directive");
1534 if (ParseAbsoluteExpression(FillSize))
1537 if (getLexer().isNot(AsmToken::Comma))
1538 return TokError("unexpected token in '.fill' directive");
1542 if (ParseAbsoluteExpression(FillExpr))
1545 if (getLexer().isNot(AsmToken::EndOfStatement))
1546 return TokError("unexpected token in '.fill' directive");
1550 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1551 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1553 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1554 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1559 /// ParseDirectiveOrg
1560 /// ::= .org expression [ , expression ]
1561 bool AsmParser::ParseDirectiveOrg() {
1562 CheckForValidSection();
1564 const MCExpr *Offset;
1565 if (ParseExpression(Offset))
1568 // Parse optional fill expression.
1569 int64_t FillExpr = 0;
1570 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1571 if (getLexer().isNot(AsmToken::Comma))
1572 return TokError("unexpected token in '.org' directive");
1575 if (ParseAbsoluteExpression(FillExpr))
1578 if (getLexer().isNot(AsmToken::EndOfStatement))
1579 return TokError("unexpected token in '.org' directive");
1584 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1585 // has to be relative to the current section.
1586 getStreamer().EmitValueToOffset(Offset, FillExpr);
1591 /// ParseDirectiveAlign
1592 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1593 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1594 CheckForValidSection();
1596 SMLoc AlignmentLoc = getLexer().getLoc();
1598 if (ParseAbsoluteExpression(Alignment))
1602 bool HasFillExpr = false;
1603 int64_t FillExpr = 0;
1604 int64_t MaxBytesToFill = 0;
1605 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1606 if (getLexer().isNot(AsmToken::Comma))
1607 return TokError("unexpected token in directive");
1610 // The fill expression can be omitted while specifying a maximum number of
1611 // alignment bytes, e.g:
1613 if (getLexer().isNot(AsmToken::Comma)) {
1615 if (ParseAbsoluteExpression(FillExpr))
1619 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1620 if (getLexer().isNot(AsmToken::Comma))
1621 return TokError("unexpected token in directive");
1624 MaxBytesLoc = getLexer().getLoc();
1625 if (ParseAbsoluteExpression(MaxBytesToFill))
1628 if (getLexer().isNot(AsmToken::EndOfStatement))
1629 return TokError("unexpected token in directive");
1638 // Compute alignment in bytes.
1640 // FIXME: Diagnose overflow.
1641 if (Alignment >= 32) {
1642 Error(AlignmentLoc, "invalid alignment value");
1646 Alignment = 1ULL << Alignment;
1649 // Diagnose non-sensical max bytes to align.
1650 if (MaxBytesLoc.isValid()) {
1651 if (MaxBytesToFill < 1) {
1652 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1653 "many bytes, ignoring maximum bytes expression");
1657 if (MaxBytesToFill >= Alignment) {
1658 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1664 // Check whether we should use optimal code alignment for this .align
1667 // FIXME: This should be using a target hook.
1668 bool UseCodeAlign = false;
1669 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1670 getStreamer().getCurrentSection()))
1671 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1672 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1673 ValueSize == 1 && UseCodeAlign) {
1674 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1676 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1677 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1684 /// ParseDirectiveSymbolAttribute
1685 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1686 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1687 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1691 if (ParseIdentifier(Name))
1692 return TokError("expected identifier in directive");
1694 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1696 getStreamer().EmitSymbolAttribute(Sym, Attr);
1698 if (getLexer().is(AsmToken::EndOfStatement))
1701 if (getLexer().isNot(AsmToken::Comma))
1702 return TokError("unexpected token in directive");
1711 /// ParseDirectiveELFType
1712 /// ::= .type identifier , @attribute
1713 bool AsmParser::ParseDirectiveELFType() {
1715 if (ParseIdentifier(Name))
1716 return TokError("expected identifier in directive");
1718 // Handle the identifier as the key symbol.
1719 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1721 if (getLexer().isNot(AsmToken::Comma))
1722 return TokError("unexpected token in '.type' directive");
1725 if (getLexer().isNot(AsmToken::At))
1726 return TokError("expected '@' before type");
1732 TypeLoc = getLexer().getLoc();
1733 if (ParseIdentifier(Type))
1734 return TokError("expected symbol type in directive");
1736 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1737 .Case("function", MCSA_ELF_TypeFunction)
1738 .Case("object", MCSA_ELF_TypeObject)
1739 .Case("tls_object", MCSA_ELF_TypeTLS)
1740 .Case("common", MCSA_ELF_TypeCommon)
1741 .Case("notype", MCSA_ELF_TypeNoType)
1742 .Default(MCSA_Invalid);
1744 if (Attr == MCSA_Invalid)
1745 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1747 if (getLexer().isNot(AsmToken::EndOfStatement))
1748 return TokError("unexpected token in '.type' directive");
1752 getStreamer().EmitSymbolAttribute(Sym, Attr);
1757 /// ParseDirectiveComm
1758 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1759 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1760 CheckForValidSection();
1762 SMLoc IDLoc = getLexer().getLoc();
1764 if (ParseIdentifier(Name))
1765 return TokError("expected identifier in directive");
1767 // Handle the identifier as the key symbol.
1768 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1770 if (getLexer().isNot(AsmToken::Comma))
1771 return TokError("unexpected token in directive");
1775 SMLoc SizeLoc = getLexer().getLoc();
1776 if (ParseAbsoluteExpression(Size))
1779 int64_t Pow2Alignment = 0;
1780 SMLoc Pow2AlignmentLoc;
1781 if (getLexer().is(AsmToken::Comma)) {
1783 Pow2AlignmentLoc = getLexer().getLoc();
1784 if (ParseAbsoluteExpression(Pow2Alignment))
1787 // If this target takes alignments in bytes (not log) validate and convert.
1788 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1789 if (!isPowerOf2_64(Pow2Alignment))
1790 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1791 Pow2Alignment = Log2_64(Pow2Alignment);
1795 if (getLexer().isNot(AsmToken::EndOfStatement))
1796 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1800 // NOTE: a size of zero for a .comm should create a undefined symbol
1801 // but a size of .lcomm creates a bss symbol of size zero.
1803 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1804 "be less than zero");
1806 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1807 // may internally end up wanting an alignment in bytes.
1808 // FIXME: Diagnose overflow.
1809 if (Pow2Alignment < 0)
1810 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1811 "alignment, can't be less than zero");
1813 if (!Sym->isUndefined())
1814 return Error(IDLoc, "invalid symbol redefinition");
1816 // '.lcomm' is equivalent to '.zerofill'.
1817 // Create the Symbol as a common or local common with Size and Pow2Alignment
1819 getStreamer().EmitZerofill(Ctx.getMachOSection(
1820 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1821 0, SectionKind::getBSS()),
1822 Sym, Size, 1 << Pow2Alignment);
1826 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1830 /// ParseDirectiveAbort
1831 /// ::= .abort [... message ...]
1832 bool AsmParser::ParseDirectiveAbort() {
1833 // FIXME: Use loc from directive.
1834 SMLoc Loc = getLexer().getLoc();
1836 StringRef Str = ParseStringToEndOfStatement();
1837 if (getLexer().isNot(AsmToken::EndOfStatement))
1838 return TokError("unexpected token in '.abort' directive");
1843 Error(Loc, ".abort detected. Assembly stopping.");
1845 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1846 // FIXME: Actually abort assembly here.
1851 /// ParseDirectiveInclude
1852 /// ::= .include "filename"
1853 bool AsmParser::ParseDirectiveInclude() {
1854 if (getLexer().isNot(AsmToken::String))
1855 return TokError("expected string in '.include' directive");
1857 std::string Filename = getTok().getString();
1858 SMLoc IncludeLoc = getLexer().getLoc();
1861 if (getLexer().isNot(AsmToken::EndOfStatement))
1862 return TokError("unexpected token in '.include' directive");
1864 // Strip the quotes.
1865 Filename = Filename.substr(1, Filename.size()-2);
1867 // Attempt to switch the lexer to the included file before consuming the end
1868 // of statement to avoid losing it when we switch.
1869 if (EnterIncludeFile(Filename)) {
1870 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1877 /// ParseDirectiveIf
1878 /// ::= .if expression
1879 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1880 TheCondStack.push_back(TheCondState);
1881 TheCondState.TheCond = AsmCond::IfCond;
1882 if(TheCondState.Ignore) {
1883 EatToEndOfStatement();
1887 if (ParseAbsoluteExpression(ExprValue))
1890 if (getLexer().isNot(AsmToken::EndOfStatement))
1891 return TokError("unexpected token in '.if' directive");
1895 TheCondState.CondMet = ExprValue;
1896 TheCondState.Ignore = !TheCondState.CondMet;
1902 /// ParseDirectiveElseIf
1903 /// ::= .elseif expression
1904 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1905 if (TheCondState.TheCond != AsmCond::IfCond &&
1906 TheCondState.TheCond != AsmCond::ElseIfCond)
1907 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1909 TheCondState.TheCond = AsmCond::ElseIfCond;
1911 bool LastIgnoreState = false;
1912 if (!TheCondStack.empty())
1913 LastIgnoreState = TheCondStack.back().Ignore;
1914 if (LastIgnoreState || TheCondState.CondMet) {
1915 TheCondState.Ignore = true;
1916 EatToEndOfStatement();
1920 if (ParseAbsoluteExpression(ExprValue))
1923 if (getLexer().isNot(AsmToken::EndOfStatement))
1924 return TokError("unexpected token in '.elseif' directive");
1927 TheCondState.CondMet = ExprValue;
1928 TheCondState.Ignore = !TheCondState.CondMet;
1934 /// ParseDirectiveElse
1936 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1937 if (getLexer().isNot(AsmToken::EndOfStatement))
1938 return TokError("unexpected token in '.else' directive");
1942 if (TheCondState.TheCond != AsmCond::IfCond &&
1943 TheCondState.TheCond != AsmCond::ElseIfCond)
1944 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1946 TheCondState.TheCond = AsmCond::ElseCond;
1947 bool LastIgnoreState = false;
1948 if (!TheCondStack.empty())
1949 LastIgnoreState = TheCondStack.back().Ignore;
1950 if (LastIgnoreState || TheCondState.CondMet)
1951 TheCondState.Ignore = true;
1953 TheCondState.Ignore = false;
1958 /// ParseDirectiveEndIf
1960 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1961 if (getLexer().isNot(AsmToken::EndOfStatement))
1962 return TokError("unexpected token in '.endif' directive");
1966 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1967 TheCondStack.empty())
1968 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1970 if (!TheCondStack.empty()) {
1971 TheCondState = TheCondStack.back();
1972 TheCondStack.pop_back();
1978 /// ParseDirectiveFile
1979 /// ::= .file [number] string
1980 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1981 // FIXME: I'm not sure what this is.
1982 int64_t FileNumber = -1;
1983 SMLoc FileNumberLoc = getLexer().getLoc();
1984 if (getLexer().is(AsmToken::Integer)) {
1985 FileNumber = getTok().getIntVal();
1989 return TokError("file number less than one");
1992 if (getLexer().isNot(AsmToken::String))
1993 return TokError("unexpected token in '.file' directive");
1995 StringRef Filename = getTok().getString();
1996 Filename = Filename.substr(1, Filename.size()-2);
1999 if (getLexer().isNot(AsmToken::EndOfStatement))
2000 return TokError("unexpected token in '.file' directive");
2002 if (FileNumber == -1)
2003 getStreamer().EmitFileDirective(Filename);
2005 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
2006 Error(FileNumberLoc, "file number already allocated");
2007 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
2013 /// ParseDirectiveLine
2014 /// ::= .line [number]
2015 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2016 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2017 if (getLexer().isNot(AsmToken::Integer))
2018 return TokError("unexpected token in '.line' directive");
2020 int64_t LineNumber = getTok().getIntVal();
2024 // FIXME: Do something with the .line.
2027 if (getLexer().isNot(AsmToken::EndOfStatement))
2028 return TokError("unexpected token in '.line' directive");
2034 /// ParseDirectiveLoc
2035 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2036 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2037 /// The first number is a file number, must have been previously assigned with
2038 /// a .file directive, the second number is the line number and optionally the
2039 /// third number is a column position (zero if not specified). The remaining
2040 /// optional items are .loc sub-directives.
2041 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2043 if (getLexer().isNot(AsmToken::Integer))
2044 return TokError("unexpected token in '.loc' directive");
2045 int64_t FileNumber = getTok().getIntVal();
2047 return TokError("file number less than one in '.loc' directive");
2048 if (!getContext().ValidateDwarfFileNumber(FileNumber))
2049 return TokError("unassigned file number in '.loc' directive");
2052 int64_t LineNumber = 0;
2053 if (getLexer().is(AsmToken::Integer)) {
2054 LineNumber = getTok().getIntVal();
2056 return TokError("line number less than one in '.loc' directive");
2060 int64_t ColumnPos = 0;
2061 if (getLexer().is(AsmToken::Integer)) {
2062 ColumnPos = getTok().getIntVal();
2064 return TokError("column position less than zero in '.loc' directive");
2070 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2072 if (getLexer().is(AsmToken::EndOfStatement))
2076 SMLoc Loc = getTok().getLoc();
2077 if (getParser().ParseIdentifier(Name))
2078 return TokError("unexpected token in '.loc' directive");
2080 if (Name == "basic_block")
2081 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2082 else if (Name == "prologue_end")
2083 Flags |= DWARF2_FLAG_PROLOGUE_END;
2084 else if (Name == "epilogue_begin")
2085 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2086 else if (Name == "is_stmt") {
2087 SMLoc Loc = getTok().getLoc();
2088 const MCExpr *Value;
2089 if (getParser().ParseExpression(Value))
2091 // The expression must be the constant 0 or 1.
2092 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2093 int Value = MCE->getValue();
2095 Flags &= ~DWARF2_FLAG_IS_STMT;
2096 else if (Value == 1)
2097 Flags |= DWARF2_FLAG_IS_STMT;
2099 return Error(Loc, "is_stmt value not 0 or 1");
2102 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2105 else if (Name == "isa") {
2106 SMLoc Loc = getTok().getLoc();
2107 const MCExpr *Value;
2108 if (getParser().ParseExpression(Value))
2110 // The expression must be a constant greater or equal to 0.
2111 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2112 int Value = MCE->getValue();
2114 return Error(Loc, "isa number less than zero");
2118 return Error(Loc, "isa number not a constant value");
2122 return Error(Loc, "unknown sub-directive in '.loc' directive");
2125 if (getLexer().is(AsmToken::EndOfStatement))
2130 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
2135 /// ParseDirectiveMacrosOnOff
2138 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2139 SMLoc DirectiveLoc) {
2140 if (getLexer().isNot(AsmToken::EndOfStatement))
2141 return Error(getLexer().getLoc(),
2142 "unexpected token in '" + Directive + "' directive");
2144 getParser().MacrosEnabled = Directive == ".macros_on";
2149 /// ParseDirectiveMacro
2151 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2152 SMLoc DirectiveLoc) {
2154 if (getParser().ParseIdentifier(Name))
2155 return TokError("expected identifier in directive");
2157 if (getLexer().isNot(AsmToken::EndOfStatement))
2158 return TokError("unexpected token in '.macro' directive");
2160 // Eat the end of statement.
2163 AsmToken EndToken, StartToken = getTok();
2165 // Lex the macro definition.
2167 // Check whether we have reached the end of the file.
2168 if (getLexer().is(AsmToken::Eof))
2169 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2171 // Otherwise, check whether we have reach the .endmacro.
2172 if (getLexer().is(AsmToken::Identifier) &&
2173 (getTok().getIdentifier() == ".endm" ||
2174 getTok().getIdentifier() == ".endmacro")) {
2175 EndToken = getTok();
2177 if (getLexer().isNot(AsmToken::EndOfStatement))
2178 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2183 // Otherwise, scan til the end of the statement.
2184 getParser().EatToEndOfStatement();
2187 if (getParser().MacroMap.lookup(Name)) {
2188 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2191 const char *BodyStart = StartToken.getLoc().getPointer();
2192 const char *BodyEnd = EndToken.getLoc().getPointer();
2193 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2194 getParser().MacroMap[Name] = new Macro(Name, Body);
2198 /// ParseDirectiveEndMacro
2201 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2202 SMLoc DirectiveLoc) {
2203 if (getLexer().isNot(AsmToken::EndOfStatement))
2204 return TokError("unexpected token in '" + Directive + "' directive");
2206 // If we are inside a macro instantiation, terminate the current
2208 if (!getParser().ActiveMacros.empty()) {
2209 getParser().HandleMacroExit();
2213 // Otherwise, this .endmacro is a stray entry in the file; well formed
2214 // .endmacro directives are handled during the macro definition parsing.
2215 return TokError("unexpected '" + Directive + "' in file, "
2216 "no current macro definition");
2219 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2220 const uint64_t Mask = (1 << 7) - 1;
2222 unsigned Byte = Value & Mask;
2224 if (Value) // Not the last one
2226 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2230 void GenericAsmParser::ParseSleb128(int64_t Value) {
2231 const int64_t Mask = (1 << 7) - 1;
2233 unsigned Byte = Value & Mask;
2235 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2236 (Value == -1 && (Byte & 0x40) != 0));
2239 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2245 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2247 if (getParser().ParseAbsoluteExpression(Value))
2250 if (getLexer().isNot(AsmToken::EndOfStatement))
2251 return TokError("unexpected token in directive");
2253 if (DirName[1] == 's')
2254 ParseSleb128(Value);
2256 ParseUleb128(Value);
2261 /// \brief Create an MCAsmParser instance.
2262 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2263 MCContext &C, MCStreamer &Out,
2264 const MCAsmInfo &MAI) {
2265 return new AsmParser(T, SM, C, Out, MAI);