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/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/MemoryBuffer.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmParser.h"
39 /// \brief Helper class for tracking macro definitions.
45 Macro(StringRef N, StringRef B) : Name(N), Body(B) {}
48 /// \brief Helper class for storing information about an active macro
50 struct MacroInstantiation {
51 /// The macro being instantiated.
52 const Macro *TheMacro;
54 /// The macro instantiation with substitutions.
55 MemoryBuffer *Instantiation;
57 /// The location of the instantiation.
58 SMLoc InstantiationLoc;
60 /// The location where parsing should resume upon instantiation completion.
64 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
65 const std::vector<std::vector<AsmToken> > &A);
68 /// \brief The concrete assembly parser instance.
69 class AsmParser : public MCAsmParser {
70 friend class GenericAsmParser;
72 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
73 void operator=(const AsmParser &); // DO NOT IMPLEMENT
79 MCAsmParserExtension *GenericParser;
80 MCAsmParserExtension *PlatformParser;
82 /// This is the current buffer index we're lexing from as managed by the
87 std::vector<AsmCond> TheCondStack;
89 /// DirectiveMap - This is a table handlers for directives. Each handler is
90 /// invoked after the directive identifier is read and is responsible for
91 /// parsing and validating the rest of the directive. The handler is passed
92 /// in the directive name and the location of the directive keyword.
93 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
95 /// MacroMap - Map of currently defined macros.
96 StringMap<Macro*> MacroMap;
98 /// ActiveMacros - Stack of active macro instantiations.
99 std::vector<MacroInstantiation*> ActiveMacros;
101 /// Boolean tracking whether macro substitution is enabled.
102 unsigned MacrosEnabled : 1;
104 /// Flag tracking whether any errors have been encountered.
105 unsigned HadError : 1;
108 AsmParser(const Target &T, SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
109 const MCAsmInfo &MAI);
112 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
114 void AddDirectiveHandler(MCAsmParserExtension *Object,
116 DirectiveHandler Handler) {
117 DirectiveMap[Directive] = std::make_pair(Object, Handler);
121 /// @name MCAsmParser Interface
124 virtual SourceMgr &getSourceManager() { return SrcMgr; }
125 virtual MCAsmLexer &getLexer() { return Lexer; }
126 virtual MCContext &getContext() { return Ctx; }
127 virtual MCStreamer &getStreamer() { return Out; }
129 virtual void Warning(SMLoc L, const Twine &Meg);
130 virtual bool Error(SMLoc L, const Twine &Msg);
132 const AsmToken &Lex();
134 bool ParseExpression(const MCExpr *&Res);
135 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
136 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
137 virtual bool ParseAbsoluteExpression(int64_t &Res);
142 void CheckForValidSection();
144 bool ParseStatement();
146 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
147 void HandleMacroExit();
149 void PrintMacroInstantiations();
150 void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type) const {
151 SrcMgr.PrintMessage(Loc, Msg, Type);
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.
181 // ".ascii", ".asciiz", ".string"
182 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
183 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
184 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
185 bool ParseDirectiveFill(); // ".fill"
186 bool ParseDirectiveSpace(); // ".space"
187 bool ParseDirectiveZero(); // ".zero"
188 bool ParseDirectiveSet(StringRef IDVal); // ".set" or ".equ"
189 bool ParseDirectiveOrg(); // ".org"
190 // ".align{,32}", ".p2align{,w,l}"
191 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
193 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
194 /// accepts a single symbol (which should be a label or an external).
195 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
196 bool ParseDirectiveELFType(); // ELF specific ".type"
198 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
200 bool ParseDirectiveAbort(); // ".abort"
201 bool ParseDirectiveInclude(); // ".include"
203 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
204 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
205 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
206 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
208 /// ParseEscapedString - Parse the current token as a string which may include
209 /// escaped characters and return the string contents.
210 bool ParseEscapedString(std::string &Data);
212 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
213 MCSymbolRefExpr::VariantKind Variant);
216 /// \brief Generic implementations of directive handling, etc. which is shared
217 /// (or the default, at least) for all assembler parser.
218 class GenericAsmParser : public MCAsmParserExtension {
219 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
220 void AddDirectiveHandler(StringRef Directive) {
221 getParser().AddDirectiveHandler(this, Directive,
222 HandleDirective<GenericAsmParser, Handler>);
226 GenericAsmParser() {}
228 AsmParser &getParser() {
229 return (AsmParser&) this->MCAsmParserExtension::getParser();
232 virtual void Initialize(MCAsmParser &Parser) {
233 // Call the base implementation.
234 this->MCAsmParserExtension::Initialize(Parser);
236 // Debugging directives.
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
240 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
243 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
245 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
247 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
249 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
251 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
252 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
255 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
256 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
257 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
258 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
260 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
261 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
262 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
264 void ParseUleb128(uint64_t Value);
265 void ParseSleb128(int64_t Value);
266 bool ParseDirectiveLEB128(StringRef, SMLoc);
273 extern MCAsmParserExtension *createDarwinAsmParser();
274 extern MCAsmParserExtension *createELFAsmParser();
275 extern MCAsmParserExtension *createCOFFAsmParser();
279 enum { DEFAULT_ADDRSPACE = 0 };
281 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
282 MCStreamer &_Out, const MCAsmInfo &_MAI)
283 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
284 GenericParser(new GenericAsmParser), PlatformParser(0),
285 CurBuffer(0), MacrosEnabled(true) {
286 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
288 // Initialize the generic parser.
289 GenericParser->Initialize(*this);
291 // Initialize the platform / file format parser.
293 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
295 if (_MAI.hasMicrosoftFastStdCallMangling()) {
296 PlatformParser = createCOFFAsmParser();
297 PlatformParser->Initialize(*this);
298 } else if (_MAI.hasSubsectionsViaSymbols()) {
299 PlatformParser = createDarwinAsmParser();
300 PlatformParser->Initialize(*this);
302 PlatformParser = createELFAsmParser();
303 PlatformParser->Initialize(*this);
307 AsmParser::~AsmParser() {
308 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
310 // Destroy any macros.
311 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
312 ie = MacroMap.end(); it != ie; ++it)
313 delete it->getValue();
315 delete PlatformParser;
316 delete GenericParser;
319 void AsmParser::PrintMacroInstantiations() {
320 // Print the active macro instantiation stack.
321 for (std::vector<MacroInstantiation*>::const_reverse_iterator
322 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
323 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
327 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
328 PrintMessage(L, Msg, "warning");
329 PrintMacroInstantiations();
332 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
334 PrintMessage(L, Msg, "error");
335 PrintMacroInstantiations();
339 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
340 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
346 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
351 void AsmParser::JumpToLoc(SMLoc Loc) {
352 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
353 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
356 const AsmToken &AsmParser::Lex() {
357 const AsmToken *tok = &Lexer.Lex();
359 if (tok->is(AsmToken::Eof)) {
360 // If this is the end of an included file, pop the parent file off the
362 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
363 if (ParentIncludeLoc != SMLoc()) {
364 JumpToLoc(ParentIncludeLoc);
369 if (tok->is(AsmToken::Error))
370 Error(Lexer.getErrLoc(), Lexer.getErr());
375 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
376 // Create the initial section, if requested.
377 if (!NoInitialTextSection)
384 AsmCond StartingCondState = TheCondState;
386 // While we have input, parse each statement.
387 while (Lexer.isNot(AsmToken::Eof)) {
388 if (!ParseStatement()) continue;
390 // We had an error, validate that one was emitted and recover by skipping to
392 assert(HadError && "Parse statement returned an error, but none emitted!");
393 EatToEndOfStatement();
396 if (TheCondState.TheCond != StartingCondState.TheCond ||
397 TheCondState.Ignore != StartingCondState.Ignore)
398 return TokError("unmatched .ifs or .elses");
400 // Check to see there are no empty DwarfFile slots.
401 const std::vector<MCDwarfFile *> &MCDwarfFiles =
402 getContext().getMCDwarfFiles();
403 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
404 if (!MCDwarfFiles[i])
405 TokError("unassigned file number: " + Twine(i) + " for .file directives");
408 // Finalize the output stream if there are no errors and if the client wants
410 if (!HadError && !NoFinalize)
416 void AsmParser::CheckForValidSection() {
417 if (!getStreamer().getCurrentSection()) {
418 TokError("expected section directive before assembly directive");
419 Out.SwitchSection(Ctx.getMachOSection(
421 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
422 0, SectionKind::getText()));
426 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
427 void AsmParser::EatToEndOfStatement() {
428 while (Lexer.isNot(AsmToken::EndOfStatement) &&
429 Lexer.isNot(AsmToken::Eof))
433 if (Lexer.is(AsmToken::EndOfStatement))
437 StringRef AsmParser::ParseStringToEndOfStatement() {
438 const char *Start = getTok().getLoc().getPointer();
440 while (Lexer.isNot(AsmToken::EndOfStatement) &&
441 Lexer.isNot(AsmToken::Eof))
444 const char *End = getTok().getLoc().getPointer();
445 return StringRef(Start, End - Start);
448 /// ParseParenExpr - Parse a paren expression and return it.
449 /// NOTE: This assumes the leading '(' has already been consumed.
451 /// parenexpr ::= expr)
453 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
454 if (ParseExpression(Res)) return true;
455 if (Lexer.isNot(AsmToken::RParen))
456 return TokError("expected ')' in parentheses expression");
457 EndLoc = Lexer.getLoc();
462 /// ParsePrimaryExpr - Parse a primary expression and return it.
463 /// primaryexpr ::= (parenexpr
464 /// primaryexpr ::= symbol
465 /// primaryexpr ::= number
466 /// primaryexpr ::= '.'
467 /// primaryexpr ::= ~,+,- primaryexpr
468 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
469 switch (Lexer.getKind()) {
471 return TokError("unknown token in expression");
472 case AsmToken::Exclaim:
473 Lex(); // Eat the operator.
474 if (ParsePrimaryExpr(Res, EndLoc))
476 Res = MCUnaryExpr::CreateLNot(Res, getContext());
478 case AsmToken::Dollar:
479 case AsmToken::String:
480 case AsmToken::Identifier: {
481 EndLoc = Lexer.getLoc();
483 StringRef Identifier;
484 if (ParseIdentifier(Identifier))
487 // This is a symbol reference.
488 std::pair<StringRef, StringRef> Split = Identifier.split('@');
489 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
491 // Mark the symbol as used in an expression.
492 Sym->setUsedInExpr(true);
494 // Lookup the symbol variant if used.
495 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
496 if (Split.first.size() != Identifier.size()) {
497 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
498 if (Variant == MCSymbolRefExpr::VK_Invalid) {
499 Variant = MCSymbolRefExpr::VK_None;
500 TokError("invalid variant '" + Split.second + "'");
504 // If this is an absolute variable reference, substitute it now to preserve
505 // semantics in the face of reassignment.
506 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
508 return Error(EndLoc, "unexpected modified on variable reference");
510 Res = Sym->getVariableValue();
514 // Otherwise create a symbol ref.
515 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
518 case AsmToken::Integer: {
519 SMLoc Loc = getTok().getLoc();
520 int64_t IntVal = getTok().getIntVal();
521 Res = MCConstantExpr::Create(IntVal, getContext());
522 EndLoc = Lexer.getLoc();
524 // Look for 'b' or 'f' following an Integer as a directional label
525 if (Lexer.getKind() == AsmToken::Identifier) {
526 StringRef IDVal = getTok().getString();
527 if (IDVal == "f" || IDVal == "b"){
528 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
529 IDVal == "f" ? 1 : 0);
530 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
532 if(IDVal == "b" && Sym->isUndefined())
533 return Error(Loc, "invalid reference to undefined symbol");
534 EndLoc = Lexer.getLoc();
535 Lex(); // Eat identifier.
540 case AsmToken::Dot: {
541 // This is a '.' reference, which references the current PC. Emit a
542 // temporary label to the streamer and refer to it.
543 MCSymbol *Sym = Ctx.CreateTempSymbol();
545 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
546 EndLoc = Lexer.getLoc();
547 Lex(); // Eat identifier.
551 case AsmToken::LParen:
552 Lex(); // Eat the '('.
553 return ParseParenExpr(Res, EndLoc);
554 case AsmToken::Minus:
555 Lex(); // Eat the operator.
556 if (ParsePrimaryExpr(Res, EndLoc))
558 Res = MCUnaryExpr::CreateMinus(Res, getContext());
561 Lex(); // Eat the operator.
562 if (ParsePrimaryExpr(Res, EndLoc))
564 Res = MCUnaryExpr::CreatePlus(Res, getContext());
566 case AsmToken::Tilde:
567 Lex(); // Eat the operator.
568 if (ParsePrimaryExpr(Res, EndLoc))
570 Res = MCUnaryExpr::CreateNot(Res, getContext());
575 bool AsmParser::ParseExpression(const MCExpr *&Res) {
577 return ParseExpression(Res, EndLoc);
581 AsmParser::ApplyModifierToExpr(const MCExpr *E,
582 MCSymbolRefExpr::VariantKind Variant) {
583 // Recurse over the given expression, rebuilding it to apply the given variant
584 // if there is exactly one symbol.
585 switch (E->getKind()) {
587 case MCExpr::Constant:
590 case MCExpr::SymbolRef: {
591 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
593 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
594 TokError("invalid variant on expression '" +
595 getTok().getIdentifier() + "' (already modified)");
599 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
602 case MCExpr::Unary: {
603 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
604 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
607 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
610 case MCExpr::Binary: {
611 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
612 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
613 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
618 if (!LHS) LHS = BE->getLHS();
619 if (!RHS) RHS = BE->getRHS();
621 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
625 assert(0 && "Invalid expression kind!");
629 /// ParseExpression - Parse an expression and return it.
631 /// expr ::= expr +,- expr -> lowest.
632 /// expr ::= expr |,^,&,! expr -> middle.
633 /// expr ::= expr *,/,%,<<,>> expr -> highest.
634 /// expr ::= primaryexpr
636 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
637 // Parse the expression.
639 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
642 // As a special case, we support 'a op b @ modifier' by rewriting the
643 // expression to include the modifier. This is inefficient, but in general we
644 // expect users to use 'a@modifier op b'.
645 if (Lexer.getKind() == AsmToken::At) {
648 if (Lexer.isNot(AsmToken::Identifier))
649 return TokError("unexpected symbol modifier following '@'");
651 MCSymbolRefExpr::VariantKind Variant =
652 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
653 if (Variant == MCSymbolRefExpr::VK_Invalid)
654 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
656 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
658 return TokError("invalid modifier '" + getTok().getIdentifier() +
659 "' (no symbols present)");
667 // Try to constant fold it up front, if possible.
669 if (Res->EvaluateAsAbsolute(Value))
670 Res = MCConstantExpr::Create(Value, getContext());
675 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
677 return ParseParenExpr(Res, EndLoc) ||
678 ParseBinOpRHS(1, Res, EndLoc);
681 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
684 SMLoc StartLoc = Lexer.getLoc();
685 if (ParseExpression(Expr))
688 if (!Expr->EvaluateAsAbsolute(Res))
689 return Error(StartLoc, "expected absolute expression");
694 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
695 MCBinaryExpr::Opcode &Kind) {
698 return 0; // not a binop.
700 // Lowest Precedence: &&, ||, @
701 case AsmToken::AmpAmp:
702 Kind = MCBinaryExpr::LAnd;
704 case AsmToken::PipePipe:
705 Kind = MCBinaryExpr::LOr;
709 // Low Precedence: |, &, ^
711 // FIXME: gas seems to support '!' as an infix operator?
713 Kind = MCBinaryExpr::Or;
715 case AsmToken::Caret:
716 Kind = MCBinaryExpr::Xor;
719 Kind = MCBinaryExpr::And;
722 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
723 case AsmToken::EqualEqual:
724 Kind = MCBinaryExpr::EQ;
726 case AsmToken::ExclaimEqual:
727 case AsmToken::LessGreater:
728 Kind = MCBinaryExpr::NE;
731 Kind = MCBinaryExpr::LT;
733 case AsmToken::LessEqual:
734 Kind = MCBinaryExpr::LTE;
736 case AsmToken::Greater:
737 Kind = MCBinaryExpr::GT;
739 case AsmToken::GreaterEqual:
740 Kind = MCBinaryExpr::GTE;
743 // High Intermediate Precedence: +, -
745 Kind = MCBinaryExpr::Add;
747 case AsmToken::Minus:
748 Kind = MCBinaryExpr::Sub;
751 // Highest Precedence: *, /, %, <<, >>
753 Kind = MCBinaryExpr::Mul;
755 case AsmToken::Slash:
756 Kind = MCBinaryExpr::Div;
758 case AsmToken::Percent:
759 Kind = MCBinaryExpr::Mod;
761 case AsmToken::LessLess:
762 Kind = MCBinaryExpr::Shl;
764 case AsmToken::GreaterGreater:
765 Kind = MCBinaryExpr::Shr;
771 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
772 /// Res contains the LHS of the expression on input.
773 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
776 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
777 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
779 // If the next token is lower precedence than we are allowed to eat, return
780 // successfully with what we ate already.
781 if (TokPrec < Precedence)
786 // Eat the next primary expression.
788 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
790 // If BinOp binds less tightly with RHS than the operator after RHS, let
791 // the pending operator take RHS as its LHS.
792 MCBinaryExpr::Opcode Dummy;
793 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
794 if (TokPrec < NextTokPrec) {
795 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
798 // Merge LHS and RHS according to operator.
799 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
807 /// ::= EndOfStatement
808 /// ::= Label* Directive ...Operands... EndOfStatement
809 /// ::= Label* Identifier OperandList* EndOfStatement
810 bool AsmParser::ParseStatement() {
811 if (Lexer.is(AsmToken::EndOfStatement)) {
817 // Statements always start with an identifier.
818 AsmToken ID = getTok();
819 SMLoc IDLoc = ID.getLoc();
821 int64_t LocalLabelVal = -1;
822 // GUESS allow an integer followed by a ':' as a directional local label
823 if (Lexer.is(AsmToken::Integer)) {
824 LocalLabelVal = getTok().getIntVal();
825 if (LocalLabelVal < 0) {
826 if (!TheCondState.Ignore)
827 return TokError("unexpected token at start of statement");
831 IDVal = getTok().getString();
832 Lex(); // Consume the integer token to be used as an identifier token.
833 if (Lexer.getKind() != AsmToken::Colon) {
834 if (!TheCondState.Ignore)
835 return TokError("unexpected token at start of statement");
839 else if (ParseIdentifier(IDVal)) {
840 if (!TheCondState.Ignore)
841 return TokError("unexpected token at start of statement");
845 // Handle conditional assembly here before checking for skipping. We
846 // have to do this so that .endif isn't skipped in a ".if 0" block for
849 return ParseDirectiveIf(IDLoc);
850 if (IDVal == ".elseif")
851 return ParseDirectiveElseIf(IDLoc);
852 if (IDVal == ".else")
853 return ParseDirectiveElse(IDLoc);
854 if (IDVal == ".endif")
855 return ParseDirectiveEndIf(IDLoc);
857 // If we are in a ".if 0" block, ignore this statement.
858 if (TheCondState.Ignore) {
859 EatToEndOfStatement();
863 // FIXME: Recurse on local labels?
865 // See what kind of statement we have.
866 switch (Lexer.getKind()) {
867 case AsmToken::Colon: {
868 CheckForValidSection();
870 // identifier ':' -> Label.
873 // Diagnose attempt to use a variable as a label.
875 // FIXME: Diagnostics. Note the location of the definition as a label.
876 // FIXME: This doesn't diagnose assignment to a symbol which has been
877 // implicitly marked as external.
879 if (LocalLabelVal == -1)
880 Sym = getContext().GetOrCreateSymbol(IDVal);
882 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
883 if (!Sym->isUndefined() || Sym->isVariable())
884 return Error(IDLoc, "invalid symbol redefinition");
889 // Consume any end of statement token, if present, to avoid spurious
890 // AddBlankLine calls().
891 if (Lexer.is(AsmToken::EndOfStatement)) {
893 if (Lexer.is(AsmToken::Eof))
897 return ParseStatement();
900 case AsmToken::Equal:
901 // identifier '=' ... -> assignment statement
904 return ParseAssignment(IDVal);
906 default: // Normal instruction or directive.
910 // If macros are enabled, check to see if this is a macro instantiation.
912 if (const Macro *M = MacroMap.lookup(IDVal))
913 return HandleMacroEntry(IDVal, IDLoc, M);
915 // Otherwise, we have a normal instruction or directive.
916 if (IDVal[0] == '.') {
917 // Assembler features
918 if (IDVal == ".set" || IDVal == ".equ")
919 return ParseDirectiveSet(IDVal);
923 if (IDVal == ".ascii")
924 return ParseDirectiveAscii(IDVal, false);
925 if (IDVal == ".asciz" || IDVal == ".string")
926 return ParseDirectiveAscii(IDVal, true);
928 if (IDVal == ".byte")
929 return ParseDirectiveValue(1);
930 if (IDVal == ".short")
931 return ParseDirectiveValue(2);
932 if (IDVal == ".value")
933 return ParseDirectiveValue(2);
934 if (IDVal == ".long")
935 return ParseDirectiveValue(4);
936 if (IDVal == ".quad")
937 return ParseDirectiveValue(8);
938 if (IDVal == ".single")
939 return ParseDirectiveRealValue(APFloat::IEEEsingle);
940 if (IDVal == ".double")
941 return ParseDirectiveRealValue(APFloat::IEEEdouble);
943 if (IDVal == ".align") {
944 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
945 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
947 if (IDVal == ".align32") {
948 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
949 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
951 if (IDVal == ".balign")
952 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
953 if (IDVal == ".balignw")
954 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
955 if (IDVal == ".balignl")
956 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
957 if (IDVal == ".p2align")
958 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
959 if (IDVal == ".p2alignw")
960 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
961 if (IDVal == ".p2alignl")
962 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
965 return ParseDirectiveOrg();
967 if (IDVal == ".fill")
968 return ParseDirectiveFill();
969 if (IDVal == ".space")
970 return ParseDirectiveSpace();
971 if (IDVal == ".zero")
972 return ParseDirectiveZero();
974 // Symbol attribute directives
976 if (IDVal == ".globl" || IDVal == ".global")
977 return ParseDirectiveSymbolAttribute(MCSA_Global);
978 // ELF only? Should it be here?
979 if (IDVal == ".local")
980 return ParseDirectiveSymbolAttribute(MCSA_Local);
981 if (IDVal == ".hidden")
982 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
983 if (IDVal == ".indirect_symbol")
984 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
985 if (IDVal == ".internal")
986 return ParseDirectiveSymbolAttribute(MCSA_Internal);
987 if (IDVal == ".lazy_reference")
988 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
989 if (IDVal == ".no_dead_strip")
990 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
991 if (IDVal == ".private_extern")
992 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
993 if (IDVal == ".protected")
994 return ParseDirectiveSymbolAttribute(MCSA_Protected);
995 if (IDVal == ".reference")
996 return ParseDirectiveSymbolAttribute(MCSA_Reference);
997 if (IDVal == ".weak")
998 return ParseDirectiveSymbolAttribute(MCSA_Weak);
999 if (IDVal == ".weak_definition")
1000 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1001 if (IDVal == ".weak_reference")
1002 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1003 if (IDVal == ".weak_def_can_be_hidden")
1004 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1006 if (IDVal == ".comm")
1007 return ParseDirectiveComm(/*IsLocal=*/false);
1008 if (IDVal == ".lcomm")
1009 return ParseDirectiveComm(/*IsLocal=*/true);
1011 if (IDVal == ".abort")
1012 return ParseDirectiveAbort();
1013 if (IDVal == ".include")
1014 return ParseDirectiveInclude();
1016 // Look up the handler in the handler table.
1017 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1018 DirectiveMap.lookup(IDVal);
1020 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1022 // Target hook for parsing target specific directives.
1023 if (!getTargetParser().ParseDirective(ID))
1026 Warning(IDLoc, "ignoring directive for now");
1027 EatToEndOfStatement();
1031 CheckForValidSection();
1033 // Canonicalize the opcode to lower case.
1034 SmallString<128> Opcode;
1035 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1036 Opcode.push_back(tolower(IDVal[i]));
1038 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1039 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1042 // Dump the parsed representation, if requested.
1043 if (getShowParsedOperands()) {
1044 SmallString<256> Str;
1045 raw_svector_ostream OS(Str);
1046 OS << "parsed instruction: [";
1047 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1050 ParsedOperands[i]->dump(OS);
1054 PrintMessage(IDLoc, OS.str(), "note");
1057 // If parsing succeeded, match the instruction.
1059 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
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(StringRef IDVal) {
1285 if (ParseIdentifier(Name))
1286 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1288 if (getLexer().isNot(AsmToken::Comma))
1289 return TokError("unexpected token in '" + Twine(IDVal) + "'");
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" ( , "string" )* ]
1355 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1356 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1357 CheckForValidSection();
1360 if (getLexer().isNot(AsmToken::String))
1361 return TokError("expected string in '" + Twine(IDVal) + "' 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 '" + Twine(IDVal) + "' 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 if (ParseExpression(Value))
1397 // Special case constant expressions to match code generator.
1398 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1399 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1401 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1403 if (getLexer().is(AsmToken::EndOfStatement))
1406 // FIXME: Improve diagnostic.
1407 if (getLexer().isNot(AsmToken::Comma))
1408 return TokError("unexpected token in directive");
1417 /// ParseDirectiveRealValue
1418 /// ::= (.single | .double) [ expression (, expression)* ]
1419 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1420 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1421 CheckForValidSection();
1424 // We don't truly support arithmetic on floating point expressions, so we
1425 // have to manually parse unary prefixes.
1427 if (getLexer().is(AsmToken::Minus)) {
1430 } else if (getLexer().is(AsmToken::Plus))
1433 if (getLexer().isNot(AsmToken::Integer) &&
1434 getLexer().isNot(AsmToken::Real))
1435 return TokError("unexpected token in directive");
1437 // Convert to an APFloat.
1438 APFloat Value(Semantics);
1439 if (Value.convertFromString(getTok().getString(),
1440 APFloat::rmNearestTiesToEven) ==
1441 APFloat::opInvalidOp)
1442 return TokError("invalid floating point literal");
1446 // Consume the numeric token.
1449 // Emit the value as an integer.
1450 APInt AsInt = Value.bitcastToAPInt();
1451 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1452 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1454 if (getLexer().is(AsmToken::EndOfStatement))
1457 if (getLexer().isNot(AsmToken::Comma))
1458 return TokError("unexpected token in directive");
1467 /// ParseDirectiveSpace
1468 /// ::= .space expression [ , expression ]
1469 bool AsmParser::ParseDirectiveSpace() {
1470 CheckForValidSection();
1473 if (ParseAbsoluteExpression(NumBytes))
1476 int64_t FillExpr = 0;
1477 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1478 if (getLexer().isNot(AsmToken::Comma))
1479 return TokError("unexpected token in '.space' directive");
1482 if (ParseAbsoluteExpression(FillExpr))
1485 if (getLexer().isNot(AsmToken::EndOfStatement))
1486 return TokError("unexpected token in '.space' directive");
1492 return TokError("invalid number of bytes in '.space' directive");
1494 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1495 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1500 /// ParseDirectiveZero
1501 /// ::= .zero expression
1502 bool AsmParser::ParseDirectiveZero() {
1503 CheckForValidSection();
1506 if (ParseAbsoluteExpression(NumBytes))
1510 if (getLexer().is(AsmToken::Comma)) {
1512 if (ParseAbsoluteExpression(Val))
1516 if (getLexer().isNot(AsmToken::EndOfStatement))
1517 return TokError("unexpected token in '.zero' directive");
1521 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1526 /// ParseDirectiveFill
1527 /// ::= .fill expression , expression , expression
1528 bool AsmParser::ParseDirectiveFill() {
1529 CheckForValidSection();
1532 if (ParseAbsoluteExpression(NumValues))
1535 if (getLexer().isNot(AsmToken::Comma))
1536 return TokError("unexpected token in '.fill' directive");
1540 if (ParseAbsoluteExpression(FillSize))
1543 if (getLexer().isNot(AsmToken::Comma))
1544 return TokError("unexpected token in '.fill' directive");
1548 if (ParseAbsoluteExpression(FillExpr))
1551 if (getLexer().isNot(AsmToken::EndOfStatement))
1552 return TokError("unexpected token in '.fill' directive");
1556 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1557 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1559 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1560 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1565 /// ParseDirectiveOrg
1566 /// ::= .org expression [ , expression ]
1567 bool AsmParser::ParseDirectiveOrg() {
1568 CheckForValidSection();
1570 const MCExpr *Offset;
1571 if (ParseExpression(Offset))
1574 // Parse optional fill expression.
1575 int64_t FillExpr = 0;
1576 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1577 if (getLexer().isNot(AsmToken::Comma))
1578 return TokError("unexpected token in '.org' directive");
1581 if (ParseAbsoluteExpression(FillExpr))
1584 if (getLexer().isNot(AsmToken::EndOfStatement))
1585 return TokError("unexpected token in '.org' directive");
1590 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1591 // has to be relative to the current section.
1592 getStreamer().EmitValueToOffset(Offset, FillExpr);
1597 /// ParseDirectiveAlign
1598 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1599 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1600 CheckForValidSection();
1602 SMLoc AlignmentLoc = getLexer().getLoc();
1604 if (ParseAbsoluteExpression(Alignment))
1608 bool HasFillExpr = false;
1609 int64_t FillExpr = 0;
1610 int64_t MaxBytesToFill = 0;
1611 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1612 if (getLexer().isNot(AsmToken::Comma))
1613 return TokError("unexpected token in directive");
1616 // The fill expression can be omitted while specifying a maximum number of
1617 // alignment bytes, e.g:
1619 if (getLexer().isNot(AsmToken::Comma)) {
1621 if (ParseAbsoluteExpression(FillExpr))
1625 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1626 if (getLexer().isNot(AsmToken::Comma))
1627 return TokError("unexpected token in directive");
1630 MaxBytesLoc = getLexer().getLoc();
1631 if (ParseAbsoluteExpression(MaxBytesToFill))
1634 if (getLexer().isNot(AsmToken::EndOfStatement))
1635 return TokError("unexpected token in directive");
1644 // Compute alignment in bytes.
1646 // FIXME: Diagnose overflow.
1647 if (Alignment >= 32) {
1648 Error(AlignmentLoc, "invalid alignment value");
1652 Alignment = 1ULL << Alignment;
1655 // Diagnose non-sensical max bytes to align.
1656 if (MaxBytesLoc.isValid()) {
1657 if (MaxBytesToFill < 1) {
1658 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1659 "many bytes, ignoring maximum bytes expression");
1663 if (MaxBytesToFill >= Alignment) {
1664 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1670 // Check whether we should use optimal code alignment for this .align
1672 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1673 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1674 ValueSize == 1 && UseCodeAlign) {
1675 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1677 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1678 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1685 /// ParseDirectiveSymbolAttribute
1686 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1687 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1688 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1692 if (ParseIdentifier(Name))
1693 return TokError("expected identifier in directive");
1695 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1697 getStreamer().EmitSymbolAttribute(Sym, Attr);
1699 if (getLexer().is(AsmToken::EndOfStatement))
1702 if (getLexer().isNot(AsmToken::Comma))
1703 return TokError("unexpected token in directive");
1712 /// ParseDirectiveComm
1713 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1714 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1715 CheckForValidSection();
1717 SMLoc IDLoc = getLexer().getLoc();
1719 if (ParseIdentifier(Name))
1720 return TokError("expected identifier in directive");
1722 // Handle the identifier as the key symbol.
1723 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1725 if (getLexer().isNot(AsmToken::Comma))
1726 return TokError("unexpected token in directive");
1730 SMLoc SizeLoc = getLexer().getLoc();
1731 if (ParseAbsoluteExpression(Size))
1734 int64_t Pow2Alignment = 0;
1735 SMLoc Pow2AlignmentLoc;
1736 if (getLexer().is(AsmToken::Comma)) {
1738 Pow2AlignmentLoc = getLexer().getLoc();
1739 if (ParseAbsoluteExpression(Pow2Alignment))
1742 // If this target takes alignments in bytes (not log) validate and convert.
1743 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1744 if (!isPowerOf2_64(Pow2Alignment))
1745 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1746 Pow2Alignment = Log2_64(Pow2Alignment);
1750 if (getLexer().isNot(AsmToken::EndOfStatement))
1751 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1755 // NOTE: a size of zero for a .comm should create a undefined symbol
1756 // but a size of .lcomm creates a bss symbol of size zero.
1758 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1759 "be less than zero");
1761 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1762 // may internally end up wanting an alignment in bytes.
1763 // FIXME: Diagnose overflow.
1764 if (Pow2Alignment < 0)
1765 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1766 "alignment, can't be less than zero");
1768 if (!Sym->isUndefined())
1769 return Error(IDLoc, "invalid symbol redefinition");
1771 // '.lcomm' is equivalent to '.zerofill'.
1772 // Create the Symbol as a common or local common with Size and Pow2Alignment
1774 getStreamer().EmitZerofill(Ctx.getMachOSection(
1775 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1776 0, SectionKind::getBSS()),
1777 Sym, Size, 1 << Pow2Alignment);
1781 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1785 /// ParseDirectiveAbort
1786 /// ::= .abort [... message ...]
1787 bool AsmParser::ParseDirectiveAbort() {
1788 // FIXME: Use loc from directive.
1789 SMLoc Loc = getLexer().getLoc();
1791 StringRef Str = ParseStringToEndOfStatement();
1792 if (getLexer().isNot(AsmToken::EndOfStatement))
1793 return TokError("unexpected token in '.abort' directive");
1798 Error(Loc, ".abort detected. Assembly stopping.");
1800 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1801 // FIXME: Actually abort assembly here.
1806 /// ParseDirectiveInclude
1807 /// ::= .include "filename"
1808 bool AsmParser::ParseDirectiveInclude() {
1809 if (getLexer().isNot(AsmToken::String))
1810 return TokError("expected string in '.include' directive");
1812 std::string Filename = getTok().getString();
1813 SMLoc IncludeLoc = getLexer().getLoc();
1816 if (getLexer().isNot(AsmToken::EndOfStatement))
1817 return TokError("unexpected token in '.include' directive");
1819 // Strip the quotes.
1820 Filename = Filename.substr(1, Filename.size()-2);
1822 // Attempt to switch the lexer to the included file before consuming the end
1823 // of statement to avoid losing it when we switch.
1824 if (EnterIncludeFile(Filename)) {
1825 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1832 /// ParseDirectiveIf
1833 /// ::= .if expression
1834 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1835 TheCondStack.push_back(TheCondState);
1836 TheCondState.TheCond = AsmCond::IfCond;
1837 if(TheCondState.Ignore) {
1838 EatToEndOfStatement();
1842 if (ParseAbsoluteExpression(ExprValue))
1845 if (getLexer().isNot(AsmToken::EndOfStatement))
1846 return TokError("unexpected token in '.if' directive");
1850 TheCondState.CondMet = ExprValue;
1851 TheCondState.Ignore = !TheCondState.CondMet;
1857 /// ParseDirectiveElseIf
1858 /// ::= .elseif expression
1859 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1860 if (TheCondState.TheCond != AsmCond::IfCond &&
1861 TheCondState.TheCond != AsmCond::ElseIfCond)
1862 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1864 TheCondState.TheCond = AsmCond::ElseIfCond;
1866 bool LastIgnoreState = false;
1867 if (!TheCondStack.empty())
1868 LastIgnoreState = TheCondStack.back().Ignore;
1869 if (LastIgnoreState || TheCondState.CondMet) {
1870 TheCondState.Ignore = true;
1871 EatToEndOfStatement();
1875 if (ParseAbsoluteExpression(ExprValue))
1878 if (getLexer().isNot(AsmToken::EndOfStatement))
1879 return TokError("unexpected token in '.elseif' directive");
1882 TheCondState.CondMet = ExprValue;
1883 TheCondState.Ignore = !TheCondState.CondMet;
1889 /// ParseDirectiveElse
1891 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1892 if (getLexer().isNot(AsmToken::EndOfStatement))
1893 return TokError("unexpected token in '.else' directive");
1897 if (TheCondState.TheCond != AsmCond::IfCond &&
1898 TheCondState.TheCond != AsmCond::ElseIfCond)
1899 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1901 TheCondState.TheCond = AsmCond::ElseCond;
1902 bool LastIgnoreState = false;
1903 if (!TheCondStack.empty())
1904 LastIgnoreState = TheCondStack.back().Ignore;
1905 if (LastIgnoreState || TheCondState.CondMet)
1906 TheCondState.Ignore = true;
1908 TheCondState.Ignore = false;
1913 /// ParseDirectiveEndIf
1915 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1916 if (getLexer().isNot(AsmToken::EndOfStatement))
1917 return TokError("unexpected token in '.endif' directive");
1921 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1922 TheCondStack.empty())
1923 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1925 if (!TheCondStack.empty()) {
1926 TheCondState = TheCondStack.back();
1927 TheCondStack.pop_back();
1933 /// ParseDirectiveFile
1934 /// ::= .file [number] string
1935 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1936 // FIXME: I'm not sure what this is.
1937 int64_t FileNumber = -1;
1938 SMLoc FileNumberLoc = getLexer().getLoc();
1939 if (getLexer().is(AsmToken::Integer)) {
1940 FileNumber = getTok().getIntVal();
1944 return TokError("file number less than one");
1947 if (getLexer().isNot(AsmToken::String))
1948 return TokError("unexpected token in '.file' directive");
1950 StringRef Filename = getTok().getString();
1951 Filename = Filename.substr(1, Filename.size()-2);
1954 if (getLexer().isNot(AsmToken::EndOfStatement))
1955 return TokError("unexpected token in '.file' directive");
1957 if (FileNumber == -1)
1958 getStreamer().EmitFileDirective(Filename);
1960 if (getContext().GetDwarfFile(Filename, FileNumber) == 0)
1961 Error(FileNumberLoc, "file number already allocated");
1962 getStreamer().EmitDwarfFileDirective(FileNumber, Filename);
1968 /// ParseDirectiveLine
1969 /// ::= .line [number]
1970 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1971 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1972 if (getLexer().isNot(AsmToken::Integer))
1973 return TokError("unexpected token in '.line' directive");
1975 int64_t LineNumber = getTok().getIntVal();
1979 // FIXME: Do something with the .line.
1982 if (getLexer().isNot(AsmToken::EndOfStatement))
1983 return TokError("unexpected token in '.line' directive");
1989 /// ParseDirectiveLoc
1990 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
1991 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
1992 /// The first number is a file number, must have been previously assigned with
1993 /// a .file directive, the second number is the line number and optionally the
1994 /// third number is a column position (zero if not specified). The remaining
1995 /// optional items are .loc sub-directives.
1996 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1998 if (getLexer().isNot(AsmToken::Integer))
1999 return TokError("unexpected token in '.loc' directive");
2000 int64_t FileNumber = getTok().getIntVal();
2002 return TokError("file number less than one in '.loc' directive");
2003 if (!getContext().isValidDwarfFileNumber(FileNumber))
2004 return TokError("unassigned file number in '.loc' directive");
2007 int64_t LineNumber = 0;
2008 if (getLexer().is(AsmToken::Integer)) {
2009 LineNumber = getTok().getIntVal();
2011 return TokError("line number less than one in '.loc' directive");
2015 int64_t ColumnPos = 0;
2016 if (getLexer().is(AsmToken::Integer)) {
2017 ColumnPos = getTok().getIntVal();
2019 return TokError("column position less than zero in '.loc' directive");
2023 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2025 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2027 if (getLexer().is(AsmToken::EndOfStatement))
2031 SMLoc Loc = getTok().getLoc();
2032 if (getParser().ParseIdentifier(Name))
2033 return TokError("unexpected token in '.loc' directive");
2035 if (Name == "basic_block")
2036 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2037 else if (Name == "prologue_end")
2038 Flags |= DWARF2_FLAG_PROLOGUE_END;
2039 else if (Name == "epilogue_begin")
2040 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2041 else if (Name == "is_stmt") {
2042 SMLoc Loc = getTok().getLoc();
2043 const MCExpr *Value;
2044 if (getParser().ParseExpression(Value))
2046 // The expression must be the constant 0 or 1.
2047 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2048 int Value = MCE->getValue();
2050 Flags &= ~DWARF2_FLAG_IS_STMT;
2051 else if (Value == 1)
2052 Flags |= DWARF2_FLAG_IS_STMT;
2054 return Error(Loc, "is_stmt value not 0 or 1");
2057 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2060 else if (Name == "isa") {
2061 SMLoc Loc = getTok().getLoc();
2062 const MCExpr *Value;
2063 if (getParser().ParseExpression(Value))
2065 // The expression must be a constant greater or equal to 0.
2066 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2067 int Value = MCE->getValue();
2069 return Error(Loc, "isa number less than zero");
2073 return Error(Loc, "isa number not a constant value");
2077 return Error(Loc, "unknown sub-directive in '.loc' directive");
2080 if (getLexer().is(AsmToken::EndOfStatement))
2085 getContext().setCurrentDwarfLoc(FileNumber, LineNumber, ColumnPos, Flags,Isa);
2090 /// ParseDirectiveStabs
2091 /// ::= .stabs string, number, number, number
2092 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2093 SMLoc DirectiveLoc) {
2094 return TokError("unsupported directive '" + Directive + "'");
2097 /// ParseDirectiveMacrosOnOff
2100 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2101 SMLoc DirectiveLoc) {
2102 if (getLexer().isNot(AsmToken::EndOfStatement))
2103 return Error(getLexer().getLoc(),
2104 "unexpected token in '" + Directive + "' directive");
2106 getParser().MacrosEnabled = Directive == ".macros_on";
2111 /// ParseDirectiveMacro
2113 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2114 SMLoc DirectiveLoc) {
2116 if (getParser().ParseIdentifier(Name))
2117 return TokError("expected identifier in directive");
2119 if (getLexer().isNot(AsmToken::EndOfStatement))
2120 return TokError("unexpected token in '.macro' directive");
2122 // Eat the end of statement.
2125 AsmToken EndToken, StartToken = getTok();
2127 // Lex the macro definition.
2129 // Check whether we have reached the end of the file.
2130 if (getLexer().is(AsmToken::Eof))
2131 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2133 // Otherwise, check whether we have reach the .endmacro.
2134 if (getLexer().is(AsmToken::Identifier) &&
2135 (getTok().getIdentifier() == ".endm" ||
2136 getTok().getIdentifier() == ".endmacro")) {
2137 EndToken = getTok();
2139 if (getLexer().isNot(AsmToken::EndOfStatement))
2140 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2145 // Otherwise, scan til the end of the statement.
2146 getParser().EatToEndOfStatement();
2149 if (getParser().MacroMap.lookup(Name)) {
2150 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2153 const char *BodyStart = StartToken.getLoc().getPointer();
2154 const char *BodyEnd = EndToken.getLoc().getPointer();
2155 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2156 getParser().MacroMap[Name] = new Macro(Name, Body);
2160 /// ParseDirectiveEndMacro
2163 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2164 SMLoc DirectiveLoc) {
2165 if (getLexer().isNot(AsmToken::EndOfStatement))
2166 return TokError("unexpected token in '" + Directive + "' directive");
2168 // If we are inside a macro instantiation, terminate the current
2170 if (!getParser().ActiveMacros.empty()) {
2171 getParser().HandleMacroExit();
2175 // Otherwise, this .endmacro is a stray entry in the file; well formed
2176 // .endmacro directives are handled during the macro definition parsing.
2177 return TokError("unexpected '" + Directive + "' in file, "
2178 "no current macro definition");
2181 void GenericAsmParser::ParseUleb128(uint64_t Value) {
2182 const uint64_t Mask = (1 << 7) - 1;
2184 unsigned Byte = Value & Mask;
2186 if (Value) // Not the last one
2188 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2192 void GenericAsmParser::ParseSleb128(int64_t Value) {
2193 const int64_t Mask = (1 << 7) - 1;
2195 unsigned Byte = Value & Mask;
2197 bool Done = ((Value == 0 && (Byte & 0x40) == 0) ||
2198 (Value == -1 && (Byte & 0x40) != 0));
2201 getStreamer().EmitIntValue(Byte, 1, DEFAULT_ADDRSPACE);
2207 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2209 if (getParser().ParseAbsoluteExpression(Value))
2212 if (getLexer().isNot(AsmToken::EndOfStatement))
2213 return TokError("unexpected token in directive");
2215 if (DirName[1] == 's')
2216 ParseSleb128(Value);
2218 ParseUleb128(Value);
2223 /// \brief Create an MCAsmParser instance.
2224 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2225 MCContext &C, MCStreamer &Out,
2226 const MCAsmInfo &MAI) {
2227 return new AsmParser(T, SM, C, Out, MAI);