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/Twine.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.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/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.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.
48 typedef std::vector<AsmToken> MacroArgument;
49 typedef std::vector<MacroArgument> MacroArguments;
50 typedef std::pair<StringRef, MacroArgument> MacroParameter;
51 typedef std::vector<MacroParameter> MacroParameters;
56 MacroParameters Parameters;
59 Macro(StringRef N, StringRef B, const MacroParameters &P) :
60 Name(N), Body(B), Parameters(P) {}
63 /// \brief Helper class for storing information about an active macro
65 struct MacroInstantiation {
66 /// The macro being instantiated.
67 const Macro *TheMacro;
69 /// The macro instantiation with substitutions.
70 MemoryBuffer *Instantiation;
72 /// The location of the instantiation.
73 SMLoc InstantiationLoc;
75 /// The location where parsing should resume upon instantiation completion.
79 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
83 /// \brief The concrete assembly parser instance.
84 class AsmParser : public MCAsmParser {
85 friend class GenericAsmParser;
87 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
88 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
95 SourceMgr::DiagHandlerTy SavedDiagHandler;
96 void *SavedDiagContext;
97 MCAsmParserExtension *GenericParser;
98 MCAsmParserExtension *PlatformParser;
100 /// This is the current buffer index we're lexing from as managed by the
101 /// SourceMgr object.
104 AsmCond TheCondState;
105 std::vector<AsmCond> TheCondStack;
107 /// DirectiveMap - This is a table handlers for directives. Each handler is
108 /// invoked after the directive identifier is read and is responsible for
109 /// parsing and validating the rest of the directive. The handler is passed
110 /// in the directive name and the location of the directive keyword.
111 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
113 /// MacroMap - Map of currently defined macros.
114 StringMap<Macro*> MacroMap;
116 /// ActiveMacros - Stack of active macro instantiations.
117 std::vector<MacroInstantiation*> ActiveMacros;
119 /// Boolean tracking whether macro substitution is enabled.
120 unsigned MacrosEnabled : 1;
122 /// Flag tracking whether any errors have been encountered.
123 unsigned HadError : 1;
125 /// The values from the last parsed cpp hash file line comment if any.
126 StringRef CppHashFilename;
127 int64_t CppHashLineNumber;
130 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
131 unsigned AssemblerDialect;
133 /// IsDarwin - is Darwin compatibility enabled?
136 /// ParsingInlineAsm - are we parsing ms-style inline assembly?
137 bool ParsingInlineAsm;
140 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
141 const MCAsmInfo &MAI);
142 virtual ~AsmParser();
144 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
146 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
148 DirectiveHandler Handler) {
149 DirectiveMap[Directive] = std::make_pair(Object, Handler);
153 /// @name MCAsmParser Interface
156 virtual SourceMgr &getSourceManager() { return SrcMgr; }
157 virtual MCAsmLexer &getLexer() { return Lexer; }
158 virtual MCContext &getContext() { return Ctx; }
159 virtual MCStreamer &getStreamer() { return Out; }
160 virtual unsigned getAssemblerDialect() {
161 if (AssemblerDialect == ~0U)
162 return MAI.getAssemblerDialect();
164 return AssemblerDialect;
166 virtual void setAssemblerDialect(unsigned i) {
167 AssemblerDialect = i;
170 virtual bool Warning(SMLoc L, const Twine &Msg,
171 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
172 virtual bool Error(SMLoc L, const Twine &Msg,
173 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
175 virtual const AsmToken &Lex();
177 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
179 bool ParseExpression(const MCExpr *&Res);
180 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
181 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
182 virtual bool ParseAbsoluteExpression(int64_t &Res);
187 void CheckForValidSection();
189 bool ParseStatement();
190 void EatToEndOfLine();
191 bool ParseCppHashLineFilenameComment(const SMLoc &L);
193 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
194 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
195 const MacroParameters &Parameters,
196 const MacroArguments &A,
198 void HandleMacroExit();
200 void PrintMacroInstantiations();
201 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
202 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
203 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
205 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
207 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
208 bool EnterIncludeFile(const std::string &Filename);
209 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
210 /// This returns true on failure.
211 bool ProcessIncbinFile(const std::string &Filename);
213 /// \brief Reset the current lexer position to that given by \p Loc. The
214 /// current token is not set; clients should ensure Lex() is called
216 void JumpToLoc(SMLoc Loc);
218 virtual void EatToEndOfStatement();
220 bool ParseMacroArgument(MacroArgument &MA,
221 AsmToken::TokenKind &ArgumentDelimiter);
222 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
224 /// \brief Parse up to the end of statement and a return the contents from the
225 /// current token until the end of the statement; the current token on exit
226 /// will be either the EndOfStatement or EOF.
227 virtual StringRef ParseStringToEndOfStatement();
229 /// \brief Parse until the end of a statement or a comma is encountered,
230 /// return the contents from the current token up to the end or comma.
231 StringRef ParseStringToComma();
233 bool ParseAssignment(StringRef Name, bool allow_redef,
234 bool NoDeadStrip = false);
236 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
237 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
238 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
239 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
241 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
242 /// and set \p Res to the identifier contents.
243 virtual bool ParseIdentifier(StringRef &Res);
245 // Directive Parsing.
247 // ".ascii", ".asciiz", ".string"
248 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
249 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
250 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
251 bool ParseDirectiveFill(); // ".fill"
252 bool ParseDirectiveSpace(); // ".space"
253 bool ParseDirectiveZero(); // ".zero"
254 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
255 bool ParseDirectiveOrg(); // ".org"
256 // ".align{,32}", ".p2align{,w,l}"
257 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
259 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
260 /// accepts a single symbol (which should be a label or an external).
261 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
263 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
265 bool ParseDirectiveAbort(); // ".abort"
266 bool ParseDirectiveInclude(); // ".include"
267 bool ParseDirectiveIncbin(); // ".incbin"
269 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
270 // ".ifb" or ".ifnb", depending on ExpectBlank.
271 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
272 // ".ifc" or ".ifnc", depending on ExpectEqual.
273 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
274 // ".ifdef" or ".ifndef", depending on expect_defined
275 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
276 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
277 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
278 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
280 /// ParseEscapedString - Parse the current token as a string which may include
281 /// escaped characters and return the string contents.
282 bool ParseEscapedString(std::string &Data);
284 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
285 MCSymbolRefExpr::VariantKind Variant);
287 // Macro-like directives
288 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
289 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
290 raw_svector_ostream &OS);
291 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
292 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
293 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
294 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
297 /// \brief Generic implementations of directive handling, etc. which is shared
298 /// (or the default, at least) for all assembler parser.
299 class GenericAsmParser : public MCAsmParserExtension {
300 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
301 void AddDirectiveHandler(StringRef Directive) {
302 getParser().AddDirectiveHandler(this, Directive,
303 HandleDirective<GenericAsmParser, Handler>);
306 GenericAsmParser() {}
308 AsmParser &getParser() {
309 return (AsmParser&) this->MCAsmParserExtension::getParser();
312 virtual void Initialize(MCAsmParser &Parser) {
313 // Call the base implementation.
314 this->MCAsmParserExtension::Initialize(Parser);
316 // Debugging directives.
317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
320 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
323 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
325 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
327 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
329 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
331 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
332 ".cfi_def_cfa_offset");
333 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
334 ".cfi_adjust_cfa_offset");
335 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
336 ".cfi_def_cfa_register");
337 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
339 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
342 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
344 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
346 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
348 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
350 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
352 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
354 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
356 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
359 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
361 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
363 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
365 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
366 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
368 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
372 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
374 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
377 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
378 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
379 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
387 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
388 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
390 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
392 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
393 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
395 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
396 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
397 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
398 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
400 bool ParseDirectiveLEB128(StringRef, SMLoc);
407 extern MCAsmParserExtension *createDarwinAsmParser();
408 extern MCAsmParserExtension *createELFAsmParser();
409 extern MCAsmParserExtension *createCOFFAsmParser();
413 enum { DEFAULT_ADDRSPACE = 0 };
415 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
416 MCStreamer &_Out, const MCAsmInfo &_MAI)
417 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
418 GenericParser(new GenericAsmParser), PlatformParser(0),
419 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
420 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
421 // Save the old handler.
422 SavedDiagHandler = SrcMgr.getDiagHandler();
423 SavedDiagContext = SrcMgr.getDiagContext();
424 // Set our own handler which calls the saved handler.
425 SrcMgr.setDiagHandler(DiagHandler, this);
426 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
428 // Initialize the generic parser.
429 GenericParser->Initialize(*this);
431 // Initialize the platform / file format parser.
433 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
435 if (_MAI.hasMicrosoftFastStdCallMangling()) {
436 PlatformParser = createCOFFAsmParser();
437 PlatformParser->Initialize(*this);
438 } else if (_MAI.hasSubsectionsViaSymbols()) {
439 PlatformParser = createDarwinAsmParser();
440 PlatformParser->Initialize(*this);
443 PlatformParser = createELFAsmParser();
444 PlatformParser->Initialize(*this);
448 AsmParser::~AsmParser() {
449 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
451 // Destroy any macros.
452 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
453 ie = MacroMap.end(); it != ie; ++it)
454 delete it->getValue();
456 delete PlatformParser;
457 delete GenericParser;
460 void AsmParser::PrintMacroInstantiations() {
461 // Print the active macro instantiation stack.
462 for (std::vector<MacroInstantiation*>::const_reverse_iterator
463 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
464 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
465 "while in macro instantiation");
468 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
469 if (FatalAssemblerWarnings)
470 return Error(L, Msg, Ranges);
471 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
472 PrintMacroInstantiations();
476 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
478 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
479 PrintMacroInstantiations();
483 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
484 std::string IncludedFile;
485 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
496 /// Process the specified .incbin file by seaching for it in the include paths
497 /// then just emitting the byte contents of the file to the streamer. This
498 /// returns true on failure.
499 bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
500 std::string IncludedFile;
501 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
505 // Pick up the bytes from the file and emit them.
506 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
511 void AsmParser::JumpToLoc(SMLoc Loc) {
512 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
513 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
516 const AsmToken &AsmParser::Lex() {
517 const AsmToken *tok = &Lexer.Lex();
519 if (tok->is(AsmToken::Eof)) {
520 // If this is the end of an included file, pop the parent file off the
522 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
523 if (ParentIncludeLoc != SMLoc()) {
524 JumpToLoc(ParentIncludeLoc);
529 if (tok->is(AsmToken::Error))
530 Error(Lexer.getErrLoc(), Lexer.getErr());
535 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
536 // Create the initial section, if requested.
537 if (!NoInitialTextSection)
544 AsmCond StartingCondState = TheCondState;
546 // If we are generating dwarf for assembly source files save the initial text
547 // section and generate a .file directive.
548 if (getContext().getGenDwarfForAssembly()) {
549 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
550 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
551 getStreamer().EmitLabel(SectionStartSym);
552 getContext().setGenDwarfSectionStartSym(SectionStartSym);
553 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
554 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
557 // While we have input, parse each statement.
558 while (Lexer.isNot(AsmToken::Eof)) {
559 if (!ParseStatement()) continue;
561 // We had an error, validate that one was emitted and recover by skipping to
563 assert(HadError && "Parse statement returned an error, but none emitted!");
564 EatToEndOfStatement();
567 if (TheCondState.TheCond != StartingCondState.TheCond ||
568 TheCondState.Ignore != StartingCondState.Ignore)
569 return TokError("unmatched .ifs or .elses");
571 // Check to see there are no empty DwarfFile slots.
572 const std::vector<MCDwarfFile *> &MCDwarfFiles =
573 getContext().getMCDwarfFiles();
574 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
575 if (!MCDwarfFiles[i])
576 TokError("unassigned file number: " + Twine(i) + " for .file directives");
579 // Check to see that all assembler local symbols were actually defined.
580 // Targets that don't do subsections via symbols may not want this, though,
581 // so conservatively exclude them. Only do this if we're finalizing, though,
582 // as otherwise we won't necessarilly have seen everything yet.
583 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
584 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
585 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
588 MCSymbol *Sym = i->getValue();
589 // Variable symbols may not be marked as defined, so check those
590 // explicitly. If we know it's a variable, we have a definition for
591 // the purposes of this check.
592 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
593 // FIXME: We would really like to refer back to where the symbol was
594 // first referenced for a source location. We need to add something
595 // to track that. Currently, we just point to the end of the file.
596 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
597 "assembler local symbol '" + Sym->getName() +
603 // Finalize the output stream if there are no errors and if the client wants
605 if (!HadError && !NoFinalize)
611 void AsmParser::CheckForValidSection() {
612 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
613 TokError("expected section directive before assembly directive");
614 Out.SwitchSection(Ctx.getMachOSection(
616 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
617 0, SectionKind::getText()));
621 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
622 void AsmParser::EatToEndOfStatement() {
623 while (Lexer.isNot(AsmToken::EndOfStatement) &&
624 Lexer.isNot(AsmToken::Eof))
628 if (Lexer.is(AsmToken::EndOfStatement))
632 StringRef AsmParser::ParseStringToEndOfStatement() {
633 const char *Start = getTok().getLoc().getPointer();
635 while (Lexer.isNot(AsmToken::EndOfStatement) &&
636 Lexer.isNot(AsmToken::Eof))
639 const char *End = getTok().getLoc().getPointer();
640 return StringRef(Start, End - Start);
643 StringRef AsmParser::ParseStringToComma() {
644 const char *Start = getTok().getLoc().getPointer();
646 while (Lexer.isNot(AsmToken::EndOfStatement) &&
647 Lexer.isNot(AsmToken::Comma) &&
648 Lexer.isNot(AsmToken::Eof))
651 const char *End = getTok().getLoc().getPointer();
652 return StringRef(Start, End - Start);
655 /// ParseParenExpr - Parse a paren expression and return it.
656 /// NOTE: This assumes the leading '(' has already been consumed.
658 /// parenexpr ::= expr)
660 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
661 if (ParseExpression(Res)) return true;
662 if (Lexer.isNot(AsmToken::RParen))
663 return TokError("expected ')' in parentheses expression");
664 EndLoc = Lexer.getLoc();
669 /// ParseBracketExpr - Parse a bracket expression and return it.
670 /// NOTE: This assumes the leading '[' has already been consumed.
672 /// bracketexpr ::= expr]
674 bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
675 if (ParseExpression(Res)) return true;
676 if (Lexer.isNot(AsmToken::RBrac))
677 return TokError("expected ']' in brackets expression");
678 EndLoc = Lexer.getLoc();
683 /// ParsePrimaryExpr - Parse a primary expression and return it.
684 /// primaryexpr ::= (parenexpr
685 /// primaryexpr ::= symbol
686 /// primaryexpr ::= number
687 /// primaryexpr ::= '.'
688 /// primaryexpr ::= ~,+,- primaryexpr
689 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
690 switch (Lexer.getKind()) {
692 return TokError("unknown token in expression");
693 // If we have an error assume that we've already handled it.
694 case AsmToken::Error:
696 case AsmToken::Exclaim:
697 Lex(); // Eat the operator.
698 if (ParsePrimaryExpr(Res, EndLoc))
700 Res = MCUnaryExpr::CreateLNot(Res, getContext());
702 case AsmToken::Dollar:
703 case AsmToken::String:
704 case AsmToken::Identifier: {
705 EndLoc = Lexer.getLoc();
707 StringRef Identifier;
708 if (ParseIdentifier(Identifier))
711 // This is a symbol reference.
712 std::pair<StringRef, StringRef> Split = Identifier.split('@');
713 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
715 // Lookup the symbol variant if used.
716 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
717 if (Split.first.size() != Identifier.size()) {
718 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
719 if (Variant == MCSymbolRefExpr::VK_Invalid) {
720 Variant = MCSymbolRefExpr::VK_None;
721 return TokError("invalid variant '" + Split.second + "'");
725 // If this is an absolute variable reference, substitute it now to preserve
726 // semantics in the face of reassignment.
727 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
729 return Error(EndLoc, "unexpected modifier on variable reference");
731 Res = Sym->getVariableValue();
735 // Otherwise create a symbol ref.
736 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
739 case AsmToken::Integer: {
740 SMLoc Loc = getTok().getLoc();
741 int64_t IntVal = getTok().getIntVal();
742 Res = MCConstantExpr::Create(IntVal, getContext());
743 EndLoc = Lexer.getLoc();
745 // Look for 'b' or 'f' following an Integer as a directional label
746 if (Lexer.getKind() == AsmToken::Identifier) {
747 StringRef IDVal = getTok().getString();
748 if (IDVal == "f" || IDVal == "b"){
749 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
750 IDVal == "f" ? 1 : 0);
751 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
753 if (IDVal == "b" && Sym->isUndefined())
754 return Error(Loc, "invalid reference to undefined symbol");
755 EndLoc = Lexer.getLoc();
756 Lex(); // Eat identifier.
761 case AsmToken::Real: {
762 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
763 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
764 Res = MCConstantExpr::Create(IntVal, getContext());
768 case AsmToken::Dot: {
769 // This is a '.' reference, which references the current PC. Emit a
770 // temporary label to the streamer and refer to it.
771 MCSymbol *Sym = Ctx.CreateTempSymbol();
773 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
774 EndLoc = Lexer.getLoc();
775 Lex(); // Eat identifier.
778 case AsmToken::LParen:
779 Lex(); // Eat the '('.
780 return ParseParenExpr(Res, EndLoc);
781 case AsmToken::LBrac:
782 if (!PlatformParser->HasBracketExpressions())
783 return TokError("brackets expression not supported on this target");
784 Lex(); // Eat the '['.
785 return ParseBracketExpr(Res, EndLoc);
786 case AsmToken::Minus:
787 Lex(); // Eat the operator.
788 if (ParsePrimaryExpr(Res, EndLoc))
790 Res = MCUnaryExpr::CreateMinus(Res, getContext());
793 Lex(); // Eat the operator.
794 if (ParsePrimaryExpr(Res, EndLoc))
796 Res = MCUnaryExpr::CreatePlus(Res, getContext());
798 case AsmToken::Tilde:
799 Lex(); // Eat the operator.
800 if (ParsePrimaryExpr(Res, EndLoc))
802 Res = MCUnaryExpr::CreateNot(Res, getContext());
807 bool AsmParser::ParseExpression(const MCExpr *&Res) {
809 return ParseExpression(Res, EndLoc);
813 AsmParser::ApplyModifierToExpr(const MCExpr *E,
814 MCSymbolRefExpr::VariantKind Variant) {
815 // Recurse over the given expression, rebuilding it to apply the given variant
816 // if there is exactly one symbol.
817 switch (E->getKind()) {
819 case MCExpr::Constant:
822 case MCExpr::SymbolRef: {
823 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
825 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
826 TokError("invalid variant on expression '" +
827 getTok().getIdentifier() + "' (already modified)");
831 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
834 case MCExpr::Unary: {
835 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
836 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
839 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
842 case MCExpr::Binary: {
843 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
844 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
845 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
850 if (!LHS) LHS = BE->getLHS();
851 if (!RHS) RHS = BE->getRHS();
853 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
857 llvm_unreachable("Invalid expression kind!");
860 /// ParseExpression - Parse an expression and return it.
862 /// expr ::= expr &&,|| expr -> lowest.
863 /// expr ::= expr |,^,&,! expr
864 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
865 /// expr ::= expr <<,>> expr
866 /// expr ::= expr +,- expr
867 /// expr ::= expr *,/,% expr -> highest.
868 /// expr ::= primaryexpr
870 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
871 // Parse the expression.
873 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
876 // As a special case, we support 'a op b @ modifier' by rewriting the
877 // expression to include the modifier. This is inefficient, but in general we
878 // expect users to use 'a@modifier op b'.
879 if (Lexer.getKind() == AsmToken::At) {
882 if (Lexer.isNot(AsmToken::Identifier))
883 return TokError("unexpected symbol modifier following '@'");
885 MCSymbolRefExpr::VariantKind Variant =
886 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
887 if (Variant == MCSymbolRefExpr::VK_Invalid)
888 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
890 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
892 return TokError("invalid modifier '" + getTok().getIdentifier() +
893 "' (no symbols present)");
900 // Try to constant fold it up front, if possible.
902 if (Res->EvaluateAsAbsolute(Value))
903 Res = MCConstantExpr::Create(Value, getContext());
908 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
910 return ParseParenExpr(Res, EndLoc) ||
911 ParseBinOpRHS(1, Res, EndLoc);
914 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
917 SMLoc StartLoc = Lexer.getLoc();
918 if (ParseExpression(Expr))
921 if (!Expr->EvaluateAsAbsolute(Res))
922 return Error(StartLoc, "expected absolute expression");
927 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
928 MCBinaryExpr::Opcode &Kind) {
931 return 0; // not a binop.
933 // Lowest Precedence: &&, ||
934 case AsmToken::AmpAmp:
935 Kind = MCBinaryExpr::LAnd;
937 case AsmToken::PipePipe:
938 Kind = MCBinaryExpr::LOr;
942 // Low Precedence: |, &, ^
944 // FIXME: gas seems to support '!' as an infix operator?
946 Kind = MCBinaryExpr::Or;
948 case AsmToken::Caret:
949 Kind = MCBinaryExpr::Xor;
952 Kind = MCBinaryExpr::And;
955 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
956 case AsmToken::EqualEqual:
957 Kind = MCBinaryExpr::EQ;
959 case AsmToken::ExclaimEqual:
960 case AsmToken::LessGreater:
961 Kind = MCBinaryExpr::NE;
964 Kind = MCBinaryExpr::LT;
966 case AsmToken::LessEqual:
967 Kind = MCBinaryExpr::LTE;
969 case AsmToken::Greater:
970 Kind = MCBinaryExpr::GT;
972 case AsmToken::GreaterEqual:
973 Kind = MCBinaryExpr::GTE;
976 // Intermediate Precedence: <<, >>
977 case AsmToken::LessLess:
978 Kind = MCBinaryExpr::Shl;
980 case AsmToken::GreaterGreater:
981 Kind = MCBinaryExpr::Shr;
984 // High Intermediate Precedence: +, -
986 Kind = MCBinaryExpr::Add;
988 case AsmToken::Minus:
989 Kind = MCBinaryExpr::Sub;
992 // Highest Precedence: *, /, %
994 Kind = MCBinaryExpr::Mul;
996 case AsmToken::Slash:
997 Kind = MCBinaryExpr::Div;
999 case AsmToken::Percent:
1000 Kind = MCBinaryExpr::Mod;
1006 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1007 /// Res contains the LHS of the expression on input.
1008 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1011 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1012 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1014 // If the next token is lower precedence than we are allowed to eat, return
1015 // successfully with what we ate already.
1016 if (TokPrec < Precedence)
1021 // Eat the next primary expression.
1023 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
1025 // If BinOp binds less tightly with RHS than the operator after RHS, let
1026 // the pending operator take RHS as its LHS.
1027 MCBinaryExpr::Opcode Dummy;
1028 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1029 if (TokPrec < NextTokPrec) {
1030 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
1033 // Merge LHS and RHS according to operator.
1034 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1039 /// ::= EndOfStatement
1040 /// ::= Label* Directive ...Operands... EndOfStatement
1041 /// ::= Label* Identifier OperandList* EndOfStatement
1042 bool AsmParser::ParseStatement() {
1043 if (Lexer.is(AsmToken::EndOfStatement)) {
1049 // Statements always start with an identifier or are a full line comment.
1050 AsmToken ID = getTok();
1051 SMLoc IDLoc = ID.getLoc();
1053 int64_t LocalLabelVal = -1;
1054 // A full line comment is a '#' as the first token.
1055 if (Lexer.is(AsmToken::Hash))
1056 return ParseCppHashLineFilenameComment(IDLoc);
1058 // Allow an integer followed by a ':' as a directional local label.
1059 if (Lexer.is(AsmToken::Integer)) {
1060 LocalLabelVal = getTok().getIntVal();
1061 if (LocalLabelVal < 0) {
1062 if (!TheCondState.Ignore)
1063 return TokError("unexpected token at start of statement");
1067 IDVal = getTok().getString();
1068 Lex(); // Consume the integer token to be used as an identifier token.
1069 if (Lexer.getKind() != AsmToken::Colon) {
1070 if (!TheCondState.Ignore)
1071 return TokError("unexpected token at start of statement");
1075 } else if (Lexer.is(AsmToken::Dot)) {
1076 // Treat '.' as a valid identifier in this context.
1080 } else if (ParseIdentifier(IDVal)) {
1081 if (!TheCondState.Ignore)
1082 return TokError("unexpected token at start of statement");
1087 // Handle conditional assembly here before checking for skipping. We
1088 // have to do this so that .endif isn't skipped in a ".if 0" block for
1091 return ParseDirectiveIf(IDLoc);
1092 if (IDVal == ".ifb")
1093 return ParseDirectiveIfb(IDLoc, true);
1094 if (IDVal == ".ifnb")
1095 return ParseDirectiveIfb(IDLoc, false);
1096 if (IDVal == ".ifc")
1097 return ParseDirectiveIfc(IDLoc, true);
1098 if (IDVal == ".ifnc")
1099 return ParseDirectiveIfc(IDLoc, false);
1100 if (IDVal == ".ifdef")
1101 return ParseDirectiveIfdef(IDLoc, true);
1102 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1103 return ParseDirectiveIfdef(IDLoc, false);
1104 if (IDVal == ".elseif")
1105 return ParseDirectiveElseIf(IDLoc);
1106 if (IDVal == ".else")
1107 return ParseDirectiveElse(IDLoc);
1108 if (IDVal == ".endif")
1109 return ParseDirectiveEndIf(IDLoc);
1111 // If we are in a ".if 0" block, ignore this statement.
1112 if (TheCondState.Ignore) {
1113 EatToEndOfStatement();
1117 // FIXME: Recurse on local labels?
1119 // See what kind of statement we have.
1120 switch (Lexer.getKind()) {
1121 case AsmToken::Colon: {
1122 CheckForValidSection();
1124 // identifier ':' -> Label.
1127 // Diagnose attempt to use '.' as a label.
1129 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1131 // Diagnose attempt to use a variable as a label.
1133 // FIXME: Diagnostics. Note the location of the definition as a label.
1134 // FIXME: This doesn't diagnose assignment to a symbol which has been
1135 // implicitly marked as external.
1137 if (LocalLabelVal == -1)
1138 Sym = getContext().GetOrCreateSymbol(IDVal);
1140 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1141 if (!Sym->isUndefined() || Sym->isVariable())
1142 return Error(IDLoc, "invalid symbol redefinition");
1147 // If we are generating dwarf for assembly source files then gather the
1148 // info to make a dwarf label entry for this label if needed.
1149 if (getContext().getGenDwarfForAssembly())
1150 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1153 // Consume any end of statement token, if present, to avoid spurious
1154 // AddBlankLine calls().
1155 if (Lexer.is(AsmToken::EndOfStatement)) {
1157 if (Lexer.is(AsmToken::Eof))
1161 return ParseStatement();
1164 case AsmToken::Equal:
1165 // identifier '=' ... -> assignment statement
1168 return ParseAssignment(IDVal, true);
1170 default: // Normal instruction or directive.
1174 // If macros are enabled, check to see if this is a macro instantiation.
1176 if (const Macro *M = MacroMap.lookup(IDVal))
1177 return HandleMacroEntry(IDVal, IDLoc, M);
1179 // Otherwise, we have a normal instruction or directive.
1180 if (IDVal[0] == '.' && IDVal != ".") {
1182 // Target hook for parsing target specific directives.
1183 if (!getTargetParser().ParseDirective(ID))
1186 // Assembler features
1187 if (IDVal == ".set" || IDVal == ".equ")
1188 return ParseDirectiveSet(IDVal, true);
1189 if (IDVal == ".equiv")
1190 return ParseDirectiveSet(IDVal, false);
1194 if (IDVal == ".ascii")
1195 return ParseDirectiveAscii(IDVal, false);
1196 if (IDVal == ".asciz" || IDVal == ".string")
1197 return ParseDirectiveAscii(IDVal, true);
1199 if (IDVal == ".byte")
1200 return ParseDirectiveValue(1);
1201 if (IDVal == ".short")
1202 return ParseDirectiveValue(2);
1203 if (IDVal == ".value")
1204 return ParseDirectiveValue(2);
1205 if (IDVal == ".2byte")
1206 return ParseDirectiveValue(2);
1207 if (IDVal == ".long")
1208 return ParseDirectiveValue(4);
1209 if (IDVal == ".int")
1210 return ParseDirectiveValue(4);
1211 if (IDVal == ".4byte")
1212 return ParseDirectiveValue(4);
1213 if (IDVal == ".quad")
1214 return ParseDirectiveValue(8);
1215 if (IDVal == ".8byte")
1216 return ParseDirectiveValue(8);
1217 if (IDVal == ".single" || IDVal == ".float")
1218 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1219 if (IDVal == ".double")
1220 return ParseDirectiveRealValue(APFloat::IEEEdouble);
1222 if (IDVal == ".align") {
1223 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1224 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1226 if (IDVal == ".align32") {
1227 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1228 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1230 if (IDVal == ".balign")
1231 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1232 if (IDVal == ".balignw")
1233 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1234 if (IDVal == ".balignl")
1235 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1236 if (IDVal == ".p2align")
1237 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1238 if (IDVal == ".p2alignw")
1239 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1240 if (IDVal == ".p2alignl")
1241 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1243 if (IDVal == ".org")
1244 return ParseDirectiveOrg();
1246 if (IDVal == ".fill")
1247 return ParseDirectiveFill();
1248 if (IDVal == ".space" || IDVal == ".skip")
1249 return ParseDirectiveSpace();
1250 if (IDVal == ".zero")
1251 return ParseDirectiveZero();
1253 // Symbol attribute directives
1255 if (IDVal == ".extern") {
1256 EatToEndOfStatement(); // .extern is the default, ignore it.
1259 if (IDVal == ".globl" || IDVal == ".global")
1260 return ParseDirectiveSymbolAttribute(MCSA_Global);
1261 if (IDVal == ".indirect_symbol")
1262 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
1263 if (IDVal == ".lazy_reference")
1264 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
1265 if (IDVal == ".no_dead_strip")
1266 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1267 if (IDVal == ".symbol_resolver")
1268 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1269 if (IDVal == ".private_extern")
1270 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1271 if (IDVal == ".reference")
1272 return ParseDirectiveSymbolAttribute(MCSA_Reference);
1273 if (IDVal == ".weak_definition")
1274 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1275 if (IDVal == ".weak_reference")
1276 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
1277 if (IDVal == ".weak_def_can_be_hidden")
1278 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1280 if (IDVal == ".comm" || IDVal == ".common")
1281 return ParseDirectiveComm(/*IsLocal=*/false);
1282 if (IDVal == ".lcomm")
1283 return ParseDirectiveComm(/*IsLocal=*/true);
1285 if (IDVal == ".abort")
1286 return ParseDirectiveAbort();
1287 if (IDVal == ".include")
1288 return ParseDirectiveInclude();
1289 if (IDVal == ".incbin")
1290 return ParseDirectiveIncbin();
1292 if (IDVal == ".code16" || IDVal == ".code16gcc")
1293 return TokError(Twine(IDVal) + " not supported yet");
1295 // Macro-like directives
1296 if (IDVal == ".rept")
1297 return ParseDirectiveRept(IDLoc);
1298 if (IDVal == ".irp")
1299 return ParseDirectiveIrp(IDLoc);
1300 if (IDVal == ".irpc")
1301 return ParseDirectiveIrpc(IDLoc);
1302 if (IDVal == ".endr")
1303 return ParseDirectiveEndr(IDLoc);
1305 // Look up the handler in the handler table.
1306 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1307 DirectiveMap.lookup(IDVal);
1309 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1312 return Error(IDLoc, "unknown directive");
1315 CheckForValidSection();
1317 // Canonicalize the opcode to lower case.
1318 SmallString<128> Opcode;
1319 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1320 Opcode.push_back(tolower(IDVal[i]));
1322 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
1323 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
1326 // Dump the parsed representation, if requested.
1327 if (getShowParsedOperands()) {
1328 SmallString<256> Str;
1329 raw_svector_ostream OS(Str);
1330 OS << "parsed instruction: [";
1331 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1334 ParsedOperands[i]->print(OS);
1338 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1341 // If we are generating dwarf for assembly source files and the current
1342 // section is the initial text section then generate a .loc directive for
1344 if (!HadError && getContext().getGenDwarfForAssembly() &&
1345 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1346 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1347 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1348 0, DWARF2_LINE_DEFAULT_IS_STMT ?
1349 DWARF2_FLAG_IS_STMT : 0, 0, 0,
1353 // If parsing succeeded, match the instruction.
1357 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
1363 // Free any parsed operands.
1364 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1365 delete ParsedOperands[i];
1367 // Don't skip the rest of the line, the instruction parser is responsible for
1372 /// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1373 /// since they may not be able to be tokenized to get to the end of line token.
1374 void AsmParser::EatToEndOfLine() {
1375 if (!Lexer.is(AsmToken::EndOfStatement))
1376 Lexer.LexUntilEndOfLine();
1381 /// ParseCppHashLineFilenameComment as this:
1382 /// ::= # number "filename"
1383 /// or just as a full line comment if it doesn't have a number and a string.
1384 bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1385 Lex(); // Eat the hash token.
1387 if (getLexer().isNot(AsmToken::Integer)) {
1388 // Consume the line since in cases it is not a well-formed line directive,
1389 // as if were simply a full line comment.
1394 int64_t LineNumber = getTok().getIntVal();
1397 if (getLexer().isNot(AsmToken::String)) {
1402 StringRef Filename = getTok().getString();
1403 // Get rid of the enclosing quotes.
1404 Filename = Filename.substr(1, Filename.size()-2);
1406 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1408 CppHashFilename = Filename;
1409 CppHashLineNumber = LineNumber;
1411 // Ignore any trailing characters, they're just comment.
1416 /// DiagHandler - will use the last parsed cpp hash line filename comment
1417 /// for the Filename and LineNo if any in the diagnostic.
1418 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1419 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1420 raw_ostream &OS = errs();
1422 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1423 const SMLoc &DiagLoc = Diag.getLoc();
1424 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1425 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1427 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1428 // before printing the message.
1429 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1430 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1431 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1432 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1435 // If we have not parsed a cpp hash line filename comment or the source
1436 // manager changed or buffer changed (like in a nested include) then just
1437 // print the normal diagnostic using its Filename and LineNo.
1438 if (!Parser->CppHashLineNumber ||
1439 &DiagSrcMgr != &Parser->SrcMgr ||
1440 DiagBuf != CppHashBuf) {
1441 if (Parser->SavedDiagHandler)
1442 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1448 // Use the CppHashFilename and calculate a line number based on the
1449 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1451 const std::string Filename = Parser->CppHashFilename;
1453 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1454 int CppHashLocLineNo =
1455 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1456 int LineNo = Parser->CppHashLineNumber - 1 +
1457 (DiagLocLineNo - CppHashLocLineNo);
1459 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1460 Filename, LineNo, Diag.getColumnNo(),
1461 Diag.getKind(), Diag.getMessage(),
1462 Diag.getLineContents(), Diag.getRanges());
1464 if (Parser->SavedDiagHandler)
1465 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1467 NewDiag.print(0, OS);
1470 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1471 // difference being that that function accepts '@' as part of identifiers and
1472 // we can't do that. AsmLexer.cpp should probably be changed to handle
1473 // '@' as a special case when needed.
1474 static bool isIdentifierChar(char c) {
1475 return isalnum(c) || c == '_' || c == '$' || c == '.';
1478 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1479 const MacroParameters &Parameters,
1480 const MacroArguments &A,
1482 unsigned NParameters = Parameters.size();
1483 if (NParameters != 0 && NParameters != A.size())
1484 return Error(L, "Wrong number of arguments");
1486 // A macro without parameters is handled differently on Darwin:
1487 // gas accepts no arguments and does no substitutions
1488 while (!Body.empty()) {
1489 // Scan for the next substitution.
1490 std::size_t End = Body.size(), Pos = 0;
1491 for (; Pos != End; ++Pos) {
1492 // Check for a substitution or escape.
1494 // This macro has no parameters, look for $0, $1, etc.
1495 if (Body[Pos] != '$' || Pos + 1 == End)
1498 char Next = Body[Pos + 1];
1499 if (Next == '$' || Next == 'n' || isdigit(Next))
1502 // This macro has parameters, look for \foo, \bar, etc.
1503 if (Body[Pos] == '\\' && Pos + 1 != End)
1509 OS << Body.slice(0, Pos);
1511 // Check if we reached the end.
1516 switch (Body[Pos+1]) {
1522 // $n => number of arguments
1527 // $[0-9] => argument
1529 // Missing arguments are ignored.
1530 unsigned Index = Body[Pos+1] - '0';
1531 if (Index >= A.size())
1534 // Otherwise substitute with the token values, with spaces eliminated.
1535 for (MacroArgument::const_iterator it = A[Index].begin(),
1536 ie = A[Index].end(); it != ie; ++it)
1537 OS << it->getString();
1543 unsigned I = Pos + 1;
1544 while (isIdentifierChar(Body[I]) && I + 1 != End)
1547 const char *Begin = Body.data() + Pos +1;
1548 StringRef Argument(Begin, I - (Pos +1));
1550 for (; Index < NParameters; ++Index)
1551 if (Parameters[Index].first == Argument)
1554 if (Index == NParameters) {
1555 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1558 OS << '\\' << Argument;
1562 for (MacroArgument::const_iterator it = A[Index].begin(),
1563 ie = A[Index].end(); it != ie; ++it)
1564 if (it->getKind() == AsmToken::String)
1565 OS << it->getStringContents();
1567 OS << it->getString();
1569 Pos += 1 + Argument.size();
1572 // Update the scan point.
1573 Body = Body.substr(Pos);
1579 MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1581 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1585 static bool IsOperator(AsmToken::TokenKind kind)
1591 case AsmToken::Plus:
1592 case AsmToken::Minus:
1593 case AsmToken::Tilde:
1594 case AsmToken::Slash:
1595 case AsmToken::Star:
1597 case AsmToken::Equal:
1598 case AsmToken::EqualEqual:
1599 case AsmToken::Pipe:
1600 case AsmToken::PipePipe:
1601 case AsmToken::Caret:
1603 case AsmToken::AmpAmp:
1604 case AsmToken::Exclaim:
1605 case AsmToken::ExclaimEqual:
1606 case AsmToken::Percent:
1607 case AsmToken::Less:
1608 case AsmToken::LessEqual:
1609 case AsmToken::LessLess:
1610 case AsmToken::LessGreater:
1611 case AsmToken::Greater:
1612 case AsmToken::GreaterEqual:
1613 case AsmToken::GreaterGreater:
1618 /// ParseMacroArgument - Extract AsmTokens for a macro argument.
1619 /// This is used for both default macro parameter values and the
1620 /// arguments in macro invocations
1621 bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1622 AsmToken::TokenKind &ArgumentDelimiter) {
1623 unsigned ParenLevel = 0;
1624 unsigned AddTokens = 0;
1626 // gas accepts arguments separated by whitespace, except on Darwin
1628 Lexer.setSkipSpace(false);
1631 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1632 Lexer.setSkipSpace(true);
1633 return TokError("unexpected token in macro instantiation");
1636 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1637 // Spaces and commas cannot be mixed to delimit parameters
1638 if (ArgumentDelimiter == AsmToken::Eof)
1639 ArgumentDelimiter = AsmToken::Comma;
1640 else if (ArgumentDelimiter != AsmToken::Comma) {
1641 Lexer.setSkipSpace(true);
1642 return TokError("expected ' ' for macro argument separator");
1647 if (Lexer.is(AsmToken::Space)) {
1648 Lex(); // Eat spaces
1650 // Spaces can delimit parameters, but could also be part an expression.
1651 // If the token after a space is an operator, add the token and the next
1652 // one into this argument
1653 if (ArgumentDelimiter == AsmToken::Space ||
1654 ArgumentDelimiter == AsmToken::Eof) {
1655 if (IsOperator(Lexer.getKind())) {
1656 // Check to see whether the token is used as an operator,
1657 // or part of an identifier
1658 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1659 if (*NextChar == ' ')
1663 if (!AddTokens && ParenLevel == 0) {
1664 if (ArgumentDelimiter == AsmToken::Eof &&
1665 !IsOperator(Lexer.getKind()))
1666 ArgumentDelimiter = AsmToken::Space;
1672 // HandleMacroEntry relies on not advancing the lexer here
1673 // to be able to fill in the remaining default parameter values
1674 if (Lexer.is(AsmToken::EndOfStatement))
1677 // Adjust the current parentheses level.
1678 if (Lexer.is(AsmToken::LParen))
1680 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1683 // Append the token to the current argument list.
1684 MA.push_back(getTok());
1690 Lexer.setSkipSpace(true);
1691 if (ParenLevel != 0)
1692 return TokError("unbalanced parentheses in macro argument");
1696 // Parse the macro instantiation arguments.
1697 bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
1698 const unsigned NParameters = M ? M->Parameters.size() : 0;
1699 // Argument delimiter is initially unknown. It will be set by
1700 // ParseMacroArgument()
1701 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
1703 // Parse two kinds of macro invocations:
1704 // - macros defined without any parameters accept an arbitrary number of them
1705 // - macros defined with parameters accept at most that many of them
1706 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1710 if (ParseMacroArgument(MA, ArgumentDelimiter))
1713 if (!MA.empty() || !NParameters)
1715 else if (NParameters) {
1716 if (!M->Parameters[Parameter].second.empty())
1717 A.push_back(M->Parameters[Parameter].second);
1720 // At the end of the statement, fill in remaining arguments that have
1721 // default values. If there aren't any, then the next argument is
1722 // required but missing
1723 if (Lexer.is(AsmToken::EndOfStatement)) {
1724 if (NParameters && Parameter < NParameters - 1) {
1725 if (M->Parameters[Parameter + 1].second.empty())
1726 return TokError("macro argument '" +
1727 Twine(M->Parameters[Parameter + 1].first) +
1735 if (Lexer.is(AsmToken::Comma))
1738 return TokError("Too many arguments");
1741 bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1743 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1744 // this, although we should protect against infinite loops.
1745 if (ActiveMacros.size() == 20)
1746 return TokError("macros cannot be nested more than 20 levels deep");
1749 if (ParseMacroArguments(M, A))
1752 // Remove any trailing empty arguments. Do this after-the-fact as we have
1753 // to keep empty arguments in the middle of the list or positionality
1754 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
1755 while (!A.empty() && A.back().empty())
1758 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1759 // to hold the macro body with substitutions.
1760 SmallString<256> Buf;
1761 StringRef Body = M->Body;
1762 raw_svector_ostream OS(Buf);
1764 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
1767 // We include the .endmacro in the buffer as our queue to exit the macro
1769 OS << ".endmacro\n";
1771 MemoryBuffer *Instantiation =
1772 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
1774 // Create the macro instantiation object and add to the current macro
1775 // instantiation stack.
1776 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
1779 ActiveMacros.push_back(MI);
1781 // Jump to the macro instantiation and prime the lexer.
1782 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1783 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1789 void AsmParser::HandleMacroExit() {
1790 // Jump to the EndOfStatement we should return to, and consume it.
1791 JumpToLoc(ActiveMacros.back()->ExitLoc);
1794 // Pop the instantiation entry.
1795 delete ActiveMacros.back();
1796 ActiveMacros.pop_back();
1799 static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
1800 switch (Value->getKind()) {
1801 case MCExpr::Binary: {
1802 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1803 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
1806 case MCExpr::Target:
1807 case MCExpr::Constant:
1809 case MCExpr::SymbolRef: {
1810 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
1812 return IsUsedIn(Sym, S.getVariableValue());
1816 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1819 llvm_unreachable("Unknown expr kind!");
1822 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1824 // FIXME: Use better location, we should use proper tokens.
1825 SMLoc EqualLoc = Lexer.getLoc();
1827 const MCExpr *Value;
1828 if (ParseExpression(Value))
1831 // Note: we don't count b as used in "a = b". This is to allow
1835 if (Lexer.isNot(AsmToken::EndOfStatement))
1836 return TokError("unexpected token in assignment");
1838 // Error on assignment to '.'.
1840 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1841 "(use '.space' or '.org').)"));
1844 // Eat the end of statement marker.
1847 // Validate that the LHS is allowed to be a variable (either it has not been
1848 // used as a symbol, or it is an absolute symbol).
1849 MCSymbol *Sym = getContext().LookupSymbol(Name);
1851 // Diagnose assignment to a label.
1853 // FIXME: Diagnostics. Note the location of the definition as a label.
1854 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
1855 if (IsUsedIn(Sym, Value))
1856 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1857 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
1858 ; // Allow redefinitions of undefined symbols only used in directives.
1859 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1860 ; // Allow redefinitions of variables that haven't yet been used.
1861 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
1862 return Error(EqualLoc, "redefinition of '" + Name + "'");
1863 else if (!Sym->isVariable())
1864 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
1865 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
1866 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1869 // Don't count these checks as uses.
1870 Sym->setUsed(false);
1872 Sym = getContext().GetOrCreateSymbol(Name);
1874 // FIXME: Handle '.'.
1876 // Do the assignment.
1877 Out.EmitAssignment(Sym, Value);
1879 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1885 /// ParseIdentifier:
1888 bool AsmParser::ParseIdentifier(StringRef &Res) {
1889 // The assembler has relaxed rules for accepting identifiers, in particular we
1890 // allow things like '.globl $foo', which would normally be separate
1891 // tokens. At this level, we have already lexed so we cannot (currently)
1892 // handle this as a context dependent token, instead we detect adjacent tokens
1893 // and return the combined identifier.
1894 if (Lexer.is(AsmToken::Dollar)) {
1895 SMLoc DollarLoc = getLexer().getLoc();
1897 // Consume the dollar sign, and check for a following identifier.
1899 if (Lexer.isNot(AsmToken::Identifier))
1902 // We have a '$' followed by an identifier, make sure they are adjacent.
1903 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1906 // Construct the joined identifier and consume the token.
1907 Res = StringRef(DollarLoc.getPointer(),
1908 getTok().getIdentifier().size() + 1);
1913 if (Lexer.isNot(AsmToken::Identifier) &&
1914 Lexer.isNot(AsmToken::String))
1917 Res = getTok().getIdentifier();
1919 Lex(); // Consume the identifier token.
1924 /// ParseDirectiveSet:
1925 /// ::= .equ identifier ',' expression
1926 /// ::= .equiv identifier ',' expression
1927 /// ::= .set identifier ',' expression
1928 bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
1931 if (ParseIdentifier(Name))
1932 return TokError("expected identifier after '" + Twine(IDVal) + "'");
1934 if (getLexer().isNot(AsmToken::Comma))
1935 return TokError("unexpected token in '" + Twine(IDVal) + "'");
1938 return ParseAssignment(Name, allow_redef, true);
1941 bool AsmParser::ParseEscapedString(std::string &Data) {
1942 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
1945 StringRef Str = getTok().getStringContents();
1946 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1947 if (Str[i] != '\\') {
1952 // Recognize escaped characters. Note that this escape semantics currently
1953 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1956 return TokError("unexpected backslash at end of string");
1958 // Recognize octal sequences.
1959 if ((unsigned) (Str[i] - '0') <= 7) {
1960 // Consume up to three octal characters.
1961 unsigned Value = Str[i] - '0';
1963 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1965 Value = Value * 8 + (Str[i] - '0');
1967 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1969 Value = Value * 8 + (Str[i] - '0');
1974 return TokError("invalid octal escape sequence (out of range)");
1976 Data += (unsigned char) Value;
1980 // Otherwise recognize individual escapes.
1983 // Just reject invalid escape sequences for now.
1984 return TokError("invalid escape sequence (unrecognized character)");
1986 case 'b': Data += '\b'; break;
1987 case 'f': Data += '\f'; break;
1988 case 'n': Data += '\n'; break;
1989 case 'r': Data += '\r'; break;
1990 case 't': Data += '\t'; break;
1991 case '"': Data += '"'; break;
1992 case '\\': Data += '\\'; break;
1999 /// ParseDirectiveAscii:
2000 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2001 bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2002 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2003 CheckForValidSection();
2006 if (getLexer().isNot(AsmToken::String))
2007 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2010 if (ParseEscapedString(Data))
2013 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
2015 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2019 if (getLexer().is(AsmToken::EndOfStatement))
2022 if (getLexer().isNot(AsmToken::Comma))
2023 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2032 /// ParseDirectiveValue
2033 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2034 bool AsmParser::ParseDirectiveValue(unsigned Size) {
2035 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2036 CheckForValidSection();
2039 const MCExpr *Value;
2040 SMLoc ExprLoc = getLexer().getLoc();
2041 if (ParseExpression(Value))
2044 // Special case constant expressions to match code generator.
2045 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2046 assert(Size <= 8 && "Invalid size");
2047 uint64_t IntValue = MCE->getValue();
2048 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2049 return Error(ExprLoc, "literal value out of range for directive");
2050 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2052 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
2054 if (getLexer().is(AsmToken::EndOfStatement))
2057 // FIXME: Improve diagnostic.
2058 if (getLexer().isNot(AsmToken::Comma))
2059 return TokError("unexpected token in directive");
2068 /// ParseDirectiveRealValue
2069 /// ::= (.single | .double) [ expression (, expression)* ]
2070 bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2071 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2072 CheckForValidSection();
2075 // We don't truly support arithmetic on floating point expressions, so we
2076 // have to manually parse unary prefixes.
2078 if (getLexer().is(AsmToken::Minus)) {
2081 } else if (getLexer().is(AsmToken::Plus))
2084 if (getLexer().isNot(AsmToken::Integer) &&
2085 getLexer().isNot(AsmToken::Real) &&
2086 getLexer().isNot(AsmToken::Identifier))
2087 return TokError("unexpected token in directive");
2089 // Convert to an APFloat.
2090 APFloat Value(Semantics);
2091 StringRef IDVal = getTok().getString();
2092 if (getLexer().is(AsmToken::Identifier)) {
2093 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2094 Value = APFloat::getInf(Semantics);
2095 else if (!IDVal.compare_lower("nan"))
2096 Value = APFloat::getNaN(Semantics, false, ~0);
2098 return TokError("invalid floating point literal");
2099 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2100 APFloat::opInvalidOp)
2101 return TokError("invalid floating point literal");
2105 // Consume the numeric token.
2108 // Emit the value as an integer.
2109 APInt AsInt = Value.bitcastToAPInt();
2110 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2111 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2113 if (getLexer().is(AsmToken::EndOfStatement))
2116 if (getLexer().isNot(AsmToken::Comma))
2117 return TokError("unexpected token in directive");
2126 /// ParseDirectiveSpace
2127 /// ::= .space expression [ , expression ]
2128 bool AsmParser::ParseDirectiveSpace() {
2129 CheckForValidSection();
2132 if (ParseAbsoluteExpression(NumBytes))
2135 int64_t FillExpr = 0;
2136 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2137 if (getLexer().isNot(AsmToken::Comma))
2138 return TokError("unexpected token in '.space' directive");
2141 if (ParseAbsoluteExpression(FillExpr))
2144 if (getLexer().isNot(AsmToken::EndOfStatement))
2145 return TokError("unexpected token in '.space' directive");
2151 return TokError("invalid number of bytes in '.space' directive");
2153 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
2154 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
2159 /// ParseDirectiveZero
2160 /// ::= .zero expression
2161 bool AsmParser::ParseDirectiveZero() {
2162 CheckForValidSection();
2165 if (ParseAbsoluteExpression(NumBytes))
2169 if (getLexer().is(AsmToken::Comma)) {
2171 if (ParseAbsoluteExpression(Val))
2175 if (getLexer().isNot(AsmToken::EndOfStatement))
2176 return TokError("unexpected token in '.zero' directive");
2180 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
2185 /// ParseDirectiveFill
2186 /// ::= .fill expression , expression , expression
2187 bool AsmParser::ParseDirectiveFill() {
2188 CheckForValidSection();
2191 if (ParseAbsoluteExpression(NumValues))
2194 if (getLexer().isNot(AsmToken::Comma))
2195 return TokError("unexpected token in '.fill' directive");
2199 if (ParseAbsoluteExpression(FillSize))
2202 if (getLexer().isNot(AsmToken::Comma))
2203 return TokError("unexpected token in '.fill' directive");
2207 if (ParseAbsoluteExpression(FillExpr))
2210 if (getLexer().isNot(AsmToken::EndOfStatement))
2211 return TokError("unexpected token in '.fill' directive");
2215 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2216 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
2218 for (uint64_t i = 0, e = NumValues; i != e; ++i)
2219 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
2224 /// ParseDirectiveOrg
2225 /// ::= .org expression [ , expression ]
2226 bool AsmParser::ParseDirectiveOrg() {
2227 CheckForValidSection();
2229 const MCExpr *Offset;
2230 SMLoc Loc = getTok().getLoc();
2231 if (ParseExpression(Offset))
2234 // Parse optional fill expression.
2235 int64_t FillExpr = 0;
2236 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2237 if (getLexer().isNot(AsmToken::Comma))
2238 return TokError("unexpected token in '.org' directive");
2241 if (ParseAbsoluteExpression(FillExpr))
2244 if (getLexer().isNot(AsmToken::EndOfStatement))
2245 return TokError("unexpected token in '.org' directive");
2250 // Only limited forms of relocatable expressions are accepted here, it
2251 // has to be relative to the current section. The streamer will return
2252 // 'true' if the expression wasn't evaluatable.
2253 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2254 return Error(Loc, "expected assembly-time absolute expression");
2259 /// ParseDirectiveAlign
2260 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2261 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2262 CheckForValidSection();
2264 SMLoc AlignmentLoc = getLexer().getLoc();
2266 if (ParseAbsoluteExpression(Alignment))
2270 bool HasFillExpr = false;
2271 int64_t FillExpr = 0;
2272 int64_t MaxBytesToFill = 0;
2273 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2274 if (getLexer().isNot(AsmToken::Comma))
2275 return TokError("unexpected token in directive");
2278 // The fill expression can be omitted while specifying a maximum number of
2279 // alignment bytes, e.g:
2281 if (getLexer().isNot(AsmToken::Comma)) {
2283 if (ParseAbsoluteExpression(FillExpr))
2287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2288 if (getLexer().isNot(AsmToken::Comma))
2289 return TokError("unexpected token in directive");
2292 MaxBytesLoc = getLexer().getLoc();
2293 if (ParseAbsoluteExpression(MaxBytesToFill))
2296 if (getLexer().isNot(AsmToken::EndOfStatement))
2297 return TokError("unexpected token in directive");
2306 // Compute alignment in bytes.
2308 // FIXME: Diagnose overflow.
2309 if (Alignment >= 32) {
2310 Error(AlignmentLoc, "invalid alignment value");
2314 Alignment = 1ULL << Alignment;
2317 // Diagnose non-sensical max bytes to align.
2318 if (MaxBytesLoc.isValid()) {
2319 if (MaxBytesToFill < 1) {
2320 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2321 "many bytes, ignoring maximum bytes expression");
2325 if (MaxBytesToFill >= Alignment) {
2326 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2332 // Check whether we should use optimal code alignment for this .align
2334 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
2335 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2336 ValueSize == 1 && UseCodeAlign) {
2337 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2339 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2340 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2347 /// ParseDirectiveSymbolAttribute
2348 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
2349 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
2350 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2353 SMLoc Loc = getTok().getLoc();
2355 if (ParseIdentifier(Name))
2356 return Error(Loc, "expected identifier in directive");
2358 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2360 // Assembler local symbols don't make any sense here. Complain loudly.
2361 if (Sym->isTemporary())
2362 return Error(Loc, "non-local symbol required in directive");
2364 getStreamer().EmitSymbolAttribute(Sym, Attr);
2366 if (getLexer().is(AsmToken::EndOfStatement))
2369 if (getLexer().isNot(AsmToken::Comma))
2370 return TokError("unexpected token in directive");
2379 /// ParseDirectiveComm
2380 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2381 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
2382 CheckForValidSection();
2384 SMLoc IDLoc = getLexer().getLoc();
2386 if (ParseIdentifier(Name))
2387 return TokError("expected identifier in directive");
2389 // Handle the identifier as the key symbol.
2390 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2392 if (getLexer().isNot(AsmToken::Comma))
2393 return TokError("unexpected token in directive");
2397 SMLoc SizeLoc = getLexer().getLoc();
2398 if (ParseAbsoluteExpression(Size))
2401 int64_t Pow2Alignment = 0;
2402 SMLoc Pow2AlignmentLoc;
2403 if (getLexer().is(AsmToken::Comma)) {
2405 Pow2AlignmentLoc = getLexer().getLoc();
2406 if (ParseAbsoluteExpression(Pow2Alignment))
2409 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2410 if (IsLocal && LCOMM == LCOMM::NoAlignment)
2411 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2413 // If this target takes alignments in bytes (not log) validate and convert.
2414 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2415 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
2416 if (!isPowerOf2_64(Pow2Alignment))
2417 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2418 Pow2Alignment = Log2_64(Pow2Alignment);
2422 if (getLexer().isNot(AsmToken::EndOfStatement))
2423 return TokError("unexpected token in '.comm' or '.lcomm' directive");
2427 // NOTE: a size of zero for a .comm should create a undefined symbol
2428 // but a size of .lcomm creates a bss symbol of size zero.
2430 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2431 "be less than zero");
2433 // NOTE: The alignment in the directive is a power of 2 value, the assembler
2434 // may internally end up wanting an alignment in bytes.
2435 // FIXME: Diagnose overflow.
2436 if (Pow2Alignment < 0)
2437 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2438 "alignment, can't be less than zero");
2440 if (!Sym->isUndefined())
2441 return Error(IDLoc, "invalid symbol redefinition");
2443 // Create the Symbol as a common or local common with Size and Pow2Alignment
2445 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2449 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
2453 /// ParseDirectiveAbort
2454 /// ::= .abort [... message ...]
2455 bool AsmParser::ParseDirectiveAbort() {
2456 // FIXME: Use loc from directive.
2457 SMLoc Loc = getLexer().getLoc();
2459 StringRef Str = ParseStringToEndOfStatement();
2460 if (getLexer().isNot(AsmToken::EndOfStatement))
2461 return TokError("unexpected token in '.abort' directive");
2466 Error(Loc, ".abort detected. Assembly stopping.");
2468 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
2469 // FIXME: Actually abort assembly here.
2474 /// ParseDirectiveInclude
2475 /// ::= .include "filename"
2476 bool AsmParser::ParseDirectiveInclude() {
2477 if (getLexer().isNot(AsmToken::String))
2478 return TokError("expected string in '.include' directive");
2480 std::string Filename = getTok().getString();
2481 SMLoc IncludeLoc = getLexer().getLoc();
2484 if (getLexer().isNot(AsmToken::EndOfStatement))
2485 return TokError("unexpected token in '.include' directive");
2487 // Strip the quotes.
2488 Filename = Filename.substr(1, Filename.size()-2);
2490 // Attempt to switch the lexer to the included file before consuming the end
2491 // of statement to avoid losing it when we switch.
2492 if (EnterIncludeFile(Filename)) {
2493 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
2500 /// ParseDirectiveIncbin
2501 /// ::= .incbin "filename"
2502 bool AsmParser::ParseDirectiveIncbin() {
2503 if (getLexer().isNot(AsmToken::String))
2504 return TokError("expected string in '.incbin' directive");
2506 std::string Filename = getTok().getString();
2507 SMLoc IncbinLoc = getLexer().getLoc();
2510 if (getLexer().isNot(AsmToken::EndOfStatement))
2511 return TokError("unexpected token in '.incbin' directive");
2513 // Strip the quotes.
2514 Filename = Filename.substr(1, Filename.size()-2);
2516 // Attempt to process the included file.
2517 if (ProcessIncbinFile(Filename)) {
2518 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2525 /// ParseDirectiveIf
2526 /// ::= .if expression
2527 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
2528 TheCondStack.push_back(TheCondState);
2529 TheCondState.TheCond = AsmCond::IfCond;
2530 if (TheCondState.Ignore) {
2531 EatToEndOfStatement();
2534 if (ParseAbsoluteExpression(ExprValue))
2537 if (getLexer().isNot(AsmToken::EndOfStatement))
2538 return TokError("unexpected token in '.if' directive");
2542 TheCondState.CondMet = ExprValue;
2543 TheCondState.Ignore = !TheCondState.CondMet;
2549 /// ParseDirectiveIfb
2551 bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2552 TheCondStack.push_back(TheCondState);
2553 TheCondState.TheCond = AsmCond::IfCond;
2555 if (TheCondState.Ignore) {
2556 EatToEndOfStatement();
2558 StringRef Str = ParseStringToEndOfStatement();
2560 if (getLexer().isNot(AsmToken::EndOfStatement))
2561 return TokError("unexpected token in '.ifb' directive");
2565 TheCondState.CondMet = ExpectBlank == Str.empty();
2566 TheCondState.Ignore = !TheCondState.CondMet;
2572 /// ParseDirectiveIfc
2573 /// ::= .ifc string1, string2
2574 bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2575 TheCondStack.push_back(TheCondState);
2576 TheCondState.TheCond = AsmCond::IfCond;
2578 if (TheCondState.Ignore) {
2579 EatToEndOfStatement();
2581 StringRef Str1 = ParseStringToComma();
2583 if (getLexer().isNot(AsmToken::Comma))
2584 return TokError("unexpected token in '.ifc' directive");
2588 StringRef Str2 = ParseStringToEndOfStatement();
2590 if (getLexer().isNot(AsmToken::EndOfStatement))
2591 return TokError("unexpected token in '.ifc' directive");
2595 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2596 TheCondState.Ignore = !TheCondState.CondMet;
2602 /// ParseDirectiveIfdef
2603 /// ::= .ifdef symbol
2604 bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2606 TheCondStack.push_back(TheCondState);
2607 TheCondState.TheCond = AsmCond::IfCond;
2609 if (TheCondState.Ignore) {
2610 EatToEndOfStatement();
2612 if (ParseIdentifier(Name))
2613 return TokError("expected identifier after '.ifdef'");
2617 MCSymbol *Sym = getContext().LookupSymbol(Name);
2620 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2622 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2623 TheCondState.Ignore = !TheCondState.CondMet;
2629 /// ParseDirectiveElseIf
2630 /// ::= .elseif expression
2631 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2632 if (TheCondState.TheCond != AsmCond::IfCond &&
2633 TheCondState.TheCond != AsmCond::ElseIfCond)
2634 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2636 TheCondState.TheCond = AsmCond::ElseIfCond;
2638 bool LastIgnoreState = false;
2639 if (!TheCondStack.empty())
2640 LastIgnoreState = TheCondStack.back().Ignore;
2641 if (LastIgnoreState || TheCondState.CondMet) {
2642 TheCondState.Ignore = true;
2643 EatToEndOfStatement();
2647 if (ParseAbsoluteExpression(ExprValue))
2650 if (getLexer().isNot(AsmToken::EndOfStatement))
2651 return TokError("unexpected token in '.elseif' directive");
2654 TheCondState.CondMet = ExprValue;
2655 TheCondState.Ignore = !TheCondState.CondMet;
2661 /// ParseDirectiveElse
2663 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
2664 if (getLexer().isNot(AsmToken::EndOfStatement))
2665 return TokError("unexpected token in '.else' directive");
2669 if (TheCondState.TheCond != AsmCond::IfCond &&
2670 TheCondState.TheCond != AsmCond::ElseIfCond)
2671 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2673 TheCondState.TheCond = AsmCond::ElseCond;
2674 bool LastIgnoreState = false;
2675 if (!TheCondStack.empty())
2676 LastIgnoreState = TheCondStack.back().Ignore;
2677 if (LastIgnoreState || TheCondState.CondMet)
2678 TheCondState.Ignore = true;
2680 TheCondState.Ignore = false;
2685 /// ParseDirectiveEndIf
2687 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
2688 if (getLexer().isNot(AsmToken::EndOfStatement))
2689 return TokError("unexpected token in '.endif' directive");
2693 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2694 TheCondStack.empty())
2695 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2697 if (!TheCondStack.empty()) {
2698 TheCondState = TheCondStack.back();
2699 TheCondStack.pop_back();
2705 /// ParseDirectiveFile
2706 /// ::= .file [number] filename
2707 /// ::= .file number directory filename
2708 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
2709 // FIXME: I'm not sure what this is.
2710 int64_t FileNumber = -1;
2711 SMLoc FileNumberLoc = getLexer().getLoc();
2712 if (getLexer().is(AsmToken::Integer)) {
2713 FileNumber = getTok().getIntVal();
2717 return TokError("file number less than one");
2720 if (getLexer().isNot(AsmToken::String))
2721 return TokError("unexpected token in '.file' directive");
2723 // Usually the directory and filename together, otherwise just the directory.
2724 StringRef Path = getTok().getString();
2725 Path = Path.substr(1, Path.size()-2);
2728 StringRef Directory;
2730 if (getLexer().is(AsmToken::String)) {
2731 if (FileNumber == -1)
2732 return TokError("explicit path specified, but no file number");
2733 Filename = getTok().getString();
2734 Filename = Filename.substr(1, Filename.size()-2);
2741 if (getLexer().isNot(AsmToken::EndOfStatement))
2742 return TokError("unexpected token in '.file' directive");
2744 if (FileNumber == -1)
2745 getStreamer().EmitFileDirective(Filename);
2747 if (getContext().getGenDwarfForAssembly() == true)
2748 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2749 "used to generate dwarf debug info for assembly code");
2751 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2752 Error(FileNumberLoc, "file number already allocated");
2758 /// ParseDirectiveLine
2759 /// ::= .line [number]
2760 bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
2761 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2762 if (getLexer().isNot(AsmToken::Integer))
2763 return TokError("unexpected token in '.line' directive");
2765 int64_t LineNumber = getTok().getIntVal();
2769 // FIXME: Do something with the .line.
2772 if (getLexer().isNot(AsmToken::EndOfStatement))
2773 return TokError("unexpected token in '.line' directive");
2779 /// ParseDirectiveLoc
2780 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2781 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2782 /// The first number is a file number, must have been previously assigned with
2783 /// a .file directive, the second number is the line number and optionally the
2784 /// third number is a column position (zero if not specified). The remaining
2785 /// optional items are .loc sub-directives.
2786 bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
2788 if (getLexer().isNot(AsmToken::Integer))
2789 return TokError("unexpected token in '.loc' directive");
2790 int64_t FileNumber = getTok().getIntVal();
2792 return TokError("file number less than one in '.loc' directive");
2793 if (!getContext().isValidDwarfFileNumber(FileNumber))
2794 return TokError("unassigned file number in '.loc' directive");
2797 int64_t LineNumber = 0;
2798 if (getLexer().is(AsmToken::Integer)) {
2799 LineNumber = getTok().getIntVal();
2801 return TokError("line number less than one in '.loc' directive");
2805 int64_t ColumnPos = 0;
2806 if (getLexer().is(AsmToken::Integer)) {
2807 ColumnPos = getTok().getIntVal();
2809 return TokError("column position less than zero in '.loc' directive");
2813 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2815 int64_t Discriminator = 0;
2816 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2818 if (getLexer().is(AsmToken::EndOfStatement))
2822 SMLoc Loc = getTok().getLoc();
2823 if (getParser().ParseIdentifier(Name))
2824 return TokError("unexpected token in '.loc' directive");
2826 if (Name == "basic_block")
2827 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2828 else if (Name == "prologue_end")
2829 Flags |= DWARF2_FLAG_PROLOGUE_END;
2830 else if (Name == "epilogue_begin")
2831 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2832 else if (Name == "is_stmt") {
2833 SMLoc Loc = getTok().getLoc();
2834 const MCExpr *Value;
2835 if (getParser().ParseExpression(Value))
2837 // The expression must be the constant 0 or 1.
2838 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2839 int Value = MCE->getValue();
2841 Flags &= ~DWARF2_FLAG_IS_STMT;
2842 else if (Value == 1)
2843 Flags |= DWARF2_FLAG_IS_STMT;
2845 return Error(Loc, "is_stmt value not 0 or 1");
2848 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2851 else if (Name == "isa") {
2852 SMLoc Loc = getTok().getLoc();
2853 const MCExpr *Value;
2854 if (getParser().ParseExpression(Value))
2856 // The expression must be a constant greater or equal to 0.
2857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2858 int Value = MCE->getValue();
2860 return Error(Loc, "isa number less than zero");
2864 return Error(Loc, "isa number not a constant value");
2867 else if (Name == "discriminator") {
2868 if (getParser().ParseAbsoluteExpression(Discriminator))
2872 return Error(Loc, "unknown sub-directive in '.loc' directive");
2875 if (getLexer().is(AsmToken::EndOfStatement))
2880 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2881 Isa, Discriminator, StringRef());
2886 /// ParseDirectiveStabs
2887 /// ::= .stabs string, number, number, number
2888 bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2889 SMLoc DirectiveLoc) {
2890 return TokError("unsupported directive '" + Directive + "'");
2893 /// ParseDirectiveCFISections
2894 /// ::= .cfi_sections section [, section]
2895 bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2896 SMLoc DirectiveLoc) {
2901 if (getParser().ParseIdentifier(Name))
2902 return TokError("Expected an identifier");
2904 if (Name == ".eh_frame")
2906 else if (Name == ".debug_frame")
2909 if (getLexer().is(AsmToken::Comma)) {
2912 if (getParser().ParseIdentifier(Name))
2913 return TokError("Expected an identifier");
2915 if (Name == ".eh_frame")
2917 else if (Name == ".debug_frame")
2921 getStreamer().EmitCFISections(EH, Debug);
2926 /// ParseDirectiveCFIStartProc
2927 /// ::= .cfi_startproc
2928 bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2929 SMLoc DirectiveLoc) {
2930 getStreamer().EmitCFIStartProc();
2934 /// ParseDirectiveCFIEndProc
2935 /// ::= .cfi_endproc
2936 bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
2937 getStreamer().EmitCFIEndProc();
2941 /// ParseRegisterOrRegisterNumber - parse register name or number.
2942 bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2943 SMLoc DirectiveLoc) {
2946 if (getLexer().isNot(AsmToken::Integer)) {
2947 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2950 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2952 return getParser().ParseAbsoluteExpression(Register);
2957 /// ParseDirectiveCFIDefCfa
2958 /// ::= .cfi_def_cfa register, offset
2959 bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2960 SMLoc DirectiveLoc) {
2961 int64_t Register = 0;
2962 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2965 if (getLexer().isNot(AsmToken::Comma))
2966 return TokError("unexpected token in directive");
2970 if (getParser().ParseAbsoluteExpression(Offset))
2973 getStreamer().EmitCFIDefCfa(Register, Offset);
2977 /// ParseDirectiveCFIDefCfaOffset
2978 /// ::= .cfi_def_cfa_offset offset
2979 bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2980 SMLoc DirectiveLoc) {
2982 if (getParser().ParseAbsoluteExpression(Offset))
2985 getStreamer().EmitCFIDefCfaOffset(Offset);
2989 /// ParseDirectiveCFIAdjustCfaOffset
2990 /// ::= .cfi_adjust_cfa_offset adjustment
2991 bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2992 SMLoc DirectiveLoc) {
2993 int64_t Adjustment = 0;
2994 if (getParser().ParseAbsoluteExpression(Adjustment))
2997 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3001 /// ParseDirectiveCFIDefCfaRegister
3002 /// ::= .cfi_def_cfa_register register
3003 bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3004 SMLoc DirectiveLoc) {
3005 int64_t Register = 0;
3006 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3009 getStreamer().EmitCFIDefCfaRegister(Register);
3013 /// ParseDirectiveCFIOffset
3014 /// ::= .cfi_offset register, offset
3015 bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3016 int64_t Register = 0;
3019 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3022 if (getLexer().isNot(AsmToken::Comma))
3023 return TokError("unexpected token in directive");
3026 if (getParser().ParseAbsoluteExpression(Offset))
3029 getStreamer().EmitCFIOffset(Register, Offset);
3033 /// ParseDirectiveCFIRelOffset
3034 /// ::= .cfi_rel_offset register, offset
3035 bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3036 SMLoc DirectiveLoc) {
3037 int64_t Register = 0;
3039 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3042 if (getLexer().isNot(AsmToken::Comma))
3043 return TokError("unexpected token in directive");
3047 if (getParser().ParseAbsoluteExpression(Offset))
3050 getStreamer().EmitCFIRelOffset(Register, Offset);
3054 static bool isValidEncoding(int64_t Encoding) {
3055 if (Encoding & ~0xff)
3058 if (Encoding == dwarf::DW_EH_PE_omit)
3061 const unsigned Format = Encoding & 0xf;
3062 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3063 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3064 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3065 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3068 const unsigned Application = Encoding & 0x70;
3069 if (Application != dwarf::DW_EH_PE_absptr &&
3070 Application != dwarf::DW_EH_PE_pcrel)
3076 /// ParseDirectiveCFIPersonalityOrLsda
3077 /// ::= .cfi_personality encoding, [symbol_name]
3078 /// ::= .cfi_lsda encoding, [symbol_name]
3079 bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
3080 SMLoc DirectiveLoc) {
3081 int64_t Encoding = 0;
3082 if (getParser().ParseAbsoluteExpression(Encoding))
3084 if (Encoding == dwarf::DW_EH_PE_omit)
3087 if (!isValidEncoding(Encoding))
3088 return TokError("unsupported encoding.");
3090 if (getLexer().isNot(AsmToken::Comma))
3091 return TokError("unexpected token in directive");
3095 if (getParser().ParseIdentifier(Name))
3096 return TokError("expected identifier in directive");
3098 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3100 if (IDVal == ".cfi_personality")
3101 getStreamer().EmitCFIPersonality(Sym, Encoding);
3103 assert(IDVal == ".cfi_lsda");
3104 getStreamer().EmitCFILsda(Sym, Encoding);
3109 /// ParseDirectiveCFIRememberState
3110 /// ::= .cfi_remember_state
3111 bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3112 SMLoc DirectiveLoc) {
3113 getStreamer().EmitCFIRememberState();
3117 /// ParseDirectiveCFIRestoreState
3118 /// ::= .cfi_remember_state
3119 bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3120 SMLoc DirectiveLoc) {
3121 getStreamer().EmitCFIRestoreState();
3125 /// ParseDirectiveCFISameValue
3126 /// ::= .cfi_same_value register
3127 bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3128 SMLoc DirectiveLoc) {
3129 int64_t Register = 0;
3131 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3134 getStreamer().EmitCFISameValue(Register);
3139 /// ParseDirectiveCFIRestore
3140 /// ::= .cfi_restore register
3141 bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
3142 SMLoc DirectiveLoc) {
3143 int64_t Register = 0;
3144 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3147 getStreamer().EmitCFIRestore(Register);
3152 /// ParseDirectiveCFIEscape
3153 /// ::= .cfi_escape expression[,...]
3154 bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3155 SMLoc DirectiveLoc) {
3158 if (getParser().ParseAbsoluteExpression(CurrValue))
3161 Values.push_back((uint8_t)CurrValue);
3163 while (getLexer().is(AsmToken::Comma)) {
3166 if (getParser().ParseAbsoluteExpression(CurrValue))
3169 Values.push_back((uint8_t)CurrValue);
3172 getStreamer().EmitCFIEscape(Values);
3176 /// ParseDirectiveCFISignalFrame
3177 /// ::= .cfi_signal_frame
3178 bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3179 SMLoc DirectiveLoc) {
3180 if (getLexer().isNot(AsmToken::EndOfStatement))
3181 return Error(getLexer().getLoc(),
3182 "unexpected token in '" + Directive + "' directive");
3184 getStreamer().EmitCFISignalFrame();
3189 /// ParseDirectiveMacrosOnOff
3192 bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3193 SMLoc DirectiveLoc) {
3194 if (getLexer().isNot(AsmToken::EndOfStatement))
3195 return Error(getLexer().getLoc(),
3196 "unexpected token in '" + Directive + "' directive");
3198 getParser().MacrosEnabled = Directive == ".macros_on";
3203 /// ParseDirectiveMacro
3204 /// ::= .macro name [parameters]
3205 bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3206 SMLoc DirectiveLoc) {
3208 if (getParser().ParseIdentifier(Name))
3209 return TokError("expected identifier in '.macro' directive");
3211 MacroParameters Parameters;
3212 // Argument delimiter is initially unknown. It will be set by
3213 // ParseMacroArgument()
3214 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3215 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3217 MacroParameter Parameter;
3218 if (getParser().ParseIdentifier(Parameter.first))
3219 return TokError("expected identifier in '.macro' directive");
3221 if (getLexer().is(AsmToken::Equal)) {
3223 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3227 Parameters.push_back(Parameter);
3229 if (getLexer().is(AsmToken::Comma))
3231 else if (getLexer().is(AsmToken::EndOfStatement))
3236 // Eat the end of statement.
3239 AsmToken EndToken, StartToken = getTok();
3241 // Lex the macro definition.
3243 // Check whether we have reached the end of the file.
3244 if (getLexer().is(AsmToken::Eof))
3245 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3247 // Otherwise, check whether we have reach the .endmacro.
3248 if (getLexer().is(AsmToken::Identifier) &&
3249 (getTok().getIdentifier() == ".endm" ||
3250 getTok().getIdentifier() == ".endmacro")) {
3251 EndToken = getTok();
3253 if (getLexer().isNot(AsmToken::EndOfStatement))
3254 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3259 // Otherwise, scan til the end of the statement.
3260 getParser().EatToEndOfStatement();
3263 if (getParser().MacroMap.lookup(Name)) {
3264 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3267 const char *BodyStart = StartToken.getLoc().getPointer();
3268 const char *BodyEnd = EndToken.getLoc().getPointer();
3269 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3270 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
3274 /// ParseDirectiveEndMacro
3277 bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3278 SMLoc DirectiveLoc) {
3279 if (getLexer().isNot(AsmToken::EndOfStatement))
3280 return TokError("unexpected token in '" + Directive + "' directive");
3282 // If we are inside a macro instantiation, terminate the current
3284 if (!getParser().ActiveMacros.empty()) {
3285 getParser().HandleMacroExit();
3289 // Otherwise, this .endmacro is a stray entry in the file; well formed
3290 // .endmacro directives are handled during the macro definition parsing.
3291 return TokError("unexpected '" + Directive + "' in file, "
3292 "no current macro definition");
3295 /// ParseDirectivePurgeMacro
3297 bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3298 SMLoc DirectiveLoc) {
3300 if (getParser().ParseIdentifier(Name))
3301 return TokError("expected identifier in '.purgem' directive");
3303 if (getLexer().isNot(AsmToken::EndOfStatement))
3304 return TokError("unexpected token in '.purgem' directive");
3306 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3307 if (I == getParser().MacroMap.end())
3308 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3310 // Undefine the macro.
3311 delete I->getValue();
3312 getParser().MacroMap.erase(I);
3316 bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
3317 getParser().CheckForValidSection();
3319 const MCExpr *Value;
3321 if (getParser().ParseExpression(Value))
3324 if (getLexer().isNot(AsmToken::EndOfStatement))
3325 return TokError("unexpected token in directive");
3327 if (DirName[1] == 's')
3328 getStreamer().EmitSLEB128Value(Value);
3330 getStreamer().EmitULEB128Value(Value);
3335 Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
3336 AsmToken EndToken, StartToken = getTok();
3338 unsigned NestLevel = 0;
3340 // Check whether we have reached the end of the file.
3341 if (getLexer().is(AsmToken::Eof)) {
3342 Error(DirectiveLoc, "no matching '.endr' in definition");
3346 if (Lexer.is(AsmToken::Identifier) &&
3347 (getTok().getIdentifier() == ".rept")) {
3351 // Otherwise, check whether we have reached the .endr.
3352 if (Lexer.is(AsmToken::Identifier) &&
3353 getTok().getIdentifier() == ".endr") {
3354 if (NestLevel == 0) {
3355 EndToken = getTok();
3357 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3358 TokError("unexpected token in '.endr' directive");
3366 // Otherwise, scan till the end of the statement.
3367 EatToEndOfStatement();
3370 const char *BodyStart = StartToken.getLoc().getPointer();
3371 const char *BodyEnd = EndToken.getLoc().getPointer();
3372 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3374 // We Are Anonymous.
3376 MacroParameters Parameters;
3377 return new Macro(Name, Body, Parameters);
3380 void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3381 raw_svector_ostream &OS) {
3384 MemoryBuffer *Instantiation =
3385 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3387 // Create the macro instantiation object and add to the current macro
3388 // instantiation stack.
3389 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3392 ActiveMacros.push_back(MI);
3394 // Jump to the macro instantiation and prime the lexer.
3395 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3396 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3400 bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3402 if (ParseAbsoluteExpression(Count))
3403 return TokError("unexpected token in '.rept' directive");
3406 return TokError("Count is negative");
3408 if (Lexer.isNot(AsmToken::EndOfStatement))
3409 return TokError("unexpected token in '.rept' directive");
3411 // Eat the end of statement.
3414 // Lex the rept definition.
3415 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3419 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3420 // to hold the macro body with substitutions.
3421 SmallString<256> Buf;
3422 MacroParameters Parameters;
3424 raw_svector_ostream OS(Buf);
3426 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3429 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3434 /// ParseDirectiveIrp
3435 /// ::= .irp symbol,values
3436 bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3437 MacroParameters Parameters;
3438 MacroParameter Parameter;
3440 if (ParseIdentifier(Parameter.first))
3441 return TokError("expected identifier in '.irp' directive");
3443 Parameters.push_back(Parameter);
3445 if (Lexer.isNot(AsmToken::Comma))
3446 return TokError("expected comma in '.irp' directive");
3451 if (ParseMacroArguments(0, A))
3454 // Eat the end of statement.
3457 // Lex the irp definition.
3458 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3462 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3463 // to hold the macro body with substitutions.
3464 SmallString<256> Buf;
3465 raw_svector_ostream OS(Buf);
3467 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3468 MacroArguments Args;
3471 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3475 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3480 /// ParseDirectiveIrpc
3481 /// ::= .irpc symbol,values
3482 bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
3483 MacroParameters Parameters;
3484 MacroParameter Parameter;
3486 if (ParseIdentifier(Parameter.first))
3487 return TokError("expected identifier in '.irpc' directive");
3489 Parameters.push_back(Parameter);
3491 if (Lexer.isNot(AsmToken::Comma))
3492 return TokError("expected comma in '.irpc' directive");
3497 if (ParseMacroArguments(0, A))
3500 if (A.size() != 1 || A.front().size() != 1)
3501 return TokError("unexpected token in '.irpc' directive");
3503 // Eat the end of statement.
3506 // Lex the irpc definition.
3507 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3511 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3512 // to hold the macro body with substitutions.
3513 SmallString<256> Buf;
3514 raw_svector_ostream OS(Buf);
3516 StringRef Values = A.front().front().getString();
3517 std::size_t I, End = Values.size();
3518 for (I = 0; I < End; ++I) {
3520 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3522 MacroArguments Args;
3523 Args.push_back(Arg);
3525 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3529 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3534 bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3535 if (ActiveMacros.empty())
3536 return TokError("unmatched '.endr' directive");
3538 // The only .repl that should get here are the ones created by
3539 // InstantiateMacroLikeBody.
3540 assert(getLexer().is(AsmToken::EndOfStatement));
3546 /// \brief Create an MCAsmParser instance.
3547 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
3548 MCContext &C, MCStreamer &Out,
3549 const MCAsmInfo &MAI) {
3550 return new AsmParser(SM, C, Out, MAI);