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);
197 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
199 bool ParseDirectiveAbort(); // ".abort"
200 bool ParseDirectiveInclude(); // ".include"
202 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
203 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
204 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
205 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
207 /// ParseEscapedString - Parse the current token as a string which may include
208 /// escaped characters and return the string contents.
209 bool ParseEscapedString(std::string &Data);
211 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
212 MCSymbolRefExpr::VariantKind Variant);
215 /// \brief Generic implementations of directive handling, etc. which is shared
216 /// (or the default, at least) for all assembler parser.
217 class GenericAsmParser : public MCAsmParserExtension {
218 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
219 void AddDirectiveHandler(StringRef Directive) {
220 getParser().AddDirectiveHandler(this, Directive,
221 HandleDirective<GenericAsmParser, Handler>);
225 GenericAsmParser() {}
227 AsmParser &getParser() {
228 return (AsmParser&) this->MCAsmParserExtension::getParser();
231 virtual void Initialize(MCAsmParser &Parser) {
232 // Call the base implementation.
233 this->MCAsmParserExtension::Initialize(Parser);
235 // Debugging directives.
236 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
237 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
238 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
239 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
242 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
244 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
246 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
247 ".cfi_def_cfa_offset");
248 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
249 ".cfi_def_cfa_register");
250 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
253 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
255 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
258 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
260 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
262 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
263 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
264 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
266 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
267 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
270 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
271 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
272 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
273 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
274 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
275 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
276 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
277 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
278 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
279 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
281 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
282 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
283 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
285 bool ParseDirectiveLEB128(StringRef, SMLoc);
292 extern MCAsmParserExtension *createDarwinAsmParser();
293 extern MCAsmParserExtension *createELFAsmParser();
294 extern MCAsmParserExtension *createCOFFAsmParser();
298 enum { DEFAULT_ADDRSPACE = 0 };
300 AsmParser::AsmParser(const Target &T, SourceMgr &_SM, MCContext &_Ctx,
301 MCStreamer &_Out, const MCAsmInfo &_MAI)
302 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM),
303 GenericParser(new GenericAsmParser), PlatformParser(0),
304 CurBuffer(0), MacrosEnabled(true) {
305 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
307 // Initialize the generic parser.
308 GenericParser->Initialize(*this);
310 // Initialize the platform / file format parser.
312 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
314 if (_MAI.hasMicrosoftFastStdCallMangling()) {
315 PlatformParser = createCOFFAsmParser();
316 PlatformParser->Initialize(*this);
317 } else if (_MAI.hasSubsectionsViaSymbols()) {
318 PlatformParser = createDarwinAsmParser();
319 PlatformParser->Initialize(*this);
321 PlatformParser = createELFAsmParser();
322 PlatformParser->Initialize(*this);
326 AsmParser::~AsmParser() {
327 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
329 // Destroy any macros.
330 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
331 ie = MacroMap.end(); it != ie; ++it)
332 delete it->getValue();
334 delete PlatformParser;
335 delete GenericParser;
338 void AsmParser::PrintMacroInstantiations() {
339 // Print the active macro instantiation stack.
340 for (std::vector<MacroInstantiation*>::const_reverse_iterator
341 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
342 PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
346 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
347 PrintMessage(L, Msg, "warning");
348 PrintMacroInstantiations();
351 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
353 PrintMessage(L, Msg, "error");
354 PrintMacroInstantiations();
358 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
359 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
365 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
370 void AsmParser::JumpToLoc(SMLoc Loc) {
371 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
372 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
375 const AsmToken &AsmParser::Lex() {
376 const AsmToken *tok = &Lexer.Lex();
378 if (tok->is(AsmToken::Eof)) {
379 // If this is the end of an included file, pop the parent file off the
381 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
382 if (ParentIncludeLoc != SMLoc()) {
383 JumpToLoc(ParentIncludeLoc);
388 if (tok->is(AsmToken::Error))
389 Error(Lexer.getErrLoc(), Lexer.getErr());
394 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
395 // Create the initial section, if requested.
396 if (!NoInitialTextSection)
403 AsmCond StartingCondState = TheCondState;
405 // While we have input, parse each statement.
406 while (Lexer.isNot(AsmToken::Eof)) {
407 if (!ParseStatement()) continue;
409 // We had an error, validate that one was emitted and recover by skipping to
411 assert(HadError && "Parse statement returned an error, but none emitted!");
412 EatToEndOfStatement();
415 if (TheCondState.TheCond != StartingCondState.TheCond ||
416 TheCondState.Ignore != StartingCondState.Ignore)
417 return TokError("unmatched .ifs or .elses");
419 // Check to see there are no empty DwarfFile slots.
420 const std::vector<MCDwarfFile *> &MCDwarfFiles =
421 getContext().getMCDwarfFiles();
422 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
423 if (!MCDwarfFiles[i])
424 TokError("unassigned file number: " + Twine(i) + " for .file directives");
427 // Finalize the output stream if there are no errors and if the client wants
429 if (!HadError && !NoFinalize)
435 void AsmParser::CheckForValidSection() {
436 if (!getStreamer().getCurrentSection()) {
437 TokError("expected section directive before assembly directive");
438 Out.SwitchSection(Ctx.getMachOSection(
440 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
441 0, SectionKind::getText()));
445 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
446 void AsmParser::EatToEndOfStatement() {
447 while (Lexer.isNot(AsmToken::EndOfStatement) &&
448 Lexer.isNot(AsmToken::Eof))
452 if (Lexer.is(AsmToken::EndOfStatement))
456 StringRef AsmParser::ParseStringToEndOfStatement() {
457 const char *Start = getTok().getLoc().getPointer();
459 while (Lexer.isNot(AsmToken::EndOfStatement) &&
460 Lexer.isNot(AsmToken::Eof))
463 const char *End = getTok().getLoc().getPointer();
464 return StringRef(Start, End - Start);
467 /// ParseParenExpr - Parse a paren expression and return it.
468 /// NOTE: This assumes the leading '(' has already been consumed.
470 /// parenexpr ::= expr)
472 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
473 if (ParseExpression(Res)) return true;
474 if (Lexer.isNot(AsmToken::RParen))
475 return TokError("expected ')' in parentheses expression");
476 EndLoc = Lexer.getLoc();
481 /// ParsePrimaryExpr - Parse a primary expression and return it.
482 /// primaryexpr ::= (parenexpr
483 /// primaryexpr ::= symbol
484 /// primaryexpr ::= number
485 /// primaryexpr ::= '.'
486 /// primaryexpr ::= ~,+,- primaryexpr
487 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
488 switch (Lexer.getKind()) {
490 return TokError("unknown token in expression");
491 case AsmToken::Exclaim:
492 Lex(); // Eat the operator.
493 if (ParsePrimaryExpr(Res, EndLoc))
495 Res = MCUnaryExpr::CreateLNot(Res, getContext());
497 case AsmToken::Dollar:
498 case AsmToken::String:
499 case AsmToken::Identifier: {
500 EndLoc = Lexer.getLoc();
502 StringRef Identifier;
503 if (ParseIdentifier(Identifier))
506 // This is a symbol reference.
507 std::pair<StringRef, StringRef> Split = Identifier.split('@');
508 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
510 // Lookup the symbol variant if used.
511 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
512 if (Split.first.size() != Identifier.size()) {
513 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
514 if (Variant == MCSymbolRefExpr::VK_Invalid) {
515 Variant = MCSymbolRefExpr::VK_None;
516 TokError("invalid variant '" + Split.second + "'");
520 // If this is an absolute variable reference, substitute it now to preserve
521 // semantics in the face of reassignment.
522 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
524 return Error(EndLoc, "unexpected modifier on variable reference");
526 Res = Sym->getVariableValue();
530 // Otherwise create a symbol ref.
531 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
534 case AsmToken::Integer: {
535 SMLoc Loc = getTok().getLoc();
536 int64_t IntVal = getTok().getIntVal();
537 Res = MCConstantExpr::Create(IntVal, getContext());
538 EndLoc = Lexer.getLoc();
540 // Look for 'b' or 'f' following an Integer as a directional label
541 if (Lexer.getKind() == AsmToken::Identifier) {
542 StringRef IDVal = getTok().getString();
543 if (IDVal == "f" || IDVal == "b"){
544 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
545 IDVal == "f" ? 1 : 0);
546 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
548 if(IDVal == "b" && Sym->isUndefined())
549 return Error(Loc, "invalid reference to undefined symbol");
550 EndLoc = Lexer.getLoc();
551 Lex(); // Eat identifier.
556 case AsmToken::Dot: {
557 // This is a '.' reference, which references the current PC. Emit a
558 // temporary label to the streamer and refer to it.
559 MCSymbol *Sym = Ctx.CreateTempSymbol();
561 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
562 EndLoc = Lexer.getLoc();
563 Lex(); // Eat identifier.
567 case AsmToken::LParen:
568 Lex(); // Eat the '('.
569 return ParseParenExpr(Res, EndLoc);
570 case AsmToken::Minus:
571 Lex(); // Eat the operator.
572 if (ParsePrimaryExpr(Res, EndLoc))
574 Res = MCUnaryExpr::CreateMinus(Res, getContext());
577 Lex(); // Eat the operator.
578 if (ParsePrimaryExpr(Res, EndLoc))
580 Res = MCUnaryExpr::CreatePlus(Res, getContext());
582 case AsmToken::Tilde:
583 Lex(); // Eat the operator.
584 if (ParsePrimaryExpr(Res, EndLoc))
586 Res = MCUnaryExpr::CreateNot(Res, getContext());
591 bool AsmParser::ParseExpression(const MCExpr *&Res) {
593 return ParseExpression(Res, EndLoc);
597 AsmParser::ApplyModifierToExpr(const MCExpr *E,
598 MCSymbolRefExpr::VariantKind Variant) {
599 // Recurse over the given expression, rebuilding it to apply the given variant
600 // if there is exactly one symbol.
601 switch (E->getKind()) {
603 case MCExpr::Constant:
606 case MCExpr::SymbolRef: {
607 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
609 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
610 TokError("invalid variant on expression '" +
611 getTok().getIdentifier() + "' (already modified)");
615 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
618 case MCExpr::Unary: {
619 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
620 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
623 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
626 case MCExpr::Binary: {
627 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
628 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
629 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
634 if (!LHS) LHS = BE->getLHS();
635 if (!RHS) RHS = BE->getRHS();
637 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
641 assert(0 && "Invalid expression kind!");
645 /// ParseExpression - Parse an expression and return it.
647 /// expr ::= expr +,- expr -> lowest.
648 /// expr ::= expr |,^,&,! expr -> middle.
649 /// expr ::= expr *,/,%,<<,>> expr -> highest.
650 /// expr ::= primaryexpr
652 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
653 // Parse the expression.
655 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
658 // As a special case, we support 'a op b @ modifier' by rewriting the
659 // expression to include the modifier. This is inefficient, but in general we
660 // expect users to use 'a@modifier op b'.
661 if (Lexer.getKind() == AsmToken::At) {
664 if (Lexer.isNot(AsmToken::Identifier))
665 return TokError("unexpected symbol modifier following '@'");
667 MCSymbolRefExpr::VariantKind Variant =
668 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
669 if (Variant == MCSymbolRefExpr::VK_Invalid)
670 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
672 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
674 return TokError("invalid modifier '" + getTok().getIdentifier() +
675 "' (no symbols present)");
683 // Try to constant fold it up front, if possible.
685 if (Res->EvaluateAsAbsolute(Value))
686 Res = MCConstantExpr::Create(Value, getContext());
691 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
693 return ParseParenExpr(Res, EndLoc) ||
694 ParseBinOpRHS(1, Res, EndLoc);
697 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
700 SMLoc StartLoc = Lexer.getLoc();
701 if (ParseExpression(Expr))
704 if (!Expr->EvaluateAsAbsolute(Res))
705 return Error(StartLoc, "expected absolute expression");
710 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
711 MCBinaryExpr::Opcode &Kind) {
714 return 0; // not a binop.
716 // Lowest Precedence: &&, ||, @
717 case AsmToken::AmpAmp:
718 Kind = MCBinaryExpr::LAnd;
720 case AsmToken::PipePipe:
721 Kind = MCBinaryExpr::LOr;
725 // Low Precedence: |, &, ^
727 // FIXME: gas seems to support '!' as an infix operator?
729 Kind = MCBinaryExpr::Or;
731 case AsmToken::Caret:
732 Kind = MCBinaryExpr::Xor;
735 Kind = MCBinaryExpr::And;
738 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
739 case AsmToken::EqualEqual:
740 Kind = MCBinaryExpr::EQ;
742 case AsmToken::ExclaimEqual:
743 case AsmToken::LessGreater:
744 Kind = MCBinaryExpr::NE;
747 Kind = MCBinaryExpr::LT;
749 case AsmToken::LessEqual:
750 Kind = MCBinaryExpr::LTE;
752 case AsmToken::Greater:
753 Kind = MCBinaryExpr::GT;
755 case AsmToken::GreaterEqual:
756 Kind = MCBinaryExpr::GTE;
759 // High Intermediate Precedence: +, -
761 Kind = MCBinaryExpr::Add;
763 case AsmToken::Minus:
764 Kind = MCBinaryExpr::Sub;
767 // Highest Precedence: *, /, %, <<, >>
769 Kind = MCBinaryExpr::Mul;
771 case AsmToken::Slash:
772 Kind = MCBinaryExpr::Div;
774 case AsmToken::Percent:
775 Kind = MCBinaryExpr::Mod;
777 case AsmToken::LessLess:
778 Kind = MCBinaryExpr::Shl;
780 case AsmToken::GreaterGreater:
781 Kind = MCBinaryExpr::Shr;
787 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
788 /// Res contains the LHS of the expression on input.
789 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
792 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
793 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
795 // If the next token is lower precedence than we are allowed to eat, return
796 // successfully with what we ate already.
797 if (TokPrec < Precedence)
802 // Eat the next primary expression.
804 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
806 // If BinOp binds less tightly with RHS than the operator after RHS, let
807 // the pending operator take RHS as its LHS.
808 MCBinaryExpr::Opcode Dummy;
809 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
810 if (TokPrec < NextTokPrec) {
811 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
814 // Merge LHS and RHS according to operator.
815 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
823 /// ::= EndOfStatement
824 /// ::= Label* Directive ...Operands... EndOfStatement
825 /// ::= Label* Identifier OperandList* EndOfStatement
826 bool AsmParser::ParseStatement() {
827 if (Lexer.is(AsmToken::EndOfStatement)) {
833 // Statements always start with an identifier.
834 AsmToken ID = getTok();
835 SMLoc IDLoc = ID.getLoc();
837 int64_t LocalLabelVal = -1;
838 // GUESS allow an integer followed by a ':' as a directional local label
839 if (Lexer.is(AsmToken::Integer)) {
840 LocalLabelVal = getTok().getIntVal();
841 if (LocalLabelVal < 0) {
842 if (!TheCondState.Ignore)
843 return TokError("unexpected token at start of statement");
847 IDVal = getTok().getString();
848 Lex(); // Consume the integer token to be used as an identifier token.
849 if (Lexer.getKind() != AsmToken::Colon) {
850 if (!TheCondState.Ignore)
851 return TokError("unexpected token at start of statement");
855 else if (ParseIdentifier(IDVal)) {
856 if (!TheCondState.Ignore)
857 return TokError("unexpected token at start of statement");
861 // Handle conditional assembly here before checking for skipping. We
862 // have to do this so that .endif isn't skipped in a ".if 0" block for
865 return ParseDirectiveIf(IDLoc);
866 if (IDVal == ".elseif")
867 return ParseDirectiveElseIf(IDLoc);
868 if (IDVal == ".else")
869 return ParseDirectiveElse(IDLoc);
870 if (IDVal == ".endif")
871 return ParseDirectiveEndIf(IDLoc);
873 // If we are in a ".if 0" block, ignore this statement.
874 if (TheCondState.Ignore) {
875 EatToEndOfStatement();
879 // FIXME: Recurse on local labels?
881 // See what kind of statement we have.
882 switch (Lexer.getKind()) {
883 case AsmToken::Colon: {
884 CheckForValidSection();
886 // identifier ':' -> Label.
889 // Diagnose attempt to use a variable as a label.
891 // FIXME: Diagnostics. Note the location of the definition as a label.
892 // FIXME: This doesn't diagnose assignment to a symbol which has been
893 // implicitly marked as external.
895 if (LocalLabelVal == -1)
896 Sym = getContext().GetOrCreateSymbol(IDVal);
898 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
899 if (!Sym->isUndefined() || Sym->isVariable())
900 return Error(IDLoc, "invalid symbol redefinition");
905 // Consume any end of statement token, if present, to avoid spurious
906 // AddBlankLine calls().
907 if (Lexer.is(AsmToken::EndOfStatement)) {
909 if (Lexer.is(AsmToken::Eof))
913 return ParseStatement();
916 case AsmToken::Equal:
917 // identifier '=' ... -> assignment statement
920 return ParseAssignment(IDVal);
922 default: // Normal instruction or directive.
926 // If macros are enabled, check to see if this is a macro instantiation.
928 if (const Macro *M = MacroMap.lookup(IDVal))
929 return HandleMacroEntry(IDVal, IDLoc, M);
931 // Otherwise, we have a normal instruction or directive.
932 if (IDVal[0] == '.') {
933 // Assembler features
934 if (IDVal == ".set" || IDVal == ".equ")
935 return ParseDirectiveSet(IDVal);
939 if (IDVal == ".ascii")
940 return ParseDirectiveAscii(IDVal, false);
941 if (IDVal == ".asciz" || IDVal == ".string")
942 return ParseDirectiveAscii(IDVal, true);
944 if (IDVal == ".byte")
945 return ParseDirectiveValue(1);
946 if (IDVal == ".short")
947 return ParseDirectiveValue(2);
948 if (IDVal == ".value")
949 return ParseDirectiveValue(2);
950 if (IDVal == ".2byte")
951 return ParseDirectiveValue(2);
952 if (IDVal == ".long")
953 return ParseDirectiveValue(4);
955 return ParseDirectiveValue(4);
956 if (IDVal == ".4byte")
957 return ParseDirectiveValue(4);
958 if (IDVal == ".quad")
959 return ParseDirectiveValue(8);
960 if (IDVal == ".8byte")
961 return ParseDirectiveValue(8);
962 if (IDVal == ".single")
963 return ParseDirectiveRealValue(APFloat::IEEEsingle);
964 if (IDVal == ".double")
965 return ParseDirectiveRealValue(APFloat::IEEEdouble);
967 if (IDVal == ".align") {
968 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
969 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
971 if (IDVal == ".align32") {
972 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
973 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
975 if (IDVal == ".balign")
976 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
977 if (IDVal == ".balignw")
978 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
979 if (IDVal == ".balignl")
980 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
981 if (IDVal == ".p2align")
982 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
983 if (IDVal == ".p2alignw")
984 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
985 if (IDVal == ".p2alignl")
986 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
989 return ParseDirectiveOrg();
991 if (IDVal == ".fill")
992 return ParseDirectiveFill();
993 if (IDVal == ".space")
994 return ParseDirectiveSpace();
995 if (IDVal == ".zero")
996 return ParseDirectiveZero();
998 // Symbol attribute directives
1000 if (IDVal == ".globl" || IDVal == ".global")
1001 return ParseDirectiveSymbolAttribute(MCSA_Global);
1002 // ELF only? Should it be here?
1003 if (IDVal == ".local")
1004 return ParseDirectiveSymbolAttribute(MCSA_Local);
1005 if (IDVal == ".hidden")
1006 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
1007 if (IDVal == ".indirect_symbol")
1008 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1009 if (IDVal == ".internal")
1010 return ParseDirectiveSymbolAttribute(MCSA_Internal);
1011 if (IDVal == ".lazy_reference")
1012 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1013 if (IDVal == ".no_dead_strip")
1014 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1015 if (IDVal == ".symbol_resolver")
1016 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1017 if (IDVal == ".private_extern")
1018 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1019 if (IDVal == ".protected")
1020 return ParseDirectiveSymbolAttribute(MCSA_Protected);
1021 if (IDVal == ".reference")
1022 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1023 if (IDVal == ".weak")
1024 return ParseDirectiveSymbolAttribute(MCSA_Weak);
1025 if (IDVal == ".weak_definition")
1026 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1027 if (IDVal == ".weak_reference")
1028 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1029 if (IDVal == ".weak_def_can_be_hidden")
1030 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1032 if (IDVal == ".comm")
1033 return ParseDirectiveComm(/*IsLocal=*/false);
1034 if (IDVal == ".lcomm")
1035 return ParseDirectiveComm(/*IsLocal=*/true);
1037 if (IDVal == ".abort")
1038 return ParseDirectiveAbort();
1039 if (IDVal == ".include")
1040 return ParseDirectiveInclude();
1042 // Look up the handler in the handler table.
1043 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1044 DirectiveMap.lookup(IDVal);
1046 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1048 // Target hook for parsing target specific directives.
1049 if (!getTargetParser().ParseDirective(ID))
1052 Warning(IDLoc, "ignoring directive for now");
1053 EatToEndOfStatement();
1057 CheckForValidSection();
1059 // Canonicalize the opcode to lower case.
1060 SmallString<128> Opcode;
1061 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1062 Opcode.push_back(tolower(IDVal[i]));
1064 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1065 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1068 // Dump the parsed representation, if requested.
1069 if (getShowParsedOperands()) {
1070 SmallString<256> Str;
1071 raw_svector_ostream OS(Str);
1072 OS << "parsed instruction: [";
1073 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1076 ParsedOperands[i]->dump(OS);
1080 PrintMessage(IDLoc, OS.str(), "note");
1083 // If parsing succeeded, match the instruction.
1085 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1088 // Free any parsed operands.
1089 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1090 delete ParsedOperands[i];
1092 // Don't skip the rest of the line, the instruction parser is responsible for
1097 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1098 const std::vector<std::vector<AsmToken> > &A)
1099 : TheMacro(M), InstantiationLoc(IL), ExitLoc(EL)
1101 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1102 // to hold the macro body with substitutions.
1103 SmallString<256> Buf;
1104 raw_svector_ostream OS(Buf);
1106 StringRef Body = M->Body;
1107 while (!Body.empty()) {
1108 // Scan for the next substitution.
1109 std::size_t End = Body.size(), Pos = 0;
1110 for (; Pos != End; ++Pos) {
1111 // Check for a substitution or escape.
1112 if (Body[Pos] != '$' || Pos + 1 == End)
1115 char Next = Body[Pos + 1];
1116 if (Next == '$' || Next == 'n' || isdigit(Next))
1121 OS << Body.slice(0, Pos);
1123 // Check if we reached the end.
1127 switch (Body[Pos+1]) {
1133 // $n => number of arguments
1138 // $[0-9] => argument
1140 // Missing arguments are ignored.
1141 unsigned Index = Body[Pos+1] - '0';
1142 if (Index >= A.size())
1145 // Otherwise substitute with the token values, with spaces eliminated.
1146 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1147 ie = A[Index].end(); it != ie; ++it)
1148 OS << it->getString();
1153 // Update the scan point.
1154 Body = Body.substr(Pos + 2);
1157 // We include the .endmacro in the buffer as our queue to exit the macro
1159 OS << ".endmacro\n";
1161 Instantiation = MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1164 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1166 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1167 // this, although we should protect against infinite loops.
1168 if (ActiveMacros.size() == 20)
1169 return TokError("macros cannot be nested more than 20 levels deep");
1171 // Parse the macro instantiation arguments.
1172 std::vector<std::vector<AsmToken> > MacroArguments;
1173 MacroArguments.push_back(std::vector<AsmToken>());
1174 unsigned ParenLevel = 0;
1176 if (Lexer.is(AsmToken::Eof))
1177 return TokError("unexpected token in macro instantiation");
1178 if (Lexer.is(AsmToken::EndOfStatement))
1181 // If we aren't inside parentheses and this is a comma, start a new token
1183 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1184 MacroArguments.push_back(std::vector<AsmToken>());
1186 // Adjust the current parentheses level.
1187 if (Lexer.is(AsmToken::LParen))
1189 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1192 // Append the token to the current argument list.
1193 MacroArguments.back().push_back(getTok());
1198 // Create the macro instantiation object and add to the current macro
1199 // instantiation stack.
1200 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1203 ActiveMacros.push_back(MI);
1205 // Jump to the macro instantiation and prime the lexer.
1206 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1207 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1213 void AsmParser::HandleMacroExit() {
1214 // Jump to the EndOfStatement we should return to, and consume it.
1215 JumpToLoc(ActiveMacros.back()->ExitLoc);
1218 // Pop the instantiation entry.
1219 delete ActiveMacros.back();
1220 ActiveMacros.pop_back();
1223 static void MarkUsed(const MCExpr *Value) {
1224 switch (Value->getKind()) {
1225 case MCExpr::Binary:
1226 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1227 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1229 case MCExpr::Target:
1230 case MCExpr::Constant:
1232 case MCExpr::SymbolRef: {
1233 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1237 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1242 bool AsmParser::ParseAssignment(StringRef Name) {
1243 // FIXME: Use better location, we should use proper tokens.
1244 SMLoc EqualLoc = Lexer.getLoc();
1246 const MCExpr *Value;
1247 if (ParseExpression(Value))
1252 if (Lexer.isNot(AsmToken::EndOfStatement))
1253 return TokError("unexpected token in assignment");
1255 // Eat the end of statement marker.
1258 // Validate that the LHS is allowed to be a variable (either it has not been
1259 // used as a symbol, or it is an absolute symbol).
1260 MCSymbol *Sym = getContext().LookupSymbol(Name);
1262 // Diagnose assignment to a label.
1264 // FIXME: Diagnostics. Note the location of the definition as a label.
1265 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1266 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1267 ; // Allow redefinitions of undefined symbols only used in directives.
1268 else if (!Sym->isUndefined() && !Sym->isAbsolute())
1269 return Error(EqualLoc, "redefinition of '" + Name + "'");
1270 else if (!Sym->isVariable())
1271 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1272 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1273 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1276 // Don't count these checks as uses.
1277 Sym->setUsed(false);
1279 Sym = getContext().GetOrCreateSymbol(Name);
1281 // FIXME: Handle '.'.
1283 // Do the assignment.
1284 Out.EmitAssignment(Sym, Value);
1289 /// ParseIdentifier:
1292 bool AsmParser::ParseIdentifier(StringRef &Res) {
1293 // The assembler has relaxed rules for accepting identifiers, in particular we
1294 // allow things like '.globl $foo', which would normally be separate
1295 // tokens. At this level, we have already lexed so we cannot (currently)
1296 // handle this as a context dependent token, instead we detect adjacent tokens
1297 // and return the combined identifier.
1298 if (Lexer.is(AsmToken::Dollar)) {
1299 SMLoc DollarLoc = getLexer().getLoc();
1301 // Consume the dollar sign, and check for a following identifier.
1303 if (Lexer.isNot(AsmToken::Identifier))
1306 // We have a '$' followed by an identifier, make sure they are adjacent.
1307 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1310 // Construct the joined identifier and consume the token.
1311 Res = StringRef(DollarLoc.getPointer(),
1312 getTok().getIdentifier().size() + 1);
1317 if (Lexer.isNot(AsmToken::Identifier) &&
1318 Lexer.isNot(AsmToken::String))
1321 Res = getTok().getIdentifier();
1323 Lex(); // Consume the identifier token.
1328 /// ParseDirectiveSet:
1329 /// ::= .set identifier ',' expression
1330 bool AsmParser::ParseDirectiveSet(StringRef IDVal) {
1333 if (ParseIdentifier(Name))
1334 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1336 if (getLexer().isNot(AsmToken::Comma))
1337 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1340 return ParseAssignment(Name);
1343 bool AsmParser::ParseEscapedString(std::string &Data) {
1344 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1347 StringRef Str = getTok().getStringContents();
1348 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1349 if (Str[i] != '\\') {
1354 // Recognize escaped characters. Note that this escape semantics currently
1355 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1358 return TokError("unexpected backslash at end of string");
1360 // Recognize octal sequences.
1361 if ((unsigned) (Str[i] - '0') <= 7) {
1362 // Consume up to three octal characters.
1363 unsigned Value = Str[i] - '0';
1365 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1367 Value = Value * 8 + (Str[i] - '0');
1369 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1371 Value = Value * 8 + (Str[i] - '0');
1376 return TokError("invalid octal escape sequence (out of range)");
1378 Data += (unsigned char) Value;
1382 // Otherwise recognize individual escapes.
1385 // Just reject invalid escape sequences for now.
1386 return TokError("invalid escape sequence (unrecognized character)");
1388 case 'b': Data += '\b'; break;
1389 case 'f': Data += '\f'; break;
1390 case 'n': Data += '\n'; break;
1391 case 'r': Data += '\r'; break;
1392 case 't': Data += '\t'; break;
1393 case '"': Data += '"'; break;
1394 case '\\': Data += '\\'; break;
1401 /// ParseDirectiveAscii:
1402 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1403 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1404 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1405 CheckForValidSection();
1408 if (getLexer().isNot(AsmToken::String))
1409 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1412 if (ParseEscapedString(Data))
1415 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1417 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1421 if (getLexer().is(AsmToken::EndOfStatement))
1424 if (getLexer().isNot(AsmToken::Comma))
1425 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1434 /// ParseDirectiveValue
1435 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1436 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1437 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1438 CheckForValidSection();
1441 const MCExpr *Value;
1442 if (ParseExpression(Value))
1445 // Special case constant expressions to match code generator.
1446 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value))
1447 getStreamer().EmitIntValue(MCE->getValue(), Size, DEFAULT_ADDRSPACE);
1449 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1451 if (getLexer().is(AsmToken::EndOfStatement))
1454 // FIXME: Improve diagnostic.
1455 if (getLexer().isNot(AsmToken::Comma))
1456 return TokError("unexpected token in directive");
1465 /// ParseDirectiveRealValue
1466 /// ::= (.single | .double) [ expression (, expression)* ]
1467 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1469 CheckForValidSection();
1472 // We don't truly support arithmetic on floating point expressions, so we
1473 // have to manually parse unary prefixes.
1475 if (getLexer().is(AsmToken::Minus)) {
1478 } else if (getLexer().is(AsmToken::Plus))
1481 if (getLexer().isNot(AsmToken::Integer) &&
1482 getLexer().isNot(AsmToken::Real))
1483 return TokError("unexpected token in directive");
1485 // Convert to an APFloat.
1486 APFloat Value(Semantics);
1487 if (Value.convertFromString(getTok().getString(),
1488 APFloat::rmNearestTiesToEven) ==
1489 APFloat::opInvalidOp)
1490 return TokError("invalid floating point literal");
1494 // Consume the numeric token.
1497 // Emit the value as an integer.
1498 APInt AsInt = Value.bitcastToAPInt();
1499 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1500 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1502 if (getLexer().is(AsmToken::EndOfStatement))
1505 if (getLexer().isNot(AsmToken::Comma))
1506 return TokError("unexpected token in directive");
1515 /// ParseDirectiveSpace
1516 /// ::= .space expression [ , expression ]
1517 bool AsmParser::ParseDirectiveSpace() {
1518 CheckForValidSection();
1521 if (ParseAbsoluteExpression(NumBytes))
1524 int64_t FillExpr = 0;
1525 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1526 if (getLexer().isNot(AsmToken::Comma))
1527 return TokError("unexpected token in '.space' directive");
1530 if (ParseAbsoluteExpression(FillExpr))
1533 if (getLexer().isNot(AsmToken::EndOfStatement))
1534 return TokError("unexpected token in '.space' directive");
1540 return TokError("invalid number of bytes in '.space' directive");
1542 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1543 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1548 /// ParseDirectiveZero
1549 /// ::= .zero expression
1550 bool AsmParser::ParseDirectiveZero() {
1551 CheckForValidSection();
1554 if (ParseAbsoluteExpression(NumBytes))
1558 if (getLexer().is(AsmToken::Comma)) {
1560 if (ParseAbsoluteExpression(Val))
1564 if (getLexer().isNot(AsmToken::EndOfStatement))
1565 return TokError("unexpected token in '.zero' directive");
1569 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1574 /// ParseDirectiveFill
1575 /// ::= .fill expression , expression , expression
1576 bool AsmParser::ParseDirectiveFill() {
1577 CheckForValidSection();
1580 if (ParseAbsoluteExpression(NumValues))
1583 if (getLexer().isNot(AsmToken::Comma))
1584 return TokError("unexpected token in '.fill' directive");
1588 if (ParseAbsoluteExpression(FillSize))
1591 if (getLexer().isNot(AsmToken::Comma))
1592 return TokError("unexpected token in '.fill' directive");
1596 if (ParseAbsoluteExpression(FillExpr))
1599 if (getLexer().isNot(AsmToken::EndOfStatement))
1600 return TokError("unexpected token in '.fill' directive");
1604 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1605 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1607 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1608 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1613 /// ParseDirectiveOrg
1614 /// ::= .org expression [ , expression ]
1615 bool AsmParser::ParseDirectiveOrg() {
1616 CheckForValidSection();
1618 const MCExpr *Offset;
1619 if (ParseExpression(Offset))
1622 // Parse optional fill expression.
1623 int64_t FillExpr = 0;
1624 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1625 if (getLexer().isNot(AsmToken::Comma))
1626 return TokError("unexpected token in '.org' directive");
1629 if (ParseAbsoluteExpression(FillExpr))
1632 if (getLexer().isNot(AsmToken::EndOfStatement))
1633 return TokError("unexpected token in '.org' directive");
1638 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1639 // has to be relative to the current section.
1640 getStreamer().EmitValueToOffset(Offset, FillExpr);
1645 /// ParseDirectiveAlign
1646 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1647 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1648 CheckForValidSection();
1650 SMLoc AlignmentLoc = getLexer().getLoc();
1652 if (ParseAbsoluteExpression(Alignment))
1656 bool HasFillExpr = false;
1657 int64_t FillExpr = 0;
1658 int64_t MaxBytesToFill = 0;
1659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1660 if (getLexer().isNot(AsmToken::Comma))
1661 return TokError("unexpected token in directive");
1664 // The fill expression can be omitted while specifying a maximum number of
1665 // alignment bytes, e.g:
1667 if (getLexer().isNot(AsmToken::Comma)) {
1669 if (ParseAbsoluteExpression(FillExpr))
1673 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1674 if (getLexer().isNot(AsmToken::Comma))
1675 return TokError("unexpected token in directive");
1678 MaxBytesLoc = getLexer().getLoc();
1679 if (ParseAbsoluteExpression(MaxBytesToFill))
1682 if (getLexer().isNot(AsmToken::EndOfStatement))
1683 return TokError("unexpected token in directive");
1692 // Compute alignment in bytes.
1694 // FIXME: Diagnose overflow.
1695 if (Alignment >= 32) {
1696 Error(AlignmentLoc, "invalid alignment value");
1700 Alignment = 1ULL << Alignment;
1703 // Diagnose non-sensical max bytes to align.
1704 if (MaxBytesLoc.isValid()) {
1705 if (MaxBytesToFill < 1) {
1706 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1707 "many bytes, ignoring maximum bytes expression");
1711 if (MaxBytesToFill >= Alignment) {
1712 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1718 // Check whether we should use optimal code alignment for this .align
1720 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
1721 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1722 ValueSize == 1 && UseCodeAlign) {
1723 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
1725 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1726 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
1733 /// ParseDirectiveSymbolAttribute
1734 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1735 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1736 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1740 if (ParseIdentifier(Name))
1741 return TokError("expected identifier in directive");
1743 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1745 getStreamer().EmitSymbolAttribute(Sym, Attr);
1747 if (getLexer().is(AsmToken::EndOfStatement))
1750 if (getLexer().isNot(AsmToken::Comma))
1751 return TokError("unexpected token in directive");
1760 /// ParseDirectiveComm
1761 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1762 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1763 CheckForValidSection();
1765 SMLoc IDLoc = getLexer().getLoc();
1767 if (ParseIdentifier(Name))
1768 return TokError("expected identifier in directive");
1770 // Handle the identifier as the key symbol.
1771 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
1773 if (getLexer().isNot(AsmToken::Comma))
1774 return TokError("unexpected token in directive");
1778 SMLoc SizeLoc = getLexer().getLoc();
1779 if (ParseAbsoluteExpression(Size))
1782 int64_t Pow2Alignment = 0;
1783 SMLoc Pow2AlignmentLoc;
1784 if (getLexer().is(AsmToken::Comma)) {
1786 Pow2AlignmentLoc = getLexer().getLoc();
1787 if (ParseAbsoluteExpression(Pow2Alignment))
1790 // If this target takes alignments in bytes (not log) validate and convert.
1791 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1792 if (!isPowerOf2_64(Pow2Alignment))
1793 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1794 Pow2Alignment = Log2_64(Pow2Alignment);
1798 if (getLexer().isNot(AsmToken::EndOfStatement))
1799 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1803 // NOTE: a size of zero for a .comm should create a undefined symbol
1804 // but a size of .lcomm creates a bss symbol of size zero.
1806 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1807 "be less than zero");
1809 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1810 // may internally end up wanting an alignment in bytes.
1811 // FIXME: Diagnose overflow.
1812 if (Pow2Alignment < 0)
1813 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1814 "alignment, can't be less than zero");
1816 if (!Sym->isUndefined())
1817 return Error(IDLoc, "invalid symbol redefinition");
1819 // '.lcomm' is equivalent to '.zerofill'.
1820 // Create the Symbol as a common or local common with Size and Pow2Alignment
1822 getStreamer().EmitZerofill(Ctx.getMachOSection(
1823 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
1824 0, SectionKind::getBSS()),
1825 Sym, Size, 1 << Pow2Alignment);
1829 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1833 /// ParseDirectiveAbort
1834 /// ::= .abort [... message ...]
1835 bool AsmParser::ParseDirectiveAbort() {
1836 // FIXME: Use loc from directive.
1837 SMLoc Loc = getLexer().getLoc();
1839 StringRef Str = ParseStringToEndOfStatement();
1840 if (getLexer().isNot(AsmToken::EndOfStatement))
1841 return TokError("unexpected token in '.abort' directive");
1846 Error(Loc, ".abort detected. Assembly stopping.");
1848 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1849 // FIXME: Actually abort assembly here.
1854 /// ParseDirectiveInclude
1855 /// ::= .include "filename"
1856 bool AsmParser::ParseDirectiveInclude() {
1857 if (getLexer().isNot(AsmToken::String))
1858 return TokError("expected string in '.include' directive");
1860 std::string Filename = getTok().getString();
1861 SMLoc IncludeLoc = getLexer().getLoc();
1864 if (getLexer().isNot(AsmToken::EndOfStatement))
1865 return TokError("unexpected token in '.include' directive");
1867 // Strip the quotes.
1868 Filename = Filename.substr(1, Filename.size()-2);
1870 // Attempt to switch the lexer to the included file before consuming the end
1871 // of statement to avoid losing it when we switch.
1872 if (EnterIncludeFile(Filename)) {
1873 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
1880 /// ParseDirectiveIf
1881 /// ::= .if expression
1882 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1883 TheCondStack.push_back(TheCondState);
1884 TheCondState.TheCond = AsmCond::IfCond;
1885 if(TheCondState.Ignore) {
1886 EatToEndOfStatement();
1890 if (ParseAbsoluteExpression(ExprValue))
1893 if (getLexer().isNot(AsmToken::EndOfStatement))
1894 return TokError("unexpected token in '.if' directive");
1898 TheCondState.CondMet = ExprValue;
1899 TheCondState.Ignore = !TheCondState.CondMet;
1905 /// ParseDirectiveElseIf
1906 /// ::= .elseif expression
1907 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1908 if (TheCondState.TheCond != AsmCond::IfCond &&
1909 TheCondState.TheCond != AsmCond::ElseIfCond)
1910 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1912 TheCondState.TheCond = AsmCond::ElseIfCond;
1914 bool LastIgnoreState = false;
1915 if (!TheCondStack.empty())
1916 LastIgnoreState = TheCondStack.back().Ignore;
1917 if (LastIgnoreState || TheCondState.CondMet) {
1918 TheCondState.Ignore = true;
1919 EatToEndOfStatement();
1923 if (ParseAbsoluteExpression(ExprValue))
1926 if (getLexer().isNot(AsmToken::EndOfStatement))
1927 return TokError("unexpected token in '.elseif' directive");
1930 TheCondState.CondMet = ExprValue;
1931 TheCondState.Ignore = !TheCondState.CondMet;
1937 /// ParseDirectiveElse
1939 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1940 if (getLexer().isNot(AsmToken::EndOfStatement))
1941 return TokError("unexpected token in '.else' directive");
1945 if (TheCondState.TheCond != AsmCond::IfCond &&
1946 TheCondState.TheCond != AsmCond::ElseIfCond)
1947 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1949 TheCondState.TheCond = AsmCond::ElseCond;
1950 bool LastIgnoreState = false;
1951 if (!TheCondStack.empty())
1952 LastIgnoreState = TheCondStack.back().Ignore;
1953 if (LastIgnoreState || TheCondState.CondMet)
1954 TheCondState.Ignore = true;
1956 TheCondState.Ignore = false;
1961 /// ParseDirectiveEndIf
1963 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1964 if (getLexer().isNot(AsmToken::EndOfStatement))
1965 return TokError("unexpected token in '.endif' directive");
1969 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1970 TheCondStack.empty())
1971 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1973 if (!TheCondStack.empty()) {
1974 TheCondState = TheCondStack.back();
1975 TheCondStack.pop_back();
1981 /// ParseDirectiveFile
1982 /// ::= .file [number] string
1983 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1984 // FIXME: I'm not sure what this is.
1985 int64_t FileNumber = -1;
1986 SMLoc FileNumberLoc = getLexer().getLoc();
1987 if (getLexer().is(AsmToken::Integer)) {
1988 FileNumber = getTok().getIntVal();
1992 return TokError("file number less than one");
1995 if (getLexer().isNot(AsmToken::String))
1996 return TokError("unexpected token in '.file' directive");
1998 StringRef Filename = getTok().getString();
1999 Filename = Filename.substr(1, Filename.size()-2);
2002 if (getLexer().isNot(AsmToken::EndOfStatement))
2003 return TokError("unexpected token in '.file' directive");
2005 if (FileNumber == -1)
2006 getStreamer().EmitFileDirective(Filename);
2008 if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
2009 Error(FileNumberLoc, "file number already allocated");
2015 /// ParseDirectiveLine
2016 /// ::= .line [number]
2017 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2018 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2019 if (getLexer().isNot(AsmToken::Integer))
2020 return TokError("unexpected token in '.line' directive");
2022 int64_t LineNumber = getTok().getIntVal();
2026 // FIXME: Do something with the .line.
2029 if (getLexer().isNot(AsmToken::EndOfStatement))
2030 return TokError("unexpected token in '.line' directive");
2036 /// ParseDirectiveLoc
2037 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2038 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2039 /// The first number is a file number, must have been previously assigned with
2040 /// a .file directive, the second number is the line number and optionally the
2041 /// third number is a column position (zero if not specified). The remaining
2042 /// optional items are .loc sub-directives.
2043 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2045 if (getLexer().isNot(AsmToken::Integer))
2046 return TokError("unexpected token in '.loc' directive");
2047 int64_t FileNumber = getTok().getIntVal();
2049 return TokError("file number less than one in '.loc' directive");
2050 if (!getContext().isValidDwarfFileNumber(FileNumber))
2051 return TokError("unassigned file number in '.loc' directive");
2054 int64_t LineNumber = 0;
2055 if (getLexer().is(AsmToken::Integer)) {
2056 LineNumber = getTok().getIntVal();
2058 return TokError("line number less than one in '.loc' directive");
2062 int64_t ColumnPos = 0;
2063 if (getLexer().is(AsmToken::Integer)) {
2064 ColumnPos = getTok().getIntVal();
2066 return TokError("column position less than zero in '.loc' directive");
2070 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2072 int64_t Discriminator = 0;
2073 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2075 if (getLexer().is(AsmToken::EndOfStatement))
2079 SMLoc Loc = getTok().getLoc();
2080 if (getParser().ParseIdentifier(Name))
2081 return TokError("unexpected token in '.loc' directive");
2083 if (Name == "basic_block")
2084 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2085 else if (Name == "prologue_end")
2086 Flags |= DWARF2_FLAG_PROLOGUE_END;
2087 else if (Name == "epilogue_begin")
2088 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2089 else if (Name == "is_stmt") {
2090 SMLoc Loc = getTok().getLoc();
2091 const MCExpr *Value;
2092 if (getParser().ParseExpression(Value))
2094 // The expression must be the constant 0 or 1.
2095 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2096 int Value = MCE->getValue();
2098 Flags &= ~DWARF2_FLAG_IS_STMT;
2099 else if (Value == 1)
2100 Flags |= DWARF2_FLAG_IS_STMT;
2102 return Error(Loc, "is_stmt value not 0 or 1");
2105 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2108 else if (Name == "isa") {
2109 SMLoc Loc = getTok().getLoc();
2110 const MCExpr *Value;
2111 if (getParser().ParseExpression(Value))
2113 // The expression must be a constant greater or equal to 0.
2114 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2115 int Value = MCE->getValue();
2117 return Error(Loc, "isa number less than zero");
2121 return Error(Loc, "isa number not a constant value");
2124 else if (Name == "discriminator") {
2125 if (getParser().ParseAbsoluteExpression(Discriminator))
2129 return Error(Loc, "unknown sub-directive in '.loc' directive");
2132 if (getLexer().is(AsmToken::EndOfStatement))
2137 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2138 Isa, Discriminator);
2143 /// ParseDirectiveStabs
2144 /// ::= .stabs string, number, number, number
2145 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2146 SMLoc DirectiveLoc) {
2147 return TokError("unsupported directive '" + Directive + "'");
2150 /// ParseDirectiveCFIStartProc
2151 /// ::= .cfi_startproc
2152 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2153 SMLoc DirectiveLoc) {
2157 /// ParseDirectiveCFIEndProc
2158 /// ::= .cfi_endproc
2159 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2163 /// ParseDirectiveCFIDefCfaOffset
2164 /// ::= .cfi_def_cfa_offset offset
2165 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2166 SMLoc DirectiveLoc) {
2168 if (getParser().ParseAbsoluteExpression(Offset))
2174 /// ParseDirectiveCFIDefCfaRegister
2175 /// ::= .cfi_def_cfa_register register
2176 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2177 SMLoc DirectiveLoc) {
2178 int64_t Register = 0;
2179 if (getParser().ParseAbsoluteExpression(Register))
2184 /// ParseDirectiveCFIOffset
2185 /// ::= .cfi_off register, offset
2186 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2187 int64_t Register = 0;
2189 if (getParser().ParseAbsoluteExpression(Register))
2192 if (getLexer().isNot(AsmToken::Comma))
2193 return TokError("unexpected token in directive");
2196 if (getParser().ParseAbsoluteExpression(Offset))
2202 /// ParseDirectiveCFIPersonalityOrLsda
2203 /// ::= .cfi_personality encoding, [symbol_name]
2204 /// ::= .cfi_lsda encoding, [symbol_name]
2205 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef,
2206 SMLoc DirectiveLoc) {
2207 int64_t Encoding = 0;
2208 if (getParser().ParseAbsoluteExpression(Encoding))
2210 if (Encoding == 255)
2213 if (getLexer().isNot(AsmToken::Comma))
2214 return TokError("unexpected token in directive");
2218 if (getParser().ParseIdentifier(Name))
2219 return TokError("expected identifier in directive");
2223 /// ParseDirectiveMacrosOnOff
2226 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2227 SMLoc DirectiveLoc) {
2228 if (getLexer().isNot(AsmToken::EndOfStatement))
2229 return Error(getLexer().getLoc(),
2230 "unexpected token in '" + Directive + "' directive");
2232 getParser().MacrosEnabled = Directive == ".macros_on";
2237 /// ParseDirectiveMacro
2239 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2240 SMLoc DirectiveLoc) {
2242 if (getParser().ParseIdentifier(Name))
2243 return TokError("expected identifier in directive");
2245 if (getLexer().isNot(AsmToken::EndOfStatement))
2246 return TokError("unexpected token in '.macro' directive");
2248 // Eat the end of statement.
2251 AsmToken EndToken, StartToken = getTok();
2253 // Lex the macro definition.
2255 // Check whether we have reached the end of the file.
2256 if (getLexer().is(AsmToken::Eof))
2257 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2259 // Otherwise, check whether we have reach the .endmacro.
2260 if (getLexer().is(AsmToken::Identifier) &&
2261 (getTok().getIdentifier() == ".endm" ||
2262 getTok().getIdentifier() == ".endmacro")) {
2263 EndToken = getTok();
2265 if (getLexer().isNot(AsmToken::EndOfStatement))
2266 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2271 // Otherwise, scan til the end of the statement.
2272 getParser().EatToEndOfStatement();
2275 if (getParser().MacroMap.lookup(Name)) {
2276 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2279 const char *BodyStart = StartToken.getLoc().getPointer();
2280 const char *BodyEnd = EndToken.getLoc().getPointer();
2281 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2282 getParser().MacroMap[Name] = new Macro(Name, Body);
2286 /// ParseDirectiveEndMacro
2289 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2290 SMLoc DirectiveLoc) {
2291 if (getLexer().isNot(AsmToken::EndOfStatement))
2292 return TokError("unexpected token in '" + Directive + "' directive");
2294 // If we are inside a macro instantiation, terminate the current
2296 if (!getParser().ActiveMacros.empty()) {
2297 getParser().HandleMacroExit();
2301 // Otherwise, this .endmacro is a stray entry in the file; well formed
2302 // .endmacro directives are handled during the macro definition parsing.
2303 return TokError("unexpected '" + Directive + "' in file, "
2304 "no current macro definition");
2307 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2308 getParser().CheckForValidSection();
2310 const MCExpr *Value;
2312 if (getParser().ParseExpression(Value))
2315 if (getLexer().isNot(AsmToken::EndOfStatement))
2316 return TokError("unexpected token in directive");
2318 if (DirName[1] == 's')
2319 getStreamer().EmitSLEB128Value(Value);
2321 getStreamer().EmitULEB128Value(Value);
2327 /// \brief Create an MCAsmParser instance.
2328 MCAsmParser *llvm::createMCAsmParser(const Target &T, SourceMgr &SM,
2329 MCContext &C, MCStreamer &Out,
2330 const MCAsmInfo &MAI) {
2331 return new AsmParser(T, SM, C, Out, MAI);