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/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCParser/AsmCond.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCTargetAsmParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/raw_ostream.h"
42 FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
47 /// \brief Helper class for tracking macro definitions.
51 std::vector<StringRef> Parameters;
54 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
58 /// \brief Helper class for storing information about an active macro
60 struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
70 /// The location where parsing should resume upon instantiation completion.
74 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
78 /// \brief The concrete assembly parser instance.
79 class AsmParser : public MCAsmParser {
80 friend class GenericAsmParser;
82 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
90 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
92 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
95 /// This is the current buffer index we're lexing from as managed by the
100 std::vector<AsmCond> TheCondStack;
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
127 const MCAsmInfo &MAI);
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
139 /// @name MCAsmParser Interface
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
146 virtual unsigned getAssemblerDialect() { return MAI.getAssemblerDialect(); }
148 virtual bool Warning(SMLoc L, const Twine &Msg,
149 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
150 virtual bool Error(SMLoc L, const Twine &Msg,
151 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
153 const AsmToken &Lex();
155 bool ParseExpression(const MCExpr *&Res);
156 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
158 virtual bool ParseAbsoluteExpression(int64_t &Res);
163 void CheckForValidSection();
165 bool ParseStatement();
166 void EatToEndOfLine();
167 bool ParseCppHashLineFilenameComment(const SMLoc &L);
169 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
170 bool expandMacro(SmallString<256> &Buf, StringRef Body,
171 const std::vector<StringRef> &Parameters,
172 const std::vector<std::vector<AsmToken> > &A,
174 void HandleMacroExit();
176 void PrintMacroInstantiations();
177 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
178 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
179 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
181 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
183 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
184 bool EnterIncludeFile(const std::string &Filename);
185 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
186 /// This returns true on failure.
187 bool ProcessIncbinFile(const std::string &Filename);
189 /// \brief Reset the current lexer position to that given by \arg Loc. The
190 /// current token is not set; clients should ensure Lex() is called
192 void JumpToLoc(SMLoc Loc);
194 void EatToEndOfStatement();
196 /// \brief Parse up to the end of statement and a return the contents from the
197 /// current token until the end of the statement; the current token on exit
198 /// will be either the EndOfStatement or EOF.
199 StringRef ParseStringToEndOfStatement();
201 bool ParseAssignment(StringRef Name, bool allow_redef);
203 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
205 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
206 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
208 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
209 /// and set \arg Res to the identifier contents.
210 bool ParseIdentifier(StringRef &Res);
212 // Directive Parsing.
214 // ".ascii", ".asciiz", ".string"
215 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
216 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
217 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
218 bool ParseDirectiveFill(); // ".fill"
219 bool ParseDirectiveSpace(); // ".space"
220 bool ParseDirectiveZero(); // ".zero"
221 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
222 bool ParseDirectiveOrg(); // ".org"
223 // ".align{,32}", ".p2align{,w,l}"
224 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
226 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
227 /// accepts a single symbol (which should be a label or an external).
228 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
230 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
232 bool ParseDirectiveAbort(); // ".abort"
233 bool ParseDirectiveInclude(); // ".include"
234 bool ParseDirectiveIncbin(); // ".incbin"
236 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
237 // ".ifdef" or ".ifndef", depending on expect_defined
238 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
239 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
240 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
241 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
243 /// ParseEscapedString - Parse the current token as a string which may include
244 /// escaped characters and return the string contents.
245 bool ParseEscapedString(std::string &Data);
247 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
248 MCSymbolRefExpr::VariantKind Variant);
251 /// \brief Generic implementations of directive handling, etc. which is shared
252 /// (or the default, at least) for all assembler parser.
253 class GenericAsmParser : public MCAsmParserExtension {
254 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
255 void AddDirectiveHandler(StringRef Directive) {
256 getParser().AddDirectiveHandler(this, Directive,
257 HandleDirective<GenericAsmParser, Handler>);
260 GenericAsmParser() {}
262 AsmParser &getParser() {
263 return (AsmParser&) this->MCAsmParserExtension::getParser();
266 virtual void Initialize(MCAsmParser &Parser) {
267 // Call the base implementation.
268 this->MCAsmParserExtension::Initialize(Parser);
270 // Debugging directives.
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
274 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
277 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
279 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
281 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
283 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
285 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
286 ".cfi_def_cfa_offset");
287 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
288 ".cfi_adjust_cfa_offset");
289 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
290 ".cfi_def_cfa_register");
291 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
293 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
296 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
298 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
300 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
302 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
304 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
306 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
308 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
313 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
320 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
323 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
325 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
327 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
328 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
329 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
330 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
332 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
333 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
334 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
336 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
337 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
338 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
339 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
341 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
342 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
343 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
345 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
346 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
347 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
349 bool ParseDirectiveLEB128(StringRef, SMLoc);
356 extern MCAsmParserExtension *createDarwinAsmParser();
357 extern MCAsmParserExtension *createELFAsmParser();
358 extern MCAsmParserExtension *createCOFFAsmParser();
362 enum { DEFAULT_ADDRSPACE = 0 };
364 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
365 MCStreamer &_Out, const MCAsmInfo &_MAI)
366 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
367 GenericParser(new GenericAsmParser), PlatformParser(0),
368 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
369 // Save the old handler.
370 SavedDiagHandler = SrcMgr.getDiagHandler();
371 SavedDiagContext = SrcMgr.getDiagContext();
372 // Set our own handler which calls the saved handler.
373 SrcMgr.setDiagHandler(DiagHandler, this);
374 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
376 // Initialize the generic parser.
377 GenericParser->Initialize(*this);
379 // Initialize the platform / file format parser.
381 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
383 if (_MAI.hasMicrosoftFastStdCallMangling()) {
384 PlatformParser = createCOFFAsmParser();
385 PlatformParser->Initialize(*this);
386 } else if (_MAI.hasSubsectionsViaSymbols()) {
387 PlatformParser = createDarwinAsmParser();
388 PlatformParser->Initialize(*this);
390 PlatformParser = createELFAsmParser();
391 PlatformParser->Initialize(*this);
395 AsmParser::~AsmParser() {
396 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
398 // Destroy any macros.
399 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
400 ie = MacroMap.end(); it != ie; ++it)
401 delete it->getValue();
403 delete PlatformParser;
404 delete GenericParser;
407 void AsmParser::PrintMacroInstantiations() {
408 // Print the active macro instantiation stack.
409 for (std::vector<MacroInstantiation*>::const_reverse_iterator
410 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
411 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
412 "while in macro instantiation");
415 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
416 if (FatalAssemblerWarnings)
417 return Error(L, Msg, Ranges);
418 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
419 PrintMacroInstantiations();
423 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
425 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
426 PrintMacroInstantiations();
430 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
431 std::string IncludedFile;
432 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
438 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
443 /// Process the specified .incbin file by seaching for it in the include paths
444 /// then just emiting the byte contents of the file to the streamer. This
445 /// returns true on failure.
446 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
447 std::string IncludedFile;
448 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
452 // Pick up the bytes from the file and emit them.
453 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
458 void AsmParser::JumpToLoc(SMLoc Loc) {
459 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
460 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
463 const AsmToken &AsmParser::Lex() {
464 const AsmToken *tok = &Lexer.Lex();
466 if (tok->is(AsmToken::Eof)) {
467 // If this is the end of an included file, pop the parent file off the
469 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
470 if (ParentIncludeLoc != SMLoc()) {
471 JumpToLoc(ParentIncludeLoc);
476 if (tok->is(AsmToken::Error))
477 Error(Lexer.getErrLoc(), Lexer.getErr());
482 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
483 // Create the initial section, if requested.
484 if (!NoInitialTextSection)
491 AsmCond StartingCondState = TheCondState;
493 // If we are generating dwarf for assembly source files save the initial text
494 // section and generate a .file directive.
495 if (getContext().getGenDwarfForAssembly()) {
496 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
497 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
498 getStreamer().EmitLabel(SectionStartSym);
499 getContext().setGenDwarfSectionStartSym(SectionStartSym);
500 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
501 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
504 // While we have input, parse each statement.
505 while (Lexer.isNot(AsmToken::Eof)) {
506 if (!ParseStatement()) continue;
508 // We had an error, validate that one was emitted and recover by skipping to
510 assert(HadError && "Parse statement returned an error, but none emitted!");
511 EatToEndOfStatement();
514 if (TheCondState.TheCond != StartingCondState.TheCond ||
515 TheCondState.Ignore != StartingCondState.Ignore)
516 return TokError("unmatched .ifs or .elses");
518 // Check to see there are no empty DwarfFile slots.
519 const std::vector<MCDwarfFile *> &MCDwarfFiles =
520 getContext().getMCDwarfFiles();
521 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
522 if (!MCDwarfFiles[i])
523 TokError("unassigned file number: " + Twine(i) + " for .file directives");
526 // Check to see that all assembler local symbols were actually defined.
527 // Targets that don't do subsections via symbols may not want this, though,
528 // so conservatively exclude them. Only do this if we're finalizing, though,
529 // as otherwise we won't necessarilly have seen everything yet.
530 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
531 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
532 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
535 MCSymbol *Sym = i->getValue();
536 // Variable symbols may not be marked as defined, so check those
537 // explicitly. If we know it's a variable, we have a definition for
538 // the purposes of this check.
539 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
540 // FIXME: We would really like to refer back to where the symbol was
541 // first referenced for a source location. We need to add something
542 // to track that. Currently, we just point to the end of the file.
543 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
544 "assembler local symbol '" + Sym->getName() +
550 // Finalize the output stream if there are no errors and if the client wants
552 if (!HadError && !NoFinalize)
558 void AsmParser::CheckForValidSection() {
559 if (!getStreamer().getCurrentSection()) {
560 TokError("expected section directive before assembly directive");
561 Out.SwitchSection(Ctx.getMachOSection(
563 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
564 0, SectionKind::getText()));
568 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
569 void AsmParser::EatToEndOfStatement() {
570 while (Lexer.isNot(AsmToken::EndOfStatement) &&
571 Lexer.isNot(AsmToken::Eof))
575 if (Lexer.is(AsmToken::EndOfStatement))
579 StringRef AsmParser::ParseStringToEndOfStatement() {
580 const char *Start = getTok().getLoc().getPointer();
582 while (Lexer.isNot(AsmToken::EndOfStatement) &&
583 Lexer.isNot(AsmToken::Eof))
586 const char *End = getTok().getLoc().getPointer();
587 return StringRef(Start, End - Start);
590 /// ParseParenExpr - Parse a paren expression and return it.
591 /// NOTE: This assumes the leading '(' has already been consumed.
593 /// parenexpr ::= expr)
595 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
596 if (ParseExpression(Res)) return true;
597 if (Lexer.isNot(AsmToken::RParen))
598 return TokError("expected ')' in parentheses expression");
599 EndLoc = Lexer.getLoc();
604 /// ParseBracketExpr - Parse a bracket expression and return it.
605 /// NOTE: This assumes the leading '[' has already been consumed.
607 /// bracketexpr ::= expr]
609 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
610 if (ParseExpression(Res)) return true;
611 if (Lexer.isNot(AsmToken::RBrac))
612 return TokError("expected ']' in brackets expression");
613 EndLoc = Lexer.getLoc();
618 /// ParsePrimaryExpr - Parse a primary expression and return it.
619 /// primaryexpr ::= (parenexpr
620 /// primaryexpr ::= symbol
621 /// primaryexpr ::= number
622 /// primaryexpr ::= '.'
623 /// primaryexpr ::= ~,+,- primaryexpr
624 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
625 switch (Lexer.getKind()) {
627 return TokError("unknown token in expression");
628 // If we have an error assume that we've already handled it.
629 case AsmToken::Error:
631 case AsmToken::Exclaim:
632 Lex(); // Eat the operator.
633 if (ParsePrimaryExpr(Res, EndLoc))
635 Res = MCUnaryExpr::CreateLNot(Res, getContext());
637 case AsmToken::Dollar:
638 case AsmToken::String:
639 case AsmToken::Identifier: {
640 EndLoc = Lexer.getLoc();
642 StringRef Identifier;
643 if (ParseIdentifier(Identifier))
646 // This is a symbol reference.
647 std::pair<StringRef, StringRef> Split = Identifier.split('@');
648 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
650 // Lookup the symbol variant if used.
651 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
652 if (Split.first.size() != Identifier.size()) {
653 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
654 if (Variant == MCSymbolRefExpr::VK_Invalid) {
655 Variant = MCSymbolRefExpr::VK_None;
656 return TokError("invalid variant '" + Split.second + "'");
660 // If this is an absolute variable reference, substitute it now to preserve
661 // semantics in the face of reassignment.
662 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
664 return Error(EndLoc, "unexpected modifier on variable reference");
666 Res = Sym->getVariableValue();
670 // Otherwise create a symbol ref.
671 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
674 case AsmToken::Integer: {
675 SMLoc Loc = getTok().getLoc();
676 int64_t IntVal = getTok().getIntVal();
677 Res = MCConstantExpr::Create(IntVal, getContext());
678 EndLoc = Lexer.getLoc();
680 // Look for 'b' or 'f' following an Integer as a directional label
681 if (Lexer.getKind() == AsmToken::Identifier) {
682 StringRef IDVal = getTok().getString();
683 if (IDVal == "f" || IDVal == "b"){
684 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
685 IDVal == "f" ? 1 : 0);
686 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
688 if(IDVal == "b" && Sym->isUndefined())
689 return Error(Loc, "invalid reference to undefined symbol");
690 EndLoc = Lexer.getLoc();
691 Lex(); // Eat identifier.
696 case AsmToken::Real: {
697 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
698 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
699 Res = MCConstantExpr::Create(IntVal, getContext());
703 case AsmToken::Dot: {
704 // This is a '.' reference, which references the current PC. Emit a
705 // temporary label to the streamer and refer to it.
706 MCSymbol *Sym = Ctx.CreateTempSymbol();
708 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
709 EndLoc = Lexer.getLoc();
710 Lex(); // Eat identifier.
713 case AsmToken::LParen:
714 Lex(); // Eat the '('.
715 return ParseParenExpr(Res, EndLoc);
716 case AsmToken::LBrac:
717 if (!PlatformParser->HasBracketExpressions())
718 return TokError("brackets expression not supported on this target");
719 Lex(); // Eat the '['.
720 return ParseBracketExpr(Res, EndLoc);
721 case AsmToken::Minus:
722 Lex(); // Eat the operator.
723 if (ParsePrimaryExpr(Res, EndLoc))
725 Res = MCUnaryExpr::CreateMinus(Res, getContext());
728 Lex(); // Eat the operator.
729 if (ParsePrimaryExpr(Res, EndLoc))
731 Res = MCUnaryExpr::CreatePlus(Res, getContext());
733 case AsmToken::Tilde:
734 Lex(); // Eat the operator.
735 if (ParsePrimaryExpr(Res, EndLoc))
737 Res = MCUnaryExpr::CreateNot(Res, getContext());
742 bool AsmParser::ParseExpression(const MCExpr *&Res) {
744 return ParseExpression(Res, EndLoc);
748 AsmParser::ApplyModifierToExpr(const MCExpr *E,
749 MCSymbolRefExpr::VariantKind Variant) {
750 // Recurse over the given expression, rebuilding it to apply the given variant
751 // if there is exactly one symbol.
752 switch (E->getKind()) {
754 case MCExpr::Constant:
757 case MCExpr::SymbolRef: {
758 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
760 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
761 TokError("invalid variant on expression '" +
762 getTok().getIdentifier() + "' (already modified)");
766 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
769 case MCExpr::Unary: {
770 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
771 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
774 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
777 case MCExpr::Binary: {
778 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
779 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
780 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
785 if (!LHS) LHS = BE->getLHS();
786 if (!RHS) RHS = BE->getRHS();
788 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
792 assert(0 && "Invalid expression kind!");
796 /// ParseExpression - Parse an expression and return it.
798 /// expr ::= expr &&,|| expr -> lowest.
799 /// expr ::= expr |,^,&,! expr
800 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
801 /// expr ::= expr <<,>> expr
802 /// expr ::= expr +,- expr
803 /// expr ::= expr *,/,% expr -> highest.
804 /// expr ::= primaryexpr
806 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
807 // Parse the expression.
809 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
812 // As a special case, we support 'a op b @ modifier' by rewriting the
813 // expression to include the modifier. This is inefficient, but in general we
814 // expect users to use 'a@modifier op b'.
815 if (Lexer.getKind() == AsmToken::At) {
818 if (Lexer.isNot(AsmToken::Identifier))
819 return TokError("unexpected symbol modifier following '@'");
821 MCSymbolRefExpr::VariantKind Variant =
822 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
823 if (Variant == MCSymbolRefExpr::VK_Invalid)
824 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
826 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
828 return TokError("invalid modifier '" + getTok().getIdentifier() +
829 "' (no symbols present)");
837 // Try to constant fold it up front, if possible.
839 if (Res->EvaluateAsAbsolute(Value))
840 Res = MCConstantExpr::Create(Value, getContext());
845 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
847 return ParseParenExpr(Res, EndLoc) ||
848 ParseBinOpRHS(1, Res, EndLoc);
851 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
854 SMLoc StartLoc = Lexer.getLoc();
855 if (ParseExpression(Expr))
858 if (!Expr->EvaluateAsAbsolute(Res))
859 return Error(StartLoc, "expected absolute expression");
864 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
865 MCBinaryExpr::Opcode &Kind) {
868 return 0; // not a binop.
870 // Lowest Precedence: &&, ||
871 case AsmToken::AmpAmp:
872 Kind = MCBinaryExpr::LAnd;
874 case AsmToken::PipePipe:
875 Kind = MCBinaryExpr::LOr;
879 // Low Precedence: |, &, ^
881 // FIXME: gas seems to support '!' as an infix operator?
883 Kind = MCBinaryExpr::Or;
885 case AsmToken::Caret:
886 Kind = MCBinaryExpr::Xor;
889 Kind = MCBinaryExpr::And;
892 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
893 case AsmToken::EqualEqual:
894 Kind = MCBinaryExpr::EQ;
896 case AsmToken::ExclaimEqual:
897 case AsmToken::LessGreater:
898 Kind = MCBinaryExpr::NE;
901 Kind = MCBinaryExpr::LT;
903 case AsmToken::LessEqual:
904 Kind = MCBinaryExpr::LTE;
906 case AsmToken::Greater:
907 Kind = MCBinaryExpr::GT;
909 case AsmToken::GreaterEqual:
910 Kind = MCBinaryExpr::GTE;
913 // Intermediate Precedence: <<, >>
914 case AsmToken::LessLess:
915 Kind = MCBinaryExpr::Shl;
917 case AsmToken::GreaterGreater:
918 Kind = MCBinaryExpr::Shr;
921 // High Intermediate Precedence: +, -
923 Kind = MCBinaryExpr::Add;
925 case AsmToken::Minus:
926 Kind = MCBinaryExpr::Sub;
929 // Highest Precedence: *, /, %
931 Kind = MCBinaryExpr::Mul;
933 case AsmToken::Slash:
934 Kind = MCBinaryExpr::Div;
936 case AsmToken::Percent:
937 Kind = MCBinaryExpr::Mod;
943 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
944 /// Res contains the LHS of the expression on input.
945 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
948 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
949 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
951 // If the next token is lower precedence than we are allowed to eat, return
952 // successfully with what we ate already.
953 if (TokPrec < Precedence)
958 // Eat the next primary expression.
960 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
962 // If BinOp binds less tightly with RHS than the operator after RHS, let
963 // the pending operator take RHS as its LHS.
964 MCBinaryExpr::Opcode Dummy;
965 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
966 if (TokPrec < NextTokPrec) {
967 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
970 // Merge LHS and RHS according to operator.
971 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
979 /// ::= EndOfStatement
980 /// ::= Label* Directive ...Operands... EndOfStatement
981 /// ::= Label* Identifier OperandList* EndOfStatement
982 bool AsmParser::ParseStatement() {
983 if (Lexer.is(AsmToken::EndOfStatement)) {
989 // Statements always start with an identifier or are a full line comment.
990 AsmToken ID = getTok();
991 SMLoc IDLoc = ID.getLoc();
993 int64_t LocalLabelVal = -1;
994 // A full line comment is a '#' as the first token.
995 if (Lexer.is(AsmToken::Hash))
996 return ParseCppHashLineFilenameComment(IDLoc);
998 // Allow an integer followed by a ':' as a directional local label.
999 if (Lexer.is(AsmToken::Integer)) {
1000 LocalLabelVal = getTok().getIntVal();
1001 if (LocalLabelVal < 0) {
1002 if (!TheCondState.Ignore)
1003 return TokError("unexpected token at start of statement");
1007 IDVal = getTok().getString();
1008 Lex(); // Consume the integer token to be used as an identifier token.
1009 if (Lexer.getKind() != AsmToken::Colon) {
1010 if (!TheCondState.Ignore)
1011 return TokError("unexpected token at start of statement");
1015 } else if (Lexer.is(AsmToken::Dot)) {
1016 // Treat '.' as a valid identifier in this context.
1020 } else if (ParseIdentifier(IDVal)) {
1021 if (!TheCondState.Ignore)
1022 return TokError("unexpected token at start of statement");
1027 // Handle conditional assembly here before checking for skipping. We
1028 // have to do this so that .endif isn't skipped in a ".if 0" block for
1031 return ParseDirectiveIf(IDLoc);
1032 if (IDVal == ".ifdef")
1033 return ParseDirectiveIfdef(IDLoc, true);
1034 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1035 return ParseDirectiveIfdef(IDLoc, false);
1036 if (IDVal == ".elseif")
1037 return ParseDirectiveElseIf(IDLoc);
1038 if (IDVal == ".else")
1039 return ParseDirectiveElse(IDLoc);
1040 if (IDVal == ".endif")
1041 return ParseDirectiveEndIf(IDLoc);
1043 // If we are in a ".if 0" block, ignore this statement.
1044 if (TheCondState.Ignore) {
1045 EatToEndOfStatement();
1049 // FIXME: Recurse on local labels?
1051 // See what kind of statement we have.
1052 switch (Lexer.getKind()) {
1053 case AsmToken::Colon: {
1054 CheckForValidSection();
1056 // identifier ':' -> Label.
1059 // Diagnose attempt to use '.' as a label.
1061 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1063 // Diagnose attempt to use a variable as a label.
1065 // FIXME: Diagnostics. Note the location of the definition as a label.
1066 // FIXME: This doesn't diagnose assignment to a symbol which has been
1067 // implicitly marked as external.
1069 if (LocalLabelVal == -1)
1070 Sym = getContext().GetOrCreateSymbol(IDVal);
1072 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1073 if (!Sym->isUndefined() || Sym->isVariable())
1074 return Error(IDLoc, "invalid symbol redefinition");
1079 // If we are generating dwarf for assembly source files then gather the
1080 // info to make a dwarf label entry for this label if needed.
1081 if (getContext().getGenDwarfForAssembly())
1082 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1085 // Consume any end of statement token, if present, to avoid spurious
1086 // AddBlankLine calls().
1087 if (Lexer.is(AsmToken::EndOfStatement)) {
1089 if (Lexer.is(AsmToken::Eof))
1093 return ParseStatement();
1096 case AsmToken::Equal:
1097 // identifier '=' ... -> assignment statement
1100 return ParseAssignment(IDVal, true);
1102 default: // Normal instruction or directive.
1106 // If macros are enabled, check to see if this is a macro instantiation.
1108 if (const Macro *M = MacroMap.lookup(IDVal))
1109 return HandleMacroEntry(IDVal, IDLoc, M);
1111 // Otherwise, we have a normal instruction or directive.
1112 if (IDVal[0] == '.' && IDVal != ".") {
1113 // Assembler features
1114 if (IDVal == ".set" || IDVal == ".equ")
1115 return ParseDirectiveSet(IDVal, true);
1116 if (IDVal == ".equiv")
1117 return ParseDirectiveSet(IDVal, false);
1121 if (IDVal == ".ascii")
1122 return ParseDirectiveAscii(IDVal, false);
1123 if (IDVal == ".asciz" || IDVal == ".string")
1124 return ParseDirectiveAscii(IDVal, true);
1126 if (IDVal == ".byte")
1127 return ParseDirectiveValue(1);
1128 if (IDVal == ".short")
1129 return ParseDirectiveValue(2);
1130 if (IDVal == ".value")
1131 return ParseDirectiveValue(2);
1132 if (IDVal == ".2byte")
1133 return ParseDirectiveValue(2);
1134 if (IDVal == ".long")
1135 return ParseDirectiveValue(4);
1136 if (IDVal == ".int")
1137 return ParseDirectiveValue(4);
1138 if (IDVal == ".4byte")
1139 return ParseDirectiveValue(4);
1140 if (IDVal == ".quad")
1141 return ParseDirectiveValue(8);
1142 if (IDVal == ".8byte")
1143 return ParseDirectiveValue(8);
1144 if (IDVal == ".single" || IDVal == ".float")
1145 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1146 if (IDVal == ".double")
1147 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1149 if (IDVal == ".align") {
1150 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1151 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1153 if (IDVal == ".align32") {
1154 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1155 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1157 if (IDVal == ".balign")
1158 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1159 if (IDVal == ".balignw")
1160 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1161 if (IDVal == ".balignl")
1162 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1163 if (IDVal == ".p2align")
1164 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1165 if (IDVal == ".p2alignw")
1166 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1167 if (IDVal == ".p2alignl")
1168 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1170 if (IDVal == ".org")
1171 return ParseDirectiveOrg();
1173 if (IDVal == ".fill")
1174 return ParseDirectiveFill();
1175 if (IDVal == ".space" || IDVal == ".skip")
1176 return ParseDirectiveSpace();
1177 if (IDVal == ".zero")
1178 return ParseDirectiveZero();
1180 // Symbol attribute directives
1182 if (IDVal == ".globl" || IDVal == ".global")
1183 return ParseDirectiveSymbolAttribute(MCSA_Global);
1184 if (IDVal == ".indirect_symbol")
1185 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1186 if (IDVal == ".lazy_reference")
1187 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1188 if (IDVal == ".no_dead_strip")
1189 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1190 if (IDVal == ".symbol_resolver")
1191 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1192 if (IDVal == ".private_extern")
1193 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1194 if (IDVal == ".reference")
1195 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1196 if (IDVal == ".weak_definition")
1197 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1198 if (IDVal == ".weak_reference")
1199 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1200 if (IDVal == ".weak_def_can_be_hidden")
1201 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1203 if (IDVal == ".comm" || IDVal == ".common")
1204 return ParseDirectiveComm(/*IsLocal=*/false);
1205 if (IDVal == ".lcomm")
1206 return ParseDirectiveComm(/*IsLocal=*/true);
1208 if (IDVal == ".abort")
1209 return ParseDirectiveAbort();
1210 if (IDVal == ".include")
1211 return ParseDirectiveInclude();
1212 if (IDVal == ".incbin")
1213 return ParseDirectiveIncbin();
1215 if (IDVal == ".code16")
1216 return TokError(Twine(IDVal) + " not supported yet");
1218 // Look up the handler in the handler table.
1219 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1220 DirectiveMap.lookup(IDVal);
1222 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1224 // Target hook for parsing target specific directives.
1225 if (!getTargetParser().ParseDirective(ID))
1228 bool retval = Warning(IDLoc, "ignoring directive for now");
1229 EatToEndOfStatement();
1233 CheckForValidSection();
1235 // Canonicalize the opcode to lower case.
1236 SmallString<128> Opcode;
1237 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1238 Opcode.push_back(tolower(IDVal[i]));
1240 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1241 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1244 // Dump the parsed representation, if requested.
1245 if (getShowParsedOperands()) {
1246 SmallString<256> Str;
1247 raw_svector_ostream OS(Str);
1248 OS << "parsed instruction: [";
1249 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1252 ParsedOperands[i]->print(OS);
1256 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1259 // If we are generating dwarf for assembly source files and the current
1260 // section is the initial text section then generate a .loc directive for
1262 if (!HadError && getContext().getGenDwarfForAssembly() &&
1263 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1264 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1265 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1266 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1267 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1271 // If parsing succeeded, match the instruction.
1273 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1276 // Free any parsed operands.
1277 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1278 delete ParsedOperands[i];
1280 // Don't skip the rest of the line, the instruction parser is responsible for
1285 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1286 /// since they may not be able to be tokenized to get to the end of line token.
1287 void AsmParser::EatToEndOfLine() {
1288 if (!Lexer.is(AsmToken::EndOfStatement))
1289 Lexer.LexUntilEndOfLine();
1294 /// ParseCppHashLineFilenameComment as this:
1295 /// ::= # number "filename"
1296 /// or just as a full line comment if it doesn't have a number and a string.
1297 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1298 Lex(); // Eat the hash token.
1300 if (getLexer().isNot(AsmToken::Integer)) {
1301 // Consume the line since in cases it is not a well-formed line directive,
1302 // as if were simply a full line comment.
1307 int64_t LineNumber = getTok().getIntVal();
1310 if (getLexer().isNot(AsmToken::String)) {
1315 StringRef Filename = getTok().getString();
1316 // Get rid of the enclosing quotes.
1317 Filename = Filename.substr(1, Filename.size()-2);
1319 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1321 CppHashFilename = Filename;
1322 CppHashLineNumber = LineNumber;
1324 // Ignore any trailing characters, they're just comment.
1329 /// DiagHandler - will use the the last parsed cpp hash line filename comment
1330 /// for the Filename and LineNo if any in the diagnostic.
1331 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1332 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1333 raw_ostream &OS = errs();
1335 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1336 const SMLoc &DiagLoc = Diag.getLoc();
1337 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1338 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1340 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1341 // before printing the message.
1342 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1343 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1344 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1345 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1348 // If we have not parsed a cpp hash line filename comment or the source
1349 // manager changed or buffer changed (like in a nested include) then just
1350 // print the normal diagnostic using its Filename and LineNo.
1351 if (!Parser->CppHashLineNumber ||
1352 &DiagSrcMgr != &Parser->SrcMgr ||
1353 DiagBuf != CppHashBuf) {
1354 if (Parser->SavedDiagHandler)
1355 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1361 // Use the CppHashFilename and calculate a line number based on the
1362 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1364 const std::string Filename = Parser->CppHashFilename;
1366 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1367 int CppHashLocLineNo =
1368 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1369 int LineNo = Parser->CppHashLineNumber - 1 +
1370 (DiagLocLineNo - CppHashLocLineNo);
1372 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1373 Filename, LineNo, Diag.getColumnNo(),
1374 Diag.getKind(), Diag.getMessage(),
1375 Diag.getLineContents(), Diag.getRanges());
1377 if (Parser->SavedDiagHandler)
1378 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1380 NewDiag.print(0, OS);
1383 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1384 const std::vector<StringRef> &Parameters,
1385 const std::vector<std::vector<AsmToken> > &A,
1387 raw_svector_ostream OS(Buf);
1388 unsigned NParameters = Parameters.size();
1389 if (NParameters != 0 && NParameters != A.size())
1390 return Error(L, "Wrong number of arguments");
1392 while (!Body.empty()) {
1393 // Scan for the next substitution.
1394 std::size_t End = Body.size(), Pos = 0;
1395 for (; Pos != End; ++Pos) {
1396 // Check for a substitution or escape.
1398 // This macro has no parameters, look for $0, $1, etc.
1399 if (Body[Pos] != '$' || Pos + 1 == End)
1402 char Next = Body[Pos + 1];
1403 if (Next == '$' || Next == 'n' || isdigit(Next))
1406 // This macro has parameters, look for \foo, \bar, etc.
1407 if (Body[Pos] == '\\' && Pos + 1 != End)
1413 OS << Body.slice(0, Pos);
1415 // Check if we reached the end.
1420 switch (Body[Pos+1]) {
1426 // $n => number of arguments
1431 // $[0-9] => argument
1433 // Missing arguments are ignored.
1434 unsigned Index = Body[Pos+1] - '0';
1435 if (Index >= A.size())
1438 // Otherwise substitute with the token values, with spaces eliminated.
1439 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1440 ie = A[Index].end(); it != ie; ++it)
1441 OS << it->getString();
1447 unsigned I = Pos + 1;
1448 while (isalnum(Body[I]) && I + 1 != End)
1451 const char *Begin = Body.data() + Pos +1;
1452 StringRef Argument(Begin, I - (Pos +1));
1454 for (; Index < NParameters; ++Index)
1455 if (Parameters[Index] == Argument)
1458 // FIXME: We should error at the macro definition.
1459 if (Index == NParameters)
1460 return Error(L, "Parameter not found");
1462 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1463 ie = A[Index].end(); it != ie; ++it)
1464 OS << it->getString();
1466 Pos += 1 + Argument.size();
1468 // Update the scan point.
1469 Body = Body.substr(Pos);
1472 // We include the .endmacro in the buffer as our queue to exit the macro
1474 OS << ".endmacro\n";
1478 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1480 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1484 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1486 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1487 // this, although we should protect against infinite loops.
1488 if (ActiveMacros.size() == 20)
1489 return TokError("macros cannot be nested more than 20 levels deep");
1491 // Parse the macro instantiation arguments.
1492 std::vector<std::vector<AsmToken> > MacroArguments;
1493 MacroArguments.push_back(std::vector<AsmToken>());
1494 unsigned ParenLevel = 0;
1496 if (Lexer.is(AsmToken::Eof))
1497 return TokError("unexpected token in macro instantiation");
1498 if (Lexer.is(AsmToken::EndOfStatement))
1501 // If we aren't inside parentheses and this is a comma, start a new token
1503 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1504 MacroArguments.push_back(std::vector<AsmToken>());
1506 // Adjust the current parentheses level.
1507 if (Lexer.is(AsmToken::LParen))
1509 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1512 // Append the token to the current argument list.
1513 MacroArguments.back().push_back(getTok());
1518 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1519 // to hold the macro body with substitutions.
1520 SmallString<256> Buf;
1521 StringRef Body = M->Body;
1523 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1526 MemoryBuffer *Instantiation =
1527 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1529 // Create the macro instantiation object and add to the current macro
1530 // instantiation stack.
1531 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1534 ActiveMacros.push_back(MI);
1536 // Jump to the macro instantiation and prime the lexer.
1537 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1538 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1544 void AsmParser::HandleMacroExit() {
1545 // Jump to the EndOfStatement we should return to, and consume it.
1546 JumpToLoc(ActiveMacros.back()->ExitLoc);
1549 // Pop the instantiation entry.
1550 delete ActiveMacros.back();
1551 ActiveMacros.pop_back();
1554 static void MarkUsed(const MCExpr *Value) {
1555 switch (Value->getKind()) {
1556 case MCExpr::Binary:
1557 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1558 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1560 case MCExpr::Target:
1561 case MCExpr::Constant:
1563 case MCExpr::SymbolRef: {
1564 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1568 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1573 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
1574 // FIXME: Use better location, we should use proper tokens.
1575 SMLoc EqualLoc = Lexer.getLoc();
1577 const MCExpr *Value;
1578 if (ParseExpression(Value))
1583 if (Lexer.isNot(AsmToken::EndOfStatement))
1584 return TokError("unexpected token in assignment");
1586 // Error on assignment to '.'.
1588 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1589 "(use '.space' or '.org').)"));
1592 // Eat the end of statement marker.
1595 // Validate that the LHS is allowed to be a variable (either it has not been
1596 // used as a symbol, or it is an absolute symbol).
1597 MCSymbol *Sym = getContext().LookupSymbol(Name);
1599 // Diagnose assignment to a label.
1601 // FIXME: Diagnostics. Note the location of the definition as a label.
1602 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1603 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1604 ; // Allow redefinitions of undefined symbols only used in directives.
1605 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1606 return Error(EqualLoc, "redefinition of '" + Name + "'");
1607 else if (!Sym->isVariable())
1608 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1609 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1610 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1613 // Don't count these checks as uses.
1614 Sym->setUsed(false);
1616 Sym = getContext().GetOrCreateSymbol(Name);
1618 // FIXME: Handle '.'.
1620 // Do the assignment.
1621 Out.EmitAssignment(Sym, Value);
1626 /// ParseIdentifier:
1629 bool AsmParser::ParseIdentifier(StringRef &Res) {
1630 // The assembler has relaxed rules for accepting identifiers, in particular we
1631 // allow things like '.globl $foo', which would normally be separate
1632 // tokens. At this level, we have already lexed so we cannot (currently)
1633 // handle this as a context dependent token, instead we detect adjacent tokens
1634 // and return the combined identifier.
1635 if (Lexer.is(AsmToken::Dollar)) {
1636 SMLoc DollarLoc = getLexer().getLoc();
1638 // Consume the dollar sign, and check for a following identifier.
1640 if (Lexer.isNot(AsmToken::Identifier))
1643 // We have a '$' followed by an identifier, make sure they are adjacent.
1644 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1647 // Construct the joined identifier and consume the token.
1648 Res = StringRef(DollarLoc.getPointer(),
1649 getTok().getIdentifier().size() + 1);
1654 if (Lexer.isNot(AsmToken::Identifier) &&
1655 Lexer.isNot(AsmToken::String))
1658 Res = getTok().getIdentifier();
1660 Lex(); // Consume the identifier token.
1665 /// ParseDirectiveSet:
1666 /// ::= .equ identifier ',' expression
1667 /// ::= .equiv identifier ',' expression
1668 /// ::= .set identifier ',' expression
1669 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1672 if (ParseIdentifier(Name))
1673 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1675 if (getLexer().isNot(AsmToken::Comma))
1676 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1679 return ParseAssignment(Name, allow_redef);
1682 bool AsmParser::ParseEscapedString(std::string &Data) {
1683 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1686 StringRef Str = getTok().getStringContents();
1687 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1688 if (Str[i] != '\\') {
1693 // Recognize escaped characters. Note that this escape semantics currently
1694 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1697 return TokError("unexpected backslash at end of string");
1699 // Recognize octal sequences.
1700 if ((unsigned) (Str[i] - '0') <= 7) {
1701 // Consume up to three octal characters.
1702 unsigned Value = Str[i] - '0';
1704 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1706 Value = Value * 8 + (Str[i] - '0');
1708 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1710 Value = Value * 8 + (Str[i] - '0');
1715 return TokError("invalid octal escape sequence (out of range)");
1717 Data += (unsigned char) Value;
1721 // Otherwise recognize individual escapes.
1724 // Just reject invalid escape sequences for now.
1725 return TokError("invalid escape sequence (unrecognized character)");
1727 case 'b': Data += '\b'; break;
1728 case 'f': Data += '\f'; break;
1729 case 'n': Data += '\n'; break;
1730 case 'r': Data += '\r'; break;
1731 case 't': Data += '\t'; break;
1732 case '"': Data += '"'; break;
1733 case '\\': Data += '\\'; break;
1740 /// ParseDirectiveAscii:
1741 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1742 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
1743 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1744 CheckForValidSection();
1747 if (getLexer().isNot(AsmToken::String))
1748 return TokError("expected string in '" + Twine(IDVal) + "' directive");
1751 if (ParseEscapedString(Data))
1754 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
1756 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1760 if (getLexer().is(AsmToken::EndOfStatement))
1763 if (getLexer().isNot(AsmToken::Comma))
1764 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
1773 /// ParseDirectiveValue
1774 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1775 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1776 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1777 CheckForValidSection();
1780 const MCExpr *Value;
1781 SMLoc ExprLoc = getLexer().getLoc();
1782 if (ParseExpression(Value))
1785 // Special case constant expressions to match code generator.
1786 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1787 assert(Size <= 8 && "Invalid size");
1788 uint64_t IntValue = MCE->getValue();
1789 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1790 return Error(ExprLoc, "literal value out of range for directive");
1791 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1793 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1795 if (getLexer().is(AsmToken::EndOfStatement))
1798 // FIXME: Improve diagnostic.
1799 if (getLexer().isNot(AsmToken::Comma))
1800 return TokError("unexpected token in directive");
1809 /// ParseDirectiveRealValue
1810 /// ::= (.single | .double) [ expression (, expression)* ]
1811 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1812 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1813 CheckForValidSection();
1816 // We don't truly support arithmetic on floating point expressions, so we
1817 // have to manually parse unary prefixes.
1819 if (getLexer().is(AsmToken::Minus)) {
1822 } else if (getLexer().is(AsmToken::Plus))
1825 if (getLexer().isNot(AsmToken::Integer) &&
1826 getLexer().isNot(AsmToken::Real) &&
1827 getLexer().isNot(AsmToken::Identifier))
1828 return TokError("unexpected token in directive");
1830 // Convert to an APFloat.
1831 APFloat Value(Semantics);
1832 StringRef IDVal = getTok().getString();
1833 if (getLexer().is(AsmToken::Identifier)) {
1834 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1835 Value = APFloat::getInf(Semantics);
1836 else if (!IDVal.compare_lower("nan"))
1837 Value = APFloat::getNaN(Semantics, false, ~0);
1839 return TokError("invalid floating point literal");
1840 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
1841 APFloat::opInvalidOp)
1842 return TokError("invalid floating point literal");
1846 // Consume the numeric token.
1849 // Emit the value as an integer.
1850 APInt AsInt = Value.bitcastToAPInt();
1851 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1852 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1854 if (getLexer().is(AsmToken::EndOfStatement))
1857 if (getLexer().isNot(AsmToken::Comma))
1858 return TokError("unexpected token in directive");
1867 /// ParseDirectiveSpace
1868 /// ::= .space expression [ , expression ]
1869 bool AsmParser::ParseDirectiveSpace() {
1870 CheckForValidSection();
1873 if (ParseAbsoluteExpression(NumBytes))
1876 int64_t FillExpr = 0;
1877 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1878 if (getLexer().isNot(AsmToken::Comma))
1879 return TokError("unexpected token in '.space' directive");
1882 if (ParseAbsoluteExpression(FillExpr))
1885 if (getLexer().isNot(AsmToken::EndOfStatement))
1886 return TokError("unexpected token in '.space' directive");
1892 return TokError("invalid number of bytes in '.space' directive");
1894 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1895 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1900 /// ParseDirectiveZero
1901 /// ::= .zero expression
1902 bool AsmParser::ParseDirectiveZero() {
1903 CheckForValidSection();
1906 if (ParseAbsoluteExpression(NumBytes))
1910 if (getLexer().is(AsmToken::Comma)) {
1912 if (ParseAbsoluteExpression(Val))
1916 if (getLexer().isNot(AsmToken::EndOfStatement))
1917 return TokError("unexpected token in '.zero' directive");
1921 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
1926 /// ParseDirectiveFill
1927 /// ::= .fill expression , expression , expression
1928 bool AsmParser::ParseDirectiveFill() {
1929 CheckForValidSection();
1932 if (ParseAbsoluteExpression(NumValues))
1935 if (getLexer().isNot(AsmToken::Comma))
1936 return TokError("unexpected token in '.fill' directive");
1940 if (ParseAbsoluteExpression(FillSize))
1943 if (getLexer().isNot(AsmToken::Comma))
1944 return TokError("unexpected token in '.fill' directive");
1948 if (ParseAbsoluteExpression(FillExpr))
1951 if (getLexer().isNot(AsmToken::EndOfStatement))
1952 return TokError("unexpected token in '.fill' directive");
1956 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1957 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1959 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1960 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
1965 /// ParseDirectiveOrg
1966 /// ::= .org expression [ , expression ]
1967 bool AsmParser::ParseDirectiveOrg() {
1968 CheckForValidSection();
1970 const MCExpr *Offset;
1971 if (ParseExpression(Offset))
1974 // Parse optional fill expression.
1975 int64_t FillExpr = 0;
1976 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1977 if (getLexer().isNot(AsmToken::Comma))
1978 return TokError("unexpected token in '.org' directive");
1981 if (ParseAbsoluteExpression(FillExpr))
1984 if (getLexer().isNot(AsmToken::EndOfStatement))
1985 return TokError("unexpected token in '.org' directive");
1990 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1991 // has to be relative to the current section.
1992 getStreamer().EmitValueToOffset(Offset, FillExpr);
1997 /// ParseDirectiveAlign
1998 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1999 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2000 CheckForValidSection();
2002 SMLoc AlignmentLoc = getLexer().getLoc();
2004 if (ParseAbsoluteExpression(Alignment))
2008 bool HasFillExpr = false;
2009 int64_t FillExpr = 0;
2010 int64_t MaxBytesToFill = 0;
2011 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2012 if (getLexer().isNot(AsmToken::Comma))
2013 return TokError("unexpected token in directive");
2016 // The fill expression can be omitted while specifying a maximum number of
2017 // alignment bytes, e.g:
2019 if (getLexer().isNot(AsmToken::Comma)) {
2021 if (ParseAbsoluteExpression(FillExpr))
2025 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2026 if (getLexer().isNot(AsmToken::Comma))
2027 return TokError("unexpected token in directive");
2030 MaxBytesLoc = getLexer().getLoc();
2031 if (ParseAbsoluteExpression(MaxBytesToFill))
2034 if (getLexer().isNot(AsmToken::EndOfStatement))
2035 return TokError("unexpected token in directive");
2044 // Compute alignment in bytes.
2046 // FIXME: Diagnose overflow.
2047 if (Alignment >= 32) {
2048 Error(AlignmentLoc, "invalid alignment value");
2052 Alignment = 1ULL << Alignment;
2055 // Diagnose non-sensical max bytes to align.
2056 if (MaxBytesLoc.isValid()) {
2057 if (MaxBytesToFill < 1) {
2058 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2059 "many bytes, ignoring maximum bytes expression");
2063 if (MaxBytesToFill >= Alignment) {
2064 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2070 // Check whether we should use optimal code alignment for this .align
2072 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2073 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2074 ValueSize == 1 && UseCodeAlign) {
2075 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2077 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2078 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2085 /// ParseDirectiveSymbolAttribute
2086 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2087 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2088 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2091 SMLoc Loc = getTok().getLoc();
2093 if (ParseIdentifier(Name))
2094 return Error(Loc, "expected identifier in directive");
2096 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2098 // Assembler local symbols don't make any sense here. Complain loudly.
2099 if (Sym->isTemporary())
2100 return Error(Loc, "non-local symbol required in directive");
2102 getStreamer().EmitSymbolAttribute(Sym, Attr);
2104 if (getLexer().is(AsmToken::EndOfStatement))
2107 if (getLexer().isNot(AsmToken::Comma))
2108 return TokError("unexpected token in directive");
2117 /// ParseDirectiveComm
2118 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2119 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2120 CheckForValidSection();
2122 SMLoc IDLoc = getLexer().getLoc();
2124 if (ParseIdentifier(Name))
2125 return TokError("expected identifier in directive");
2127 // Handle the identifier as the key symbol.
2128 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2130 if (getLexer().isNot(AsmToken::Comma))
2131 return TokError("unexpected token in directive");
2135 SMLoc SizeLoc = getLexer().getLoc();
2136 if (ParseAbsoluteExpression(Size))
2139 int64_t Pow2Alignment = 0;
2140 SMLoc Pow2AlignmentLoc;
2141 if (getLexer().is(AsmToken::Comma)) {
2143 Pow2AlignmentLoc = getLexer().getLoc();
2144 if (ParseAbsoluteExpression(Pow2Alignment))
2147 // If this target takes alignments in bytes (not log) validate and convert.
2148 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2149 if (!isPowerOf2_64(Pow2Alignment))
2150 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2151 Pow2Alignment = Log2_64(Pow2Alignment);
2155 if (getLexer().isNot(AsmToken::EndOfStatement))
2156 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2160 // NOTE: a size of zero for a .comm should create a undefined symbol
2161 // but a size of .lcomm creates a bss symbol of size zero.
2163 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2164 "be less than zero");
2166 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2167 // may internally end up wanting an alignment in bytes.
2168 // FIXME: Diagnose overflow.
2169 if (Pow2Alignment < 0)
2170 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2171 "alignment, can't be less than zero");
2173 if (!Sym->isUndefined())
2174 return Error(IDLoc, "invalid symbol redefinition");
2176 // '.lcomm' is equivalent to '.zerofill'.
2177 // Create the Symbol as a common or local common with Size and Pow2Alignment
2179 getStreamer().EmitZerofill(Ctx.getMachOSection(
2180 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2181 0, SectionKind::getBSS()),
2182 Sym, Size, 1 << Pow2Alignment);
2186 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2190 /// ParseDirectiveAbort
2191 /// ::= .abort [... message ...]
2192 bool AsmParser::ParseDirectiveAbort() {
2193 // FIXME: Use loc from directive.
2194 SMLoc Loc = getLexer().getLoc();
2196 StringRef Str = ParseStringToEndOfStatement();
2197 if (getLexer().isNot(AsmToken::EndOfStatement))
2198 return TokError("unexpected token in '.abort' directive");
2203 Error(Loc, ".abort detected. Assembly stopping.");
2205 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2206 // FIXME: Actually abort assembly here.
2211 /// ParseDirectiveInclude
2212 /// ::= .include "filename"
2213 bool AsmParser::ParseDirectiveInclude() {
2214 if (getLexer().isNot(AsmToken::String))
2215 return TokError("expected string in '.include' directive");
2217 std::string Filename = getTok().getString();
2218 SMLoc IncludeLoc = getLexer().getLoc();
2221 if (getLexer().isNot(AsmToken::EndOfStatement))
2222 return TokError("unexpected token in '.include' directive");
2224 // Strip the quotes.
2225 Filename = Filename.substr(1, Filename.size()-2);
2227 // Attempt to switch the lexer to the included file before consuming the end
2228 // of statement to avoid losing it when we switch.
2229 if (EnterIncludeFile(Filename)) {
2230 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2237 /// ParseDirectiveIncbin
2238 /// ::= .incbin "filename"
2239 bool AsmParser::ParseDirectiveIncbin() {
2240 if (getLexer().isNot(AsmToken::String))
2241 return TokError("expected string in '.incbin' directive");
2243 std::string Filename = getTok().getString();
2244 SMLoc IncbinLoc = getLexer().getLoc();
2247 if (getLexer().isNot(AsmToken::EndOfStatement))
2248 return TokError("unexpected token in '.incbin' directive");
2250 // Strip the quotes.
2251 Filename = Filename.substr(1, Filename.size()-2);
2253 // Attempt to process the included file.
2254 if (ProcessIncbinFile(Filename)) {
2255 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2262 /// ParseDirectiveIf
2263 /// ::= .if expression
2264 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2265 TheCondStack.push_back(TheCondState);
2266 TheCondState.TheCond = AsmCond::IfCond;
2267 if(TheCondState.Ignore) {
2268 EatToEndOfStatement();
2272 if (ParseAbsoluteExpression(ExprValue))
2275 if (getLexer().isNot(AsmToken::EndOfStatement))
2276 return TokError("unexpected token in '.if' directive");
2280 TheCondState.CondMet = ExprValue;
2281 TheCondState.Ignore = !TheCondState.CondMet;
2287 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2289 TheCondStack.push_back(TheCondState);
2290 TheCondState.TheCond = AsmCond::IfCond;
2292 if (TheCondState.Ignore) {
2293 EatToEndOfStatement();
2295 if (ParseIdentifier(Name))
2296 return TokError("expected identifier after '.ifdef'");
2300 MCSymbol *Sym = getContext().LookupSymbol(Name);
2303 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2305 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2306 TheCondState.Ignore = !TheCondState.CondMet;
2312 /// ParseDirectiveElseIf
2313 /// ::= .elseif expression
2314 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2315 if (TheCondState.TheCond != AsmCond::IfCond &&
2316 TheCondState.TheCond != AsmCond::ElseIfCond)
2317 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2319 TheCondState.TheCond = AsmCond::ElseIfCond;
2321 bool LastIgnoreState = false;
2322 if (!TheCondStack.empty())
2323 LastIgnoreState = TheCondStack.back().Ignore;
2324 if (LastIgnoreState || TheCondState.CondMet) {
2325 TheCondState.Ignore = true;
2326 EatToEndOfStatement();
2330 if (ParseAbsoluteExpression(ExprValue))
2333 if (getLexer().isNot(AsmToken::EndOfStatement))
2334 return TokError("unexpected token in '.elseif' directive");
2337 TheCondState.CondMet = ExprValue;
2338 TheCondState.Ignore = !TheCondState.CondMet;
2344 /// ParseDirectiveElse
2346 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2347 if (getLexer().isNot(AsmToken::EndOfStatement))
2348 return TokError("unexpected token in '.else' directive");
2352 if (TheCondState.TheCond != AsmCond::IfCond &&
2353 TheCondState.TheCond != AsmCond::ElseIfCond)
2354 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2356 TheCondState.TheCond = AsmCond::ElseCond;
2357 bool LastIgnoreState = false;
2358 if (!TheCondStack.empty())
2359 LastIgnoreState = TheCondStack.back().Ignore;
2360 if (LastIgnoreState || TheCondState.CondMet)
2361 TheCondState.Ignore = true;
2363 TheCondState.Ignore = false;
2368 /// ParseDirectiveEndIf
2370 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2371 if (getLexer().isNot(AsmToken::EndOfStatement))
2372 return TokError("unexpected token in '.endif' directive");
2376 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2377 TheCondStack.empty())
2378 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2380 if (!TheCondStack.empty()) {
2381 TheCondState = TheCondStack.back();
2382 TheCondStack.pop_back();
2388 /// ParseDirectiveFile
2389 /// ::= .file [number] filename
2390 /// ::= .file number directory filename
2391 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2392 // FIXME: I'm not sure what this is.
2393 int64_t FileNumber = -1;
2394 SMLoc FileNumberLoc = getLexer().getLoc();
2395 if (getLexer().is(AsmToken::Integer)) {
2396 FileNumber = getTok().getIntVal();
2400 return TokError("file number less than one");
2403 if (getLexer().isNot(AsmToken::String))
2404 return TokError("unexpected token in '.file' directive");
2406 // Usually the directory and filename together, otherwise just the directory.
2407 StringRef Path = getTok().getString();
2408 Path = Path.substr(1, Path.size()-2);
2411 StringRef Directory;
2413 if (getLexer().is(AsmToken::String)) {
2414 if (FileNumber == -1)
2415 return TokError("explicit path specified, but no file number");
2416 Filename = getTok().getString();
2417 Filename = Filename.substr(1, Filename.size()-2);
2424 if (getLexer().isNot(AsmToken::EndOfStatement))
2425 return TokError("unexpected token in '.file' directive");
2427 if (getContext().getGenDwarfForAssembly() == true)
2428 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2429 "used to generate dwarf debug info for assembly code");
2431 if (FileNumber == -1)
2432 getStreamer().EmitFileDirective(Filename);
2434 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2435 Error(FileNumberLoc, "file number already allocated");
2441 /// ParseDirectiveLine
2442 /// ::= .line [number]
2443 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2444 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2445 if (getLexer().isNot(AsmToken::Integer))
2446 return TokError("unexpected token in '.line' directive");
2448 int64_t LineNumber = getTok().getIntVal();
2452 // FIXME: Do something with the .line.
2455 if (getLexer().isNot(AsmToken::EndOfStatement))
2456 return TokError("unexpected token in '.line' directive");
2462 /// ParseDirectiveLoc
2463 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2464 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2465 /// The first number is a file number, must have been previously assigned with
2466 /// a .file directive, the second number is the line number and optionally the
2467 /// third number is a column position (zero if not specified). The remaining
2468 /// optional items are .loc sub-directives.
2469 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2471 if (getLexer().isNot(AsmToken::Integer))
2472 return TokError("unexpected token in '.loc' directive");
2473 int64_t FileNumber = getTok().getIntVal();
2475 return TokError("file number less than one in '.loc' directive");
2476 if (!getContext().isValidDwarfFileNumber(FileNumber))
2477 return TokError("unassigned file number in '.loc' directive");
2480 int64_t LineNumber = 0;
2481 if (getLexer().is(AsmToken::Integer)) {
2482 LineNumber = getTok().getIntVal();
2484 return TokError("line number less than one in '.loc' directive");
2488 int64_t ColumnPos = 0;
2489 if (getLexer().is(AsmToken::Integer)) {
2490 ColumnPos = getTok().getIntVal();
2492 return TokError("column position less than zero in '.loc' directive");
2496 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2498 int64_t Discriminator = 0;
2499 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2501 if (getLexer().is(AsmToken::EndOfStatement))
2505 SMLoc Loc = getTok().getLoc();
2506 if (getParser().ParseIdentifier(Name))
2507 return TokError("unexpected token in '.loc' directive");
2509 if (Name == "basic_block")
2510 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2511 else if (Name == "prologue_end")
2512 Flags |= DWARF2_FLAG_PROLOGUE_END;
2513 else if (Name == "epilogue_begin")
2514 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2515 else if (Name == "is_stmt") {
2516 SMLoc Loc = getTok().getLoc();
2517 const MCExpr *Value;
2518 if (getParser().ParseExpression(Value))
2520 // The expression must be the constant 0 or 1.
2521 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2522 int Value = MCE->getValue();
2524 Flags &= ~DWARF2_FLAG_IS_STMT;
2525 else if (Value == 1)
2526 Flags |= DWARF2_FLAG_IS_STMT;
2528 return Error(Loc, "is_stmt value not 0 or 1");
2531 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2534 else if (Name == "isa") {
2535 SMLoc Loc = getTok().getLoc();
2536 const MCExpr *Value;
2537 if (getParser().ParseExpression(Value))
2539 // The expression must be a constant greater or equal to 0.
2540 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2541 int Value = MCE->getValue();
2543 return Error(Loc, "isa number less than zero");
2547 return Error(Loc, "isa number not a constant value");
2550 else if (Name == "discriminator") {
2551 if (getParser().ParseAbsoluteExpression(Discriminator))
2555 return Error(Loc, "unknown sub-directive in '.loc' directive");
2558 if (getLexer().is(AsmToken::EndOfStatement))
2563 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2564 Isa, Discriminator, StringRef());
2569 /// ParseDirectiveStabs
2570 /// ::= .stabs string, number, number, number
2571 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2572 SMLoc DirectiveLoc) {
2573 return TokError("unsupported directive '" + Directive + "'");
2576 /// ParseDirectiveCFISections
2577 /// ::= .cfi_sections section [, section]
2578 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2579 SMLoc DirectiveLoc) {
2584 if (getParser().ParseIdentifier(Name))
2585 return TokError("Expected an identifier");
2587 if (Name == ".eh_frame")
2589 else if (Name == ".debug_frame")
2592 if (getLexer().is(AsmToken::Comma)) {
2595 if (getParser().ParseIdentifier(Name))
2596 return TokError("Expected an identifier");
2598 if (Name == ".eh_frame")
2600 else if (Name == ".debug_frame")
2604 getStreamer().EmitCFISections(EH, Debug);
2609 /// ParseDirectiveCFIStartProc
2610 /// ::= .cfi_startproc
2611 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2612 SMLoc DirectiveLoc) {
2613 getStreamer().EmitCFIStartProc();
2617 /// ParseDirectiveCFIEndProc
2618 /// ::= .cfi_endproc
2619 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2620 getStreamer().EmitCFIEndProc();
2624 /// ParseRegisterOrRegisterNumber - parse register name or number.
2625 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2626 SMLoc DirectiveLoc) {
2629 if (getLexer().isNot(AsmToken::Integer)) {
2630 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2633 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2635 return getParser().ParseAbsoluteExpression(Register);
2640 /// ParseDirectiveCFIDefCfa
2641 /// ::= .cfi_def_cfa register, offset
2642 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2643 SMLoc DirectiveLoc) {
2644 int64_t Register = 0;
2645 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2648 if (getLexer().isNot(AsmToken::Comma))
2649 return TokError("unexpected token in directive");
2653 if (getParser().ParseAbsoluteExpression(Offset))
2656 getStreamer().EmitCFIDefCfa(Register, Offset);
2660 /// ParseDirectiveCFIDefCfaOffset
2661 /// ::= .cfi_def_cfa_offset offset
2662 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2663 SMLoc DirectiveLoc) {
2665 if (getParser().ParseAbsoluteExpression(Offset))
2668 getStreamer().EmitCFIDefCfaOffset(Offset);
2672 /// ParseDirectiveCFIAdjustCfaOffset
2673 /// ::= .cfi_adjust_cfa_offset adjustment
2674 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2675 SMLoc DirectiveLoc) {
2676 int64_t Adjustment = 0;
2677 if (getParser().ParseAbsoluteExpression(Adjustment))
2680 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2684 /// ParseDirectiveCFIDefCfaRegister
2685 /// ::= .cfi_def_cfa_register register
2686 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2687 SMLoc DirectiveLoc) {
2688 int64_t Register = 0;
2689 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2692 getStreamer().EmitCFIDefCfaRegister(Register);
2696 /// ParseDirectiveCFIOffset
2697 /// ::= .cfi_offset register, offset
2698 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2699 int64_t Register = 0;
2702 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2705 if (getLexer().isNot(AsmToken::Comma))
2706 return TokError("unexpected token in directive");
2709 if (getParser().ParseAbsoluteExpression(Offset))
2712 getStreamer().EmitCFIOffset(Register, Offset);
2716 /// ParseDirectiveCFIRelOffset
2717 /// ::= .cfi_rel_offset register, offset
2718 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2719 SMLoc DirectiveLoc) {
2720 int64_t Register = 0;
2722 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2725 if (getLexer().isNot(AsmToken::Comma))
2726 return TokError("unexpected token in directive");
2730 if (getParser().ParseAbsoluteExpression(Offset))
2733 getStreamer().EmitCFIRelOffset(Register, Offset);
2737 static bool isValidEncoding(int64_t Encoding) {
2738 if (Encoding & ~0xff)
2741 if (Encoding == dwarf::DW_EH_PE_omit)
2744 const unsigned Format = Encoding & 0xf;
2745 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2746 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2747 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2748 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2751 const unsigned Application = Encoding & 0x70;
2752 if (Application != dwarf::DW_EH_PE_absptr &&
2753 Application != dwarf::DW_EH_PE_pcrel)
2759 /// ParseDirectiveCFIPersonalityOrLsda
2760 /// ::= .cfi_personality encoding, [symbol_name]
2761 /// ::= .cfi_lsda encoding, [symbol_name]
2762 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
2763 SMLoc DirectiveLoc) {
2764 int64_t Encoding = 0;
2765 if (getParser().ParseAbsoluteExpression(Encoding))
2767 if (Encoding == dwarf::DW_EH_PE_omit)
2770 if (!isValidEncoding(Encoding))
2771 return TokError("unsupported encoding.");
2773 if (getLexer().isNot(AsmToken::Comma))
2774 return TokError("unexpected token in directive");
2778 if (getParser().ParseIdentifier(Name))
2779 return TokError("expected identifier in directive");
2781 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2783 if (IDVal == ".cfi_personality")
2784 getStreamer().EmitCFIPersonality(Sym, Encoding);
2786 assert(IDVal == ".cfi_lsda");
2787 getStreamer().EmitCFILsda(Sym, Encoding);
2792 /// ParseDirectiveCFIRememberState
2793 /// ::= .cfi_remember_state
2794 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2795 SMLoc DirectiveLoc) {
2796 getStreamer().EmitCFIRememberState();
2800 /// ParseDirectiveCFIRestoreState
2801 /// ::= .cfi_remember_state
2802 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2803 SMLoc DirectiveLoc) {
2804 getStreamer().EmitCFIRestoreState();
2808 /// ParseDirectiveCFISameValue
2809 /// ::= .cfi_same_value register
2810 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2811 SMLoc DirectiveLoc) {
2812 int64_t Register = 0;
2814 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2817 getStreamer().EmitCFISameValue(Register);
2822 /// ParseDirectiveCFIRestore
2823 /// ::= .cfi_restore register
2824 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2825 SMLoc DirectiveLoc) {
2826 int64_t Register = 0;
2827 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2830 getStreamer().EmitCFIRestore(Register);
2835 /// ParseDirectiveCFIEscape
2836 /// ::= .cfi_escape expression[,...]
2837 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2838 SMLoc DirectiveLoc) {
2841 if (getParser().ParseAbsoluteExpression(CurrValue))
2844 Values.push_back((uint8_t)CurrValue);
2846 while (getLexer().is(AsmToken::Comma)) {
2849 if (getParser().ParseAbsoluteExpression(CurrValue))
2852 Values.push_back((uint8_t)CurrValue);
2855 getStreamer().EmitCFIEscape(Values);
2859 /// ParseDirectiveMacrosOnOff
2862 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2863 SMLoc DirectiveLoc) {
2864 if (getLexer().isNot(AsmToken::EndOfStatement))
2865 return Error(getLexer().getLoc(),
2866 "unexpected token in '" + Directive + "' directive");
2868 getParser().MacrosEnabled = Directive == ".macros_on";
2873 /// ParseDirectiveMacro
2874 /// ::= .macro name [parameters]
2875 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2876 SMLoc DirectiveLoc) {
2878 if (getParser().ParseIdentifier(Name))
2879 return TokError("expected identifier in directive");
2881 std::vector<StringRef> Parameters;
2882 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2884 StringRef Parameter;
2885 if (getParser().ParseIdentifier(Parameter))
2886 return TokError("expected identifier in directive");
2887 Parameters.push_back(Parameter);
2889 if (getLexer().isNot(AsmToken::Comma))
2895 if (getLexer().isNot(AsmToken::EndOfStatement))
2896 return TokError("unexpected token in '.macro' directive");
2898 // Eat the end of statement.
2901 AsmToken EndToken, StartToken = getTok();
2903 // Lex the macro definition.
2905 // Check whether we have reached the end of the file.
2906 if (getLexer().is(AsmToken::Eof))
2907 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2909 // Otherwise, check whether we have reach the .endmacro.
2910 if (getLexer().is(AsmToken::Identifier) &&
2911 (getTok().getIdentifier() == ".endm" ||
2912 getTok().getIdentifier() == ".endmacro")) {
2913 EndToken = getTok();
2915 if (getLexer().isNot(AsmToken::EndOfStatement))
2916 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2921 // Otherwise, scan til the end of the statement.
2922 getParser().EatToEndOfStatement();
2925 if (getParser().MacroMap.lookup(Name)) {
2926 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2929 const char *BodyStart = StartToken.getLoc().getPointer();
2930 const char *BodyEnd = EndToken.getLoc().getPointer();
2931 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
2932 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
2936 /// ParseDirectiveEndMacro
2939 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2940 SMLoc DirectiveLoc) {
2941 if (getLexer().isNot(AsmToken::EndOfStatement))
2942 return TokError("unexpected token in '" + Directive + "' directive");
2944 // If we are inside a macro instantiation, terminate the current
2946 if (!getParser().ActiveMacros.empty()) {
2947 getParser().HandleMacroExit();
2951 // Otherwise, this .endmacro is a stray entry in the file; well formed
2952 // .endmacro directives are handled during the macro definition parsing.
2953 return TokError("unexpected '" + Directive + "' in file, "
2954 "no current macro definition");
2957 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
2958 getParser().CheckForValidSection();
2960 const MCExpr *Value;
2962 if (getParser().ParseExpression(Value))
2965 if (getLexer().isNot(AsmToken::EndOfStatement))
2966 return TokError("unexpected token in directive");
2968 if (DirName[1] == 's')
2969 getStreamer().EmitSLEB128Value(Value);
2971 getStreamer().EmitULEB128Value(Value);
2977 /// \brief Create an MCAsmParser instance.
2978 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
2979 MCContext &C, MCStreamer &Out,
2980 const MCAsmInfo &MAI) {
2981 return new AsmParser(SM, C, Out, MAI);