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/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/AsmCond.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCTargetAsmParser.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/raw_ostream.h"
49 FatalAssemblerWarnings("fatal-assembler-warnings",
50 cl::desc("Consider warnings as error"));
52 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
55 /// \brief Helper types for tracking macro definitions.
56 typedef std::vector<AsmToken> MCAsmMacroArgument;
57 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
59 struct MCAsmMacroParameter {
61 MCAsmMacroArgument Value;
65 MCAsmMacroParameter() : Required(false), Vararg(false) {}
68 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
73 MCAsmMacroParameters Parameters;
76 MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
77 Name(N), Body(B), Parameters(P) {}
80 /// \brief Helper class for storing information about an active macro
82 struct MacroInstantiation {
83 /// The macro being instantiated.
84 const MCAsmMacro *TheMacro;
86 /// The macro instantiation with substitutions.
87 MemoryBuffer *Instantiation;
89 /// The location of the instantiation.
90 SMLoc InstantiationLoc;
92 /// The buffer where parsing should resume upon instantiation completion.
95 /// The location where parsing should resume upon instantiation completion.
99 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
103 struct ParseStatementInfo {
104 /// \brief The parsed operands from the last parsed statement.
105 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
107 /// \brief The opcode from the last parsed instruction.
110 /// \brief Was there an error parsing the inline assembly?
113 SmallVectorImpl<AsmRewrite> *AsmRewrites;
115 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
116 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
117 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
120 /// \brief The concrete assembly parser instance.
121 class AsmParser : public MCAsmParser {
122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
128 const MCAsmInfo &MAI;
130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
132 MCAsmParserExtension *PlatformParser;
134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
141 /// \brief maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// addDirectiveHandler.
144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146 /// \brief Map of currently defined macros.
147 StringMap<MCAsmMacro*> MacroMap;
149 /// \brief Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
152 /// \brief List of bodies of anonymous macros.
153 std::deque<MCAsmMacro> MacroLikeBodies;
155 /// Boolean tracking whether macro substitution is enabled.
156 unsigned MacrosEnabledFlag : 1;
158 /// Flag tracking whether any errors have been encountered.
159 unsigned HadError : 1;
161 /// The values from the last parsed cpp hash file line comment if any.
162 StringRef CppHashFilename;
163 int64_t CppHashLineNumber;
166 /// When generating dwarf for assembly source files we need to calculate the
167 /// logical line number based on the last parsed cpp hash file line comment
168 /// and current line. Since this is slow and messes up the SourceMgr's
169 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
170 SMLoc LastQueryIDLoc;
172 unsigned LastQueryLine;
174 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175 unsigned AssemblerDialect;
177 /// \brief is Darwin compatibility enabled?
180 /// \brief Are we parsing ms-style inline assembly?
181 bool ParsingInlineAsm;
184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
185 const MCAsmInfo &MAI);
186 virtual ~AsmParser();
188 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
190 void addDirectiveHandler(StringRef Directive,
191 ExtensionDirectiveHandler Handler) override {
192 ExtensionDirectiveMap[Directive] = Handler;
196 /// @name MCAsmParser Interface
199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
204 if (AssemblerDialect == ~0U)
205 return MAI.getAssemblerDialect();
207 return AssemblerDialect;
209 void setAssemblerDialect(unsigned i) override {
210 AssemblerDialect = i;
213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
220 const AsmToken &Lex() override;
222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
226 unsigned &NumOutputs, unsigned &NumInputs,
227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
228 SmallVectorImpl<std::string> &Constraints,
229 SmallVectorImpl<std::string> &Clobbers,
230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
233 bool parseExpression(const MCExpr *&Res);
234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseAbsoluteExpression(int64_t &Res) override;
239 /// \brief Parse an identifier or string (as a quoted identifier)
240 /// and set \p Res to the identifier contents.
241 bool parseIdentifier(StringRef &Res) override;
242 void eatToEndOfStatement() override;
244 void checkForValidSection() override;
249 bool parseStatement(ParseStatementInfo &Info);
250 void eatToEndOfLine();
251 bool parseCppHashLineFilenameComment(const SMLoc &L);
253 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
254 ArrayRef<MCAsmMacroParameter> Parameters);
255 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
256 ArrayRef<MCAsmMacroParameter> Parameters,
257 ArrayRef<MCAsmMacroArgument> A,
260 /// \brief Are macros enabled in the parser?
261 bool areMacrosEnabled() {return MacrosEnabledFlag;}
263 /// \brief Control a flag in the parser that enables or disables macros.
264 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
266 /// \brief Lookup a previously defined macro.
267 /// \param Name Macro name.
268 /// \returns Pointer to macro. NULL if no such macro was defined.
269 const MCAsmMacro* lookupMacro(StringRef Name);
271 /// \brief Define a new macro with the given name and information.
272 void defineMacro(StringRef Name, const MCAsmMacro& Macro);
274 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
275 void undefineMacro(StringRef Name);
277 /// \brief Are we inside a macro instantiation?
278 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
280 /// \brief Handle entry to macro instantiation.
282 /// \param M The macro.
283 /// \param NameLoc Instantiation location.
284 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
286 /// \brief Handle exit from macro instantiation.
287 void handleMacroExit();
289 /// \brief Extract AsmTokens for a macro argument.
290 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
292 /// \brief Parse all macro arguments for a given macro.
293 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
295 void printMacroInstantiations();
296 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
297 ArrayRef<SMRange> Ranges = None) const {
298 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
300 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
302 /// \brief Enter the specified file. This returns true on failure.
303 bool enterIncludeFile(const std::string &Filename);
305 /// \brief Process the specified file for the .incbin directive.
306 /// This returns true on failure.
307 bool processIncbinFile(const std::string &Filename);
309 /// \brief Reset the current lexer position to that given by \p Loc. The
310 /// current token is not set; clients should ensure Lex() is called
313 /// \param InBuffer If not -1, should be the known buffer id that contains the
315 void jumpToLoc(SMLoc Loc, int InBuffer=-1);
317 /// \brief Parse up to the end of statement and a return the contents from the
318 /// current token until the end of the statement; the current token on exit
319 /// will be either the EndOfStatement or EOF.
320 StringRef parseStringToEndOfStatement() override;
322 /// \brief Parse until the end of a statement or a comma is encountered,
323 /// return the contents from the current token up to the end or comma.
324 StringRef parseStringToComma();
326 bool parseAssignment(StringRef Name, bool allow_redef,
327 bool NoDeadStrip = false);
329 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
330 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
331 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
333 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
335 // Generic (target and platform independent) directive parsing.
337 DK_NO_DIRECTIVE, // Placeholder
338 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
339 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
340 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
341 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
342 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
343 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
344 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
345 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
346 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
347 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
348 DK_IF, DK_IFNE, DK_IFB, DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF,
349 DK_IFNDEF, DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
350 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
351 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
352 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
353 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
354 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
355 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
356 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
357 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
358 DK_SLEB128, DK_ULEB128,
363 /// \brief Maps directive name --> DirectiveKind enum, for
364 /// directives parsed by this class.
365 StringMap<DirectiveKind> DirectiveKindMap;
367 // ".ascii", ".asciz", ".string"
368 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
369 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
370 bool parseDirectiveOctaValue(); // ".octa"
371 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
372 bool parseDirectiveFill(); // ".fill"
373 bool parseDirectiveZero(); // ".zero"
374 // ".set", ".equ", ".equiv"
375 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
376 bool parseDirectiveOrg(); // ".org"
377 // ".align{,32}", ".p2align{,w,l}"
378 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
380 // ".file", ".line", ".loc", ".stabs"
381 bool parseDirectiveFile(SMLoc DirectiveLoc);
382 bool parseDirectiveLine();
383 bool parseDirectiveLoc();
384 bool parseDirectiveStabs();
387 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
388 bool parseDirectiveCFIWindowSave();
389 bool parseDirectiveCFISections();
390 bool parseDirectiveCFIStartProc();
391 bool parseDirectiveCFIEndProc();
392 bool parseDirectiveCFIDefCfaOffset();
393 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
394 bool parseDirectiveCFIAdjustCfaOffset();
395 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
396 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
397 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
398 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
399 bool parseDirectiveCFIRememberState();
400 bool parseDirectiveCFIRestoreState();
401 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIEscape();
404 bool parseDirectiveCFISignalFrame();
405 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
408 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
409 bool parseDirectiveEndMacro(StringRef Directive);
410 bool parseDirectiveMacro(SMLoc DirectiveLoc);
411 bool parseDirectiveMacrosOnOff(StringRef Directive);
413 // ".bundle_align_mode"
414 bool parseDirectiveBundleAlignMode();
416 bool parseDirectiveBundleLock();
418 bool parseDirectiveBundleUnlock();
421 bool parseDirectiveSpace(StringRef IDVal);
423 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
424 bool parseDirectiveLEB128(bool Signed);
426 /// \brief Parse a directive like ".globl" which
427 /// accepts a single symbol (which should be a label or an external).
428 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
430 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
432 bool parseDirectiveAbort(); // ".abort"
433 bool parseDirectiveInclude(); // ".include"
434 bool parseDirectiveIncbin(); // ".incbin"
437 bool parseDirectiveIf(SMLoc DirectiveLoc);
438 // ".ifb" or ".ifnb", depending on ExpectBlank.
439 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
440 // ".ifc" or ".ifnc", depending on ExpectEqual.
441 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
443 bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
444 // ".ifdef" or ".ifndef", depending on expect_defined
445 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
446 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
447 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
448 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
449 bool parseEscapedString(std::string &Data) override;
451 const MCExpr *applyModifierToExpr(const MCExpr *E,
452 MCSymbolRefExpr::VariantKind Variant);
454 // Macro-like directives
455 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
456 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
457 raw_svector_ostream &OS);
458 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
459 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
460 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
461 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
463 // "_emit" or "__emit"
464 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
468 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
471 bool parseDirectiveEnd(SMLoc DirectiveLoc);
473 // ".err" or ".error"
474 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
476 void initializeDirectiveKindMap();
482 extern MCAsmParserExtension *createDarwinAsmParser();
483 extern MCAsmParserExtension *createELFAsmParser();
484 extern MCAsmParserExtension *createCOFFAsmParser();
488 enum { DEFAULT_ADDRSPACE = 0 };
490 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
491 const MCAsmInfo &_MAI)
492 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
493 PlatformParser(nullptr), CurBuffer(0), MacrosEnabledFlag(true),
494 HadError(false), CppHashLineNumber(0), AssemblerDialect(~0U),
495 IsDarwin(false), ParsingInlineAsm(false) {
496 // Save the old handler.
497 SavedDiagHandler = SrcMgr.getDiagHandler();
498 SavedDiagContext = SrcMgr.getDiagContext();
499 // Set our own handler which calls the saved handler.
500 SrcMgr.setDiagHandler(DiagHandler, this);
501 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
503 // Initialize the platform / file format parser.
504 switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
505 case MCObjectFileInfo::IsCOFF:
506 PlatformParser = createCOFFAsmParser();
507 PlatformParser->Initialize(*this);
509 case MCObjectFileInfo::IsMachO:
510 PlatformParser = createDarwinAsmParser();
511 PlatformParser->Initialize(*this);
514 case MCObjectFileInfo::IsELF:
515 PlatformParser = createELFAsmParser();
516 PlatformParser->Initialize(*this);
520 initializeDirectiveKindMap();
523 AsmParser::~AsmParser() {
524 assert((HadError || ActiveMacros.empty()) &&
525 "Unexpected active macro instantiation!");
527 // Destroy any macros.
528 for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
531 delete it->getValue();
533 delete PlatformParser;
536 void AsmParser::printMacroInstantiations() {
537 // Print the active macro instantiation stack.
538 for (std::vector<MacroInstantiation *>::const_reverse_iterator
539 it = ActiveMacros.rbegin(),
540 ie = ActiveMacros.rend();
542 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
543 "while in macro instantiation");
546 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
547 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
548 printMacroInstantiations();
551 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
552 if (FatalAssemblerWarnings)
553 return Error(L, Msg, Ranges);
554 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
555 printMacroInstantiations();
559 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
561 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
562 printMacroInstantiations();
566 bool AsmParser::enterIncludeFile(const std::string &Filename) {
567 std::string IncludedFile;
568 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
574 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
579 /// Process the specified .incbin file by searching for it in the include paths
580 /// then just emitting the byte contents of the file to the streamer. This
581 /// returns true on failure.
582 bool AsmParser::processIncbinFile(const std::string &Filename) {
583 std::string IncludedFile;
584 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
588 // Pick up the bytes from the file and emit them.
589 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
593 void AsmParser::jumpToLoc(SMLoc Loc, int InBuffer) {
594 if (InBuffer != -1) {
595 CurBuffer = InBuffer;
597 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
599 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
602 const AsmToken &AsmParser::Lex() {
603 const AsmToken *tok = &Lexer.Lex();
605 if (tok->is(AsmToken::Eof)) {
606 // If this is the end of an included file, pop the parent file off the
608 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
609 if (ParentIncludeLoc != SMLoc()) {
610 jumpToLoc(ParentIncludeLoc);
615 if (tok->is(AsmToken::Error))
616 Error(Lexer.getErrLoc(), Lexer.getErr());
621 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
622 // Create the initial section, if requested.
623 if (!NoInitialTextSection)
630 AsmCond StartingCondState = TheCondState;
632 // If we are generating dwarf for assembly source files save the initial text
633 // section and generate a .file directive.
634 if (getContext().getGenDwarfForAssembly()) {
635 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
636 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
637 getStreamer().EmitLabel(SectionStartSym);
638 getContext().setGenDwarfSectionStartSym(SectionStartSym);
639 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
640 0, StringRef(), getContext().getMainFileName()));
643 // While we have input, parse each statement.
644 while (Lexer.isNot(AsmToken::Eof)) {
645 ParseStatementInfo Info;
646 if (!parseStatement(Info))
649 // We had an error, validate that one was emitted and recover by skipping to
651 assert(HadError && "Parse statement returned an error, but none emitted!");
652 eatToEndOfStatement();
655 if (TheCondState.TheCond != StartingCondState.TheCond ||
656 TheCondState.Ignore != StartingCondState.Ignore)
657 return TokError("unmatched .ifs or .elses");
659 // Check to see there are no empty DwarfFile slots.
660 const auto &LineTables = getContext().getMCDwarfLineTables();
661 if (!LineTables.empty()) {
663 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
664 if (File.Name.empty() && Index != 0)
665 TokError("unassigned file number: " + Twine(Index) +
666 " for .file directives");
671 // Check to see that all assembler local symbols were actually defined.
672 // Targets that don't do subsections via symbols may not want this, though,
673 // so conservatively exclude them. Only do this if we're finalizing, though,
674 // as otherwise we won't necessarilly have seen everything yet.
675 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
676 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
677 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
680 MCSymbol *Sym = i->getValue();
681 // Variable symbols may not be marked as defined, so check those
682 // explicitly. If we know it's a variable, we have a definition for
683 // the purposes of this check.
684 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
685 // FIXME: We would really like to refer back to where the symbol was
686 // first referenced for a source location. We need to add something
687 // to track that. Currently, we just point to the end of the file.
689 getLexer().getLoc(), SourceMgr::DK_Error,
690 "assembler local symbol '" + Sym->getName() + "' not defined");
694 // Finalize the output stream if there are no errors and if the client wants
696 if (!HadError && !NoFinalize)
702 void AsmParser::checkForValidSection() {
703 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
704 TokError("expected section directive before assembly directive");
709 /// \brief Throw away the rest of the line for testing purposes.
710 void AsmParser::eatToEndOfStatement() {
711 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
715 if (Lexer.is(AsmToken::EndOfStatement))
719 StringRef AsmParser::parseStringToEndOfStatement() {
720 const char *Start = getTok().getLoc().getPointer();
722 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
725 const char *End = getTok().getLoc().getPointer();
726 return StringRef(Start, End - Start);
729 StringRef AsmParser::parseStringToComma() {
730 const char *Start = getTok().getLoc().getPointer();
732 while (Lexer.isNot(AsmToken::EndOfStatement) &&
733 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
736 const char *End = getTok().getLoc().getPointer();
737 return StringRef(Start, End - Start);
740 /// \brief Parse a paren expression and return it.
741 /// NOTE: This assumes the leading '(' has already been consumed.
743 /// parenexpr ::= expr)
745 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (parseExpression(Res))
748 if (Lexer.isNot(AsmToken::RParen))
749 return TokError("expected ')' in parentheses expression");
750 EndLoc = Lexer.getTok().getEndLoc();
755 /// \brief Parse a bracket expression and return it.
756 /// NOTE: This assumes the leading '[' has already been consumed.
758 /// bracketexpr ::= expr]
760 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
761 if (parseExpression(Res))
763 if (Lexer.isNot(AsmToken::RBrac))
764 return TokError("expected ']' in brackets expression");
765 EndLoc = Lexer.getTok().getEndLoc();
770 /// \brief Parse a primary expression and return it.
771 /// primaryexpr ::= (parenexpr
772 /// primaryexpr ::= symbol
773 /// primaryexpr ::= number
774 /// primaryexpr ::= '.'
775 /// primaryexpr ::= ~,+,- primaryexpr
776 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
777 SMLoc FirstTokenLoc = getLexer().getLoc();
778 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
779 switch (FirstTokenKind) {
781 return TokError("unknown token in expression");
782 // If we have an error assume that we've already handled it.
783 case AsmToken::Error:
785 case AsmToken::Exclaim:
786 Lex(); // Eat the operator.
787 if (parsePrimaryExpr(Res, EndLoc))
789 Res = MCUnaryExpr::CreateLNot(Res, getContext());
791 case AsmToken::Dollar:
793 case AsmToken::String:
794 case AsmToken::Identifier: {
795 StringRef Identifier;
796 if (parseIdentifier(Identifier)) {
797 if (FirstTokenKind == AsmToken::Dollar) {
798 if (Lexer.getMAI().getDollarIsPC()) {
799 // This is a '$' reference, which references the current PC. Emit a
800 // temporary label to the streamer and refer to it.
801 MCSymbol *Sym = Ctx.CreateTempSymbol();
803 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
805 EndLoc = FirstTokenLoc;
808 return Error(FirstTokenLoc, "invalid token in expression");
811 // Parse symbol variant
812 std::pair<StringRef, StringRef> Split;
813 if (!MAI.useParensForSymbolVariant()) {
814 Split = Identifier.split('@');
815 } else if (Lexer.is(AsmToken::LParen)) {
816 Lexer.Lex(); // eat (
818 parseIdentifier(VName);
819 if (Lexer.isNot(AsmToken::RParen)) {
820 return Error(Lexer.getTok().getLoc(),
821 "unexpected token in variant, expected ')'");
823 Lexer.Lex(); // eat )
824 Split = std::make_pair(Identifier, VName);
827 EndLoc = SMLoc::getFromPointer(Identifier.end());
829 // This is a symbol reference.
830 StringRef SymbolName = Identifier;
831 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
833 // Lookup the symbol variant if used.
834 if (Split.second.size()) {
835 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
836 if (Variant != MCSymbolRefExpr::VK_Invalid) {
837 SymbolName = Split.first;
838 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
839 Variant = MCSymbolRefExpr::VK_None;
841 return Error(SMLoc::getFromPointer(Split.second.begin()),
842 "invalid variant '" + Split.second + "'");
846 MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
848 // If this is an absolute variable reference, substitute it now to preserve
849 // semantics in the face of reassignment.
850 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
852 return Error(EndLoc, "unexpected modifier on variable reference");
854 Res = Sym->getVariableValue();
858 // Otherwise create a symbol ref.
859 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
862 case AsmToken::BigNum:
863 return TokError("literal value out of range for directive");
864 case AsmToken::Integer: {
865 SMLoc Loc = getTok().getLoc();
866 int64_t IntVal = getTok().getIntVal();
867 Res = MCConstantExpr::Create(IntVal, getContext());
868 EndLoc = Lexer.getTok().getEndLoc();
870 // Look for 'b' or 'f' following an Integer as a directional label
871 if (Lexer.getKind() == AsmToken::Identifier) {
872 StringRef IDVal = getTok().getString();
873 // Lookup the symbol variant if used.
874 std::pair<StringRef, StringRef> Split = IDVal.split('@');
875 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
876 if (Split.first.size() != IDVal.size()) {
877 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
878 if (Variant == MCSymbolRefExpr::VK_Invalid)
879 return TokError("invalid variant '" + Split.second + "'");
882 if (IDVal == "f" || IDVal == "b") {
884 Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
885 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
886 if (IDVal == "b" && Sym->isUndefined())
887 return Error(Loc, "invalid reference to undefined symbol");
888 EndLoc = Lexer.getTok().getEndLoc();
889 Lex(); // Eat identifier.
894 case AsmToken::Real: {
895 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
896 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
897 Res = MCConstantExpr::Create(IntVal, getContext());
898 EndLoc = Lexer.getTok().getEndLoc();
902 case AsmToken::Dot: {
903 // This is a '.' reference, which references the current PC. Emit a
904 // temporary label to the streamer and refer to it.
905 MCSymbol *Sym = Ctx.CreateTempSymbol();
907 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
908 EndLoc = Lexer.getTok().getEndLoc();
909 Lex(); // Eat identifier.
912 case AsmToken::LParen:
913 Lex(); // Eat the '('.
914 return parseParenExpr(Res, EndLoc);
915 case AsmToken::LBrac:
916 if (!PlatformParser->HasBracketExpressions())
917 return TokError("brackets expression not supported on this target");
918 Lex(); // Eat the '['.
919 return parseBracketExpr(Res, EndLoc);
920 case AsmToken::Minus:
921 Lex(); // Eat the operator.
922 if (parsePrimaryExpr(Res, EndLoc))
924 Res = MCUnaryExpr::CreateMinus(Res, getContext());
927 Lex(); // Eat the operator.
928 if (parsePrimaryExpr(Res, EndLoc))
930 Res = MCUnaryExpr::CreatePlus(Res, getContext());
932 case AsmToken::Tilde:
933 Lex(); // Eat the operator.
934 if (parsePrimaryExpr(Res, EndLoc))
936 Res = MCUnaryExpr::CreateNot(Res, getContext());
941 bool AsmParser::parseExpression(const MCExpr *&Res) {
943 return parseExpression(Res, EndLoc);
947 AsmParser::applyModifierToExpr(const MCExpr *E,
948 MCSymbolRefExpr::VariantKind Variant) {
949 // Ask the target implementation about this expression first.
950 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
953 // Recurse over the given expression, rebuilding it to apply the given variant
954 // if there is exactly one symbol.
955 switch (E->getKind()) {
957 case MCExpr::Constant:
960 case MCExpr::SymbolRef: {
961 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
963 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
964 TokError("invalid variant on expression '" + getTok().getIdentifier() +
965 "' (already modified)");
969 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
972 case MCExpr::Unary: {
973 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
974 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
977 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
980 case MCExpr::Binary: {
981 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
982 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
983 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
993 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
997 llvm_unreachable("Invalid expression kind!");
1000 /// \brief Parse an expression and return it.
1002 /// expr ::= expr &&,|| expr -> lowest.
1003 /// expr ::= expr |,^,&,! expr
1004 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1005 /// expr ::= expr <<,>> expr
1006 /// expr ::= expr +,- expr
1007 /// expr ::= expr *,/,% expr -> highest.
1008 /// expr ::= primaryexpr
1010 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1011 // Parse the expression.
1013 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1016 // As a special case, we support 'a op b @ modifier' by rewriting the
1017 // expression to include the modifier. This is inefficient, but in general we
1018 // expect users to use 'a@modifier op b'.
1019 if (Lexer.getKind() == AsmToken::At) {
1022 if (Lexer.isNot(AsmToken::Identifier))
1023 return TokError("unexpected symbol modifier following '@'");
1025 MCSymbolRefExpr::VariantKind Variant =
1026 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1027 if (Variant == MCSymbolRefExpr::VK_Invalid)
1028 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1030 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1032 return TokError("invalid modifier '" + getTok().getIdentifier() +
1033 "' (no symbols present)");
1040 // Try to constant fold it up front, if possible.
1042 if (Res->EvaluateAsAbsolute(Value))
1043 Res = MCConstantExpr::Create(Value, getContext());
1048 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1050 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1053 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1056 SMLoc StartLoc = Lexer.getLoc();
1057 if (parseExpression(Expr))
1060 if (!Expr->EvaluateAsAbsolute(Res))
1061 return Error(StartLoc, "expected absolute expression");
1066 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
1067 MCBinaryExpr::Opcode &Kind) {
1070 return 0; // not a binop.
1072 // Lowest Precedence: &&, ||
1073 case AsmToken::AmpAmp:
1074 Kind = MCBinaryExpr::LAnd;
1076 case AsmToken::PipePipe:
1077 Kind = MCBinaryExpr::LOr;
1080 // Low Precedence: |, &, ^
1082 // FIXME: gas seems to support '!' as an infix operator?
1083 case AsmToken::Pipe:
1084 Kind = MCBinaryExpr::Or;
1086 case AsmToken::Caret:
1087 Kind = MCBinaryExpr::Xor;
1090 Kind = MCBinaryExpr::And;
1093 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1094 case AsmToken::EqualEqual:
1095 Kind = MCBinaryExpr::EQ;
1097 case AsmToken::ExclaimEqual:
1098 case AsmToken::LessGreater:
1099 Kind = MCBinaryExpr::NE;
1101 case AsmToken::Less:
1102 Kind = MCBinaryExpr::LT;
1104 case AsmToken::LessEqual:
1105 Kind = MCBinaryExpr::LTE;
1107 case AsmToken::Greater:
1108 Kind = MCBinaryExpr::GT;
1110 case AsmToken::GreaterEqual:
1111 Kind = MCBinaryExpr::GTE;
1114 // Intermediate Precedence: <<, >>
1115 case AsmToken::LessLess:
1116 Kind = MCBinaryExpr::Shl;
1118 case AsmToken::GreaterGreater:
1119 Kind = MCBinaryExpr::Shr;
1122 // High Intermediate Precedence: +, -
1123 case AsmToken::Plus:
1124 Kind = MCBinaryExpr::Add;
1126 case AsmToken::Minus:
1127 Kind = MCBinaryExpr::Sub;
1130 // Highest Precedence: *, /, %
1131 case AsmToken::Star:
1132 Kind = MCBinaryExpr::Mul;
1134 case AsmToken::Slash:
1135 Kind = MCBinaryExpr::Div;
1137 case AsmToken::Percent:
1138 Kind = MCBinaryExpr::Mod;
1143 /// \brief Parse all binary operators with precedence >= 'Precedence'.
1144 /// Res contains the LHS of the expression on input.
1145 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1148 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1149 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1151 // If the next token is lower precedence than we are allowed to eat, return
1152 // successfully with what we ate already.
1153 if (TokPrec < Precedence)
1158 // Eat the next primary expression.
1160 if (parsePrimaryExpr(RHS, EndLoc))
1163 // If BinOp binds less tightly with RHS than the operator after RHS, let
1164 // the pending operator take RHS as its LHS.
1165 MCBinaryExpr::Opcode Dummy;
1166 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1167 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1170 // Merge LHS and RHS according to operator.
1171 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
1176 /// ::= EndOfStatement
1177 /// ::= Label* Directive ...Operands... EndOfStatement
1178 /// ::= Label* Identifier OperandList* EndOfStatement
1179 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
1180 if (Lexer.is(AsmToken::EndOfStatement)) {
1186 // Statements always start with an identifier or are a full line comment.
1187 AsmToken ID = getTok();
1188 SMLoc IDLoc = ID.getLoc();
1190 int64_t LocalLabelVal = -1;
1191 // A full line comment is a '#' as the first token.
1192 if (Lexer.is(AsmToken::Hash))
1193 return parseCppHashLineFilenameComment(IDLoc);
1195 // Allow an integer followed by a ':' as a directional local label.
1196 if (Lexer.is(AsmToken::Integer)) {
1197 LocalLabelVal = getTok().getIntVal();
1198 if (LocalLabelVal < 0) {
1199 if (!TheCondState.Ignore)
1200 return TokError("unexpected token at start of statement");
1203 IDVal = getTok().getString();
1204 Lex(); // Consume the integer token to be used as an identifier token.
1205 if (Lexer.getKind() != AsmToken::Colon) {
1206 if (!TheCondState.Ignore)
1207 return TokError("unexpected token at start of statement");
1210 } else if (Lexer.is(AsmToken::Dot)) {
1211 // Treat '.' as a valid identifier in this context.
1214 } else if (parseIdentifier(IDVal)) {
1215 if (!TheCondState.Ignore)
1216 return TokError("unexpected token at start of statement");
1220 // Handle conditional assembly here before checking for skipping. We
1221 // have to do this so that .endif isn't skipped in a ".if 0" block for
1223 StringMap<DirectiveKind>::const_iterator DirKindIt =
1224 DirectiveKindMap.find(IDVal);
1225 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1227 : DirKindIt->getValue();
1233 return parseDirectiveIf(IDLoc);
1235 return parseDirectiveIfb(IDLoc, true);
1237 return parseDirectiveIfb(IDLoc, false);
1239 return parseDirectiveIfc(IDLoc, true);
1241 return parseDirectiveIfeqs(IDLoc);
1243 return parseDirectiveIfc(IDLoc, false);
1245 return parseDirectiveIfdef(IDLoc, true);
1248 return parseDirectiveIfdef(IDLoc, false);
1250 return parseDirectiveElseIf(IDLoc);
1252 return parseDirectiveElse(IDLoc);
1254 return parseDirectiveEndIf(IDLoc);
1257 // Ignore the statement if in the middle of inactive conditional
1259 if (TheCondState.Ignore) {
1260 eatToEndOfStatement();
1264 // FIXME: Recurse on local labels?
1266 // See what kind of statement we have.
1267 switch (Lexer.getKind()) {
1268 case AsmToken::Colon: {
1269 checkForValidSection();
1271 // identifier ':' -> Label.
1274 // Diagnose attempt to use '.' as a label.
1276 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1278 // Diagnose attempt to use a variable as a label.
1280 // FIXME: Diagnostics. Note the location of the definition as a label.
1281 // FIXME: This doesn't diagnose assignment to a symbol which has been
1282 // implicitly marked as external.
1284 if (LocalLabelVal == -1)
1285 Sym = getContext().GetOrCreateSymbol(IDVal);
1287 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
1288 if (!Sym->isUndefined() || Sym->isVariable())
1289 return Error(IDLoc, "invalid symbol redefinition");
1292 if (!ParsingInlineAsm)
1295 // If we are generating dwarf for assembly source files then gather the
1296 // info to make a dwarf label entry for this label if needed.
1297 if (getContext().getGenDwarfForAssembly())
1298 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1301 getTargetParser().onLabelParsed(Sym);
1303 // Consume any end of statement token, if present, to avoid spurious
1304 // AddBlankLine calls().
1305 if (Lexer.is(AsmToken::EndOfStatement)) {
1307 if (Lexer.is(AsmToken::Eof))
1314 case AsmToken::Equal:
1315 // identifier '=' ... -> assignment statement
1318 return parseAssignment(IDVal, true);
1320 default: // Normal instruction or directive.
1324 // If macros are enabled, check to see if this is a macro instantiation.
1325 if (areMacrosEnabled())
1326 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1327 return handleMacroEntry(M, IDLoc);
1330 // Otherwise, we have a normal instruction or directive.
1332 // Directives start with "."
1333 if (IDVal[0] == '.' && IDVal != ".") {
1334 // There are several entities interested in parsing directives:
1336 // 1. The target-specific assembly parser. Some directives are target
1337 // specific or may potentially behave differently on certain targets.
1338 // 2. Asm parser extensions. For example, platform-specific parsers
1339 // (like the ELF parser) register themselves as extensions.
1340 // 3. The generic directive parser implemented by this class. These are
1341 // all the directives that behave in a target and platform independent
1342 // manner, or at least have a default behavior that's shared between
1343 // all targets and platforms.
1345 // First query the target-specific parser. It will return 'true' if it
1346 // isn't interested in this directive.
1347 if (!getTargetParser().ParseDirective(ID))
1350 // Next, check the extension directive map to see if any extension has
1351 // registered itself to parse this directive.
1352 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1353 ExtensionDirectiveMap.lookup(IDVal);
1355 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1357 // Finally, if no one else is interested in this directive, it must be
1358 // generic and familiar to this class.
1364 return parseDirectiveSet(IDVal, true);
1366 return parseDirectiveSet(IDVal, false);
1368 return parseDirectiveAscii(IDVal, false);
1371 return parseDirectiveAscii(IDVal, true);
1373 return parseDirectiveValue(1);
1377 return parseDirectiveValue(2);
1381 return parseDirectiveValue(4);
1384 return parseDirectiveValue(8);
1386 return parseDirectiveOctaValue();
1389 return parseDirectiveRealValue(APFloat::IEEEsingle);
1391 return parseDirectiveRealValue(APFloat::IEEEdouble);
1393 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1394 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1397 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1398 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1401 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1403 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1405 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1407 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1409 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1411 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1413 return parseDirectiveOrg();
1415 return parseDirectiveFill();
1417 return parseDirectiveZero();
1419 eatToEndOfStatement(); // .extern is the default, ignore it.
1423 return parseDirectiveSymbolAttribute(MCSA_Global);
1424 case DK_LAZY_REFERENCE:
1425 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1426 case DK_NO_DEAD_STRIP:
1427 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1428 case DK_SYMBOL_RESOLVER:
1429 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1430 case DK_PRIVATE_EXTERN:
1431 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1433 return parseDirectiveSymbolAttribute(MCSA_Reference);
1434 case DK_WEAK_DEFINITION:
1435 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1436 case DK_WEAK_REFERENCE:
1437 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1438 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1439 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1442 return parseDirectiveComm(/*IsLocal=*/false);
1444 return parseDirectiveComm(/*IsLocal=*/true);
1446 return parseDirectiveAbort();
1448 return parseDirectiveInclude();
1450 return parseDirectiveIncbin();
1453 return TokError(Twine(IDVal) + " not supported yet");
1455 return parseDirectiveRept(IDLoc, IDVal);
1457 return parseDirectiveIrp(IDLoc);
1459 return parseDirectiveIrpc(IDLoc);
1461 return parseDirectiveEndr(IDLoc);
1462 case DK_BUNDLE_ALIGN_MODE:
1463 return parseDirectiveBundleAlignMode();
1464 case DK_BUNDLE_LOCK:
1465 return parseDirectiveBundleLock();
1466 case DK_BUNDLE_UNLOCK:
1467 return parseDirectiveBundleUnlock();
1469 return parseDirectiveLEB128(true);
1471 return parseDirectiveLEB128(false);
1474 return parseDirectiveSpace(IDVal);
1476 return parseDirectiveFile(IDLoc);
1478 return parseDirectiveLine();
1480 return parseDirectiveLoc();
1482 return parseDirectiveStabs();
1483 case DK_CFI_SECTIONS:
1484 return parseDirectiveCFISections();
1485 case DK_CFI_STARTPROC:
1486 return parseDirectiveCFIStartProc();
1487 case DK_CFI_ENDPROC:
1488 return parseDirectiveCFIEndProc();
1489 case DK_CFI_DEF_CFA:
1490 return parseDirectiveCFIDefCfa(IDLoc);
1491 case DK_CFI_DEF_CFA_OFFSET:
1492 return parseDirectiveCFIDefCfaOffset();
1493 case DK_CFI_ADJUST_CFA_OFFSET:
1494 return parseDirectiveCFIAdjustCfaOffset();
1495 case DK_CFI_DEF_CFA_REGISTER:
1496 return parseDirectiveCFIDefCfaRegister(IDLoc);
1498 return parseDirectiveCFIOffset(IDLoc);
1499 case DK_CFI_REL_OFFSET:
1500 return parseDirectiveCFIRelOffset(IDLoc);
1501 case DK_CFI_PERSONALITY:
1502 return parseDirectiveCFIPersonalityOrLsda(true);
1504 return parseDirectiveCFIPersonalityOrLsda(false);
1505 case DK_CFI_REMEMBER_STATE:
1506 return parseDirectiveCFIRememberState();
1507 case DK_CFI_RESTORE_STATE:
1508 return parseDirectiveCFIRestoreState();
1509 case DK_CFI_SAME_VALUE:
1510 return parseDirectiveCFISameValue(IDLoc);
1511 case DK_CFI_RESTORE:
1512 return parseDirectiveCFIRestore(IDLoc);
1514 return parseDirectiveCFIEscape();
1515 case DK_CFI_SIGNAL_FRAME:
1516 return parseDirectiveCFISignalFrame();
1517 case DK_CFI_UNDEFINED:
1518 return parseDirectiveCFIUndefined(IDLoc);
1519 case DK_CFI_REGISTER:
1520 return parseDirectiveCFIRegister(IDLoc);
1521 case DK_CFI_WINDOW_SAVE:
1522 return parseDirectiveCFIWindowSave();
1525 return parseDirectiveMacrosOnOff(IDVal);
1527 return parseDirectiveMacro(IDLoc);
1530 return parseDirectiveEndMacro(IDVal);
1532 return parseDirectivePurgeMacro(IDLoc);
1534 return parseDirectiveEnd(IDLoc);
1536 return parseDirectiveError(IDLoc, false);
1538 return parseDirectiveError(IDLoc, true);
1541 return Error(IDLoc, "unknown directive");
1544 // __asm _emit or __asm __emit
1545 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1546 IDVal == "_EMIT" || IDVal == "__EMIT"))
1547 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1550 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1551 return parseDirectiveMSAlign(IDLoc, Info);
1553 checkForValidSection();
1555 // Canonicalize the opcode to lower case.
1556 std::string OpcodeStr = IDVal.lower();
1557 ParseInstructionInfo IInfo(Info.AsmRewrites);
1558 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
1559 Info.ParsedOperands);
1560 Info.ParseError = HadError;
1562 // Dump the parsed representation, if requested.
1563 if (getShowParsedOperands()) {
1564 SmallString<256> Str;
1565 raw_svector_ostream OS(Str);
1566 OS << "parsed instruction: [";
1567 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
1570 Info.ParsedOperands[i]->print(OS);
1574 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
1577 // If we are generating dwarf for assembly source files and the current
1578 // section is the initial text section then generate a .loc directive for
1580 if (!HadError && getContext().getGenDwarfForAssembly() &&
1581 getContext().getGenDwarfSection() ==
1582 getStreamer().getCurrentSection().first) {
1584 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1586 // If we previously parsed a cpp hash file line comment then make sure the
1587 // current Dwarf File is for the CppHashFilename if not then emit the
1588 // Dwarf File table for it and adjust the line number for the .loc.
1589 if (CppHashFilename.size() != 0) {
1590 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1591 0, StringRef(), CppHashFilename);
1592 getContext().setGenDwarfFileNumber(FileNumber);
1594 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1595 // cache with the different Loc from the call above we save the last
1596 // info we queried here with SrcMgr.FindLineNumber().
1597 unsigned CppHashLocLineNo;
1598 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1599 CppHashLocLineNo = LastQueryLine;
1601 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1602 LastQueryLine = CppHashLocLineNo;
1603 LastQueryIDLoc = CppHashLoc;
1604 LastQueryBuffer = CppHashBuf;
1606 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1609 getStreamer().EmitDwarfLocDirective(
1610 getContext().getGenDwarfFileNumber(), Line, 0,
1611 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1615 // If parsing succeeded, match the instruction.
1618 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1619 Info.ParsedOperands, Out,
1620 ErrorInfo, ParsingInlineAsm);
1623 // Don't skip the rest of the line, the instruction parser is responsible for
1628 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1629 /// since they may not be able to be tokenized to get to the end of line token.
1630 void AsmParser::eatToEndOfLine() {
1631 if (!Lexer.is(AsmToken::EndOfStatement))
1632 Lexer.LexUntilEndOfLine();
1637 /// parseCppHashLineFilenameComment as this:
1638 /// ::= # number "filename"
1639 /// or just as a full line comment if it doesn't have a number and a string.
1640 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
1641 Lex(); // Eat the hash token.
1643 if (getLexer().isNot(AsmToken::Integer)) {
1644 // Consume the line since in cases it is not a well-formed line directive,
1645 // as if were simply a full line comment.
1650 int64_t LineNumber = getTok().getIntVal();
1653 if (getLexer().isNot(AsmToken::String)) {
1658 StringRef Filename = getTok().getString();
1659 // Get rid of the enclosing quotes.
1660 Filename = Filename.substr(1, Filename.size() - 2);
1662 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1664 CppHashFilename = Filename;
1665 CppHashLineNumber = LineNumber;
1666 CppHashBuf = CurBuffer;
1668 // Ignore any trailing characters, they're just comment.
1673 /// \brief will use the last parsed cpp hash line filename comment
1674 /// for the Filename and LineNo if any in the diagnostic.
1675 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1676 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
1677 raw_ostream &OS = errs();
1679 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1680 const SMLoc &DiagLoc = Diag.getLoc();
1681 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1682 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1684 // Like SourceMgr::printMessage() we need to print the include stack if any
1685 // before printing the message.
1686 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1687 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
1688 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1689 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1692 // If we have not parsed a cpp hash line filename comment or the source
1693 // manager changed or buffer changed (like in a nested include) then just
1694 // print the normal diagnostic using its Filename and LineNo.
1695 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
1696 DiagBuf != CppHashBuf) {
1697 if (Parser->SavedDiagHandler)
1698 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1700 Diag.print(nullptr, OS);
1704 // Use the CppHashFilename and calculate a line number based on the
1705 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1707 const std::string &Filename = Parser->CppHashFilename;
1709 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1710 int CppHashLocLineNo =
1711 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1713 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
1715 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1716 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
1717 Diag.getLineContents(), Diag.getRanges());
1719 if (Parser->SavedDiagHandler)
1720 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1722 NewDiag.print(nullptr, OS);
1725 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1726 // difference being that that function accepts '@' as part of identifiers and
1727 // we can't do that. AsmLexer.cpp should probably be changed to handle
1728 // '@' as a special case when needed.
1729 static bool isIdentifierChar(char c) {
1730 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1734 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
1735 ArrayRef<MCAsmMacroParameter> Parameters,
1736 ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
1737 unsigned NParameters = Parameters.size();
1738 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
1739 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
1740 return Error(L, "Wrong number of arguments");
1742 // A macro without parameters is handled differently on Darwin:
1743 // gas accepts no arguments and does no substitutions
1744 while (!Body.empty()) {
1745 // Scan for the next substitution.
1746 std::size_t End = Body.size(), Pos = 0;
1747 for (; Pos != End; ++Pos) {
1748 // Check for a substitution or escape.
1749 if (IsDarwin && !NParameters) {
1750 // This macro has no parameters, look for $0, $1, etc.
1751 if (Body[Pos] != '$' || Pos + 1 == End)
1754 char Next = Body[Pos + 1];
1755 if (Next == '$' || Next == 'n' ||
1756 isdigit(static_cast<unsigned char>(Next)))
1759 // This macro has parameters, look for \foo, \bar, etc.
1760 if (Body[Pos] == '\\' && Pos + 1 != End)
1766 OS << Body.slice(0, Pos);
1768 // Check if we reached the end.
1772 if (IsDarwin && !NParameters) {
1773 switch (Body[Pos + 1]) {
1779 // $n => number of arguments
1784 // $[0-9] => argument
1786 // Missing arguments are ignored.
1787 unsigned Index = Body[Pos + 1] - '0';
1788 if (Index >= A.size())
1791 // Otherwise substitute with the token values, with spaces eliminated.
1792 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1793 ie = A[Index].end();
1795 OS << it->getString();
1801 unsigned I = Pos + 1;
1802 while (isIdentifierChar(Body[I]) && I + 1 != End)
1805 const char *Begin = Body.data() + Pos + 1;
1806 StringRef Argument(Begin, I - (Pos + 1));
1808 for (; Index < NParameters; ++Index)
1809 if (Parameters[Index].Name == Argument)
1812 if (Index == NParameters) {
1813 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1816 OS << '\\' << Argument;
1820 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1821 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1822 ie = A[Index].end();
1824 // We expect no quotes around the string's contents when
1825 // parsing for varargs.
1826 if (it->getKind() != AsmToken::String || VarargParameter)
1827 OS << it->getString();
1829 OS << it->getStringContents();
1831 Pos += 1 + Argument.size();
1834 // Update the scan point.
1835 Body = Body.substr(Pos);
1841 MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB,
1842 SMLoc EL, MemoryBuffer *I)
1843 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1846 static bool isOperator(AsmToken::TokenKind kind) {
1850 case AsmToken::Plus:
1851 case AsmToken::Minus:
1852 case AsmToken::Tilde:
1853 case AsmToken::Slash:
1854 case AsmToken::Star:
1856 case AsmToken::Equal:
1857 case AsmToken::EqualEqual:
1858 case AsmToken::Pipe:
1859 case AsmToken::PipePipe:
1860 case AsmToken::Caret:
1862 case AsmToken::AmpAmp:
1863 case AsmToken::Exclaim:
1864 case AsmToken::ExclaimEqual:
1865 case AsmToken::Percent:
1866 case AsmToken::Less:
1867 case AsmToken::LessEqual:
1868 case AsmToken::LessLess:
1869 case AsmToken::LessGreater:
1870 case AsmToken::Greater:
1871 case AsmToken::GreaterEqual:
1872 case AsmToken::GreaterGreater:
1878 class AsmLexerSkipSpaceRAII {
1880 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1881 Lexer.setSkipSpace(SkipSpace);
1884 ~AsmLexerSkipSpaceRAII() {
1885 Lexer.setSkipSpace(true);
1893 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1896 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1897 StringRef Str = parseStringToEndOfStatement();
1898 MA.push_back(AsmToken(AsmToken::String, Str));
1903 unsigned ParenLevel = 0;
1904 unsigned AddTokens = 0;
1906 // Darwin doesn't use spaces to delmit arguments.
1907 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
1910 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1911 return TokError("unexpected token in macro instantiation");
1913 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1916 if (Lexer.is(AsmToken::Space)) {
1917 Lex(); // Eat spaces
1919 // Spaces can delimit parameters, but could also be part an expression.
1920 // If the token after a space is an operator, add the token and the next
1921 // one into this argument
1923 if (isOperator(Lexer.getKind())) {
1924 // Check to see whether the token is used as an operator,
1925 // or part of an identifier
1926 const char *NextChar = getTok().getEndLoc().getPointer();
1927 if (*NextChar == ' ')
1931 if (!AddTokens && ParenLevel == 0) {
1937 // handleMacroEntry relies on not advancing the lexer here
1938 // to be able to fill in the remaining default parameter values
1939 if (Lexer.is(AsmToken::EndOfStatement))
1942 // Adjust the current parentheses level.
1943 if (Lexer.is(AsmToken::LParen))
1945 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1948 // Append the token to the current argument list.
1949 MA.push_back(getTok());
1955 if (ParenLevel != 0)
1956 return TokError("unbalanced parentheses in macro argument");
1960 // Parse the macro instantiation arguments.
1961 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
1962 MCAsmMacroArguments &A) {
1963 const unsigned NParameters = M ? M->Parameters.size() : 0;
1964 bool NamedParametersFound = false;
1965 SmallVector<SMLoc, 4> FALocs;
1967 A.resize(NParameters);
1968 FALocs.resize(NParameters);
1970 // Parse two kinds of macro invocations:
1971 // - macros defined without any parameters accept an arbitrary number of them
1972 // - macros defined with parameters accept at most that many of them
1973 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
1974 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1976 SMLoc IDLoc = Lexer.getLoc();
1977 MCAsmMacroParameter FA;
1979 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
1980 if (parseIdentifier(FA.Name)) {
1981 Error(IDLoc, "invalid argument identifier for formal argument");
1982 eatToEndOfStatement();
1986 if (!Lexer.is(AsmToken::Equal)) {
1987 TokError("expected '=' after formal parameter identifier");
1988 eatToEndOfStatement();
1993 NamedParametersFound = true;
1996 if (NamedParametersFound && FA.Name.empty()) {
1997 Error(IDLoc, "cannot mix positional and keyword arguments");
1998 eatToEndOfStatement();
2002 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2003 if (parseMacroArgument(FA.Value, Vararg))
2006 unsigned PI = Parameter;
2007 if (!FA.Name.empty()) {
2009 for (FAI = 0; FAI < NParameters; ++FAI)
2010 if (M->Parameters[FAI].Name == FA.Name)
2013 if (FAI >= NParameters) {
2014 assert(M && "expected macro to be defined");
2016 "parameter named '" + FA.Name + "' does not exist for macro '" +
2023 if (!FA.Value.empty()) {
2028 if (FALocs.size() <= PI)
2029 FALocs.resize(PI + 1);
2031 FALocs[PI] = Lexer.getLoc();
2034 // At the end of the statement, fill in remaining arguments that have
2035 // default values. If there aren't any, then the next argument is
2036 // required but missing
2037 if (Lexer.is(AsmToken::EndOfStatement)) {
2038 bool Failure = false;
2039 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2040 if (A[FAI].empty()) {
2041 if (M->Parameters[FAI].Required) {
2042 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2043 "missing value for required parameter "
2044 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2048 if (!M->Parameters[FAI].Value.empty())
2049 A[FAI] = M->Parameters[FAI].Value;
2055 if (Lexer.is(AsmToken::Comma))
2059 return TokError("too many positional arguments");
2062 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2063 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2064 return (I == MacroMap.end()) ? nullptr : I->getValue();
2067 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
2068 MacroMap[Name] = new MCAsmMacro(Macro);
2071 void AsmParser::undefineMacro(StringRef Name) {
2072 StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
2073 if (I != MacroMap.end()) {
2074 delete I->getValue();
2079 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2080 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2081 // this, although we should protect against infinite loops.
2082 if (ActiveMacros.size() == 20)
2083 return TokError("macros cannot be nested more than 20 levels deep");
2085 MCAsmMacroArguments A;
2086 if (parseMacroArguments(M, A))
2089 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2090 // to hold the macro body with substitutions.
2091 SmallString<256> Buf;
2092 StringRef Body = M->Body;
2093 raw_svector_ostream OS(Buf);
2095 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
2098 // We include the .endmacro in the buffer as our cue to exit the macro
2100 OS << ".endmacro\n";
2102 MemoryBuffer *Instantiation =
2103 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2105 // Create the macro instantiation object and add to the current macro
2106 // instantiation stack.
2107 MacroInstantiation *MI = new MacroInstantiation(
2108 M, NameLoc, CurBuffer, getTok().getLoc(), Instantiation);
2109 ActiveMacros.push_back(MI);
2111 // Jump to the macro instantiation and prime the lexer.
2112 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
2113 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
2119 void AsmParser::handleMacroExit() {
2120 // Jump to the EndOfStatement we should return to, and consume it.
2121 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2124 // Pop the instantiation entry.
2125 delete ActiveMacros.back();
2126 ActiveMacros.pop_back();
2129 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
2130 switch (Value->getKind()) {
2131 case MCExpr::Binary: {
2132 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
2133 return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
2135 case MCExpr::Target:
2136 case MCExpr::Constant:
2138 case MCExpr::SymbolRef: {
2140 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
2142 return isUsedIn(Sym, S.getVariableValue());
2146 return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
2149 llvm_unreachable("Unknown expr kind!");
2152 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2154 // FIXME: Use better location, we should use proper tokens.
2155 SMLoc EqualLoc = Lexer.getLoc();
2157 const MCExpr *Value;
2158 if (parseExpression(Value))
2161 // Note: we don't count b as used in "a = b". This is to allow
2165 if (Lexer.isNot(AsmToken::EndOfStatement))
2166 return TokError("unexpected token in assignment");
2168 // Eat the end of statement marker.
2171 // Validate that the LHS is allowed to be a variable (either it has not been
2172 // used as a symbol, or it is an absolute symbol).
2173 MCSymbol *Sym = getContext().LookupSymbol(Name);
2175 // Diagnose assignment to a label.
2177 // FIXME: Diagnostics. Note the location of the definition as a label.
2178 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
2179 if (isUsedIn(Sym, Value))
2180 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2181 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
2182 ; // Allow redefinitions of undefined symbols only used in directives.
2183 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2184 ; // Allow redefinitions of variables that haven't yet been used.
2185 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
2186 return Error(EqualLoc, "redefinition of '" + Name + "'");
2187 else if (!Sym->isVariable())
2188 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
2189 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
2190 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2193 // Don't count these checks as uses.
2194 Sym->setUsed(false);
2195 } else if (Name == ".") {
2196 if (Out.EmitValueToOffset(Value, 0)) {
2197 Error(EqualLoc, "expected absolute expression");
2198 eatToEndOfStatement();
2202 Sym = getContext().GetOrCreateSymbol(Name);
2204 // Do the assignment.
2205 Out.EmitAssignment(Sym, Value);
2207 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2212 /// parseIdentifier:
2215 bool AsmParser::parseIdentifier(StringRef &Res) {
2216 // The assembler has relaxed rules for accepting identifiers, in particular we
2217 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2218 // separate tokens. At this level, we have already lexed so we cannot (currently)
2219 // handle this as a context dependent token, instead we detect adjacent tokens
2220 // and return the combined identifier.
2221 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2222 SMLoc PrefixLoc = getLexer().getLoc();
2224 // Consume the prefix character, and check for a following identifier.
2226 if (Lexer.isNot(AsmToken::Identifier))
2229 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2230 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2233 // Construct the joined identifier and consume the token.
2235 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2240 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2243 Res = getTok().getIdentifier();
2245 Lex(); // Consume the identifier token.
2250 /// parseDirectiveSet:
2251 /// ::= .equ identifier ',' expression
2252 /// ::= .equiv identifier ',' expression
2253 /// ::= .set identifier ',' expression
2254 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2257 if (parseIdentifier(Name))
2258 return TokError("expected identifier after '" + Twine(IDVal) + "'");
2260 if (getLexer().isNot(AsmToken::Comma))
2261 return TokError("unexpected token in '" + Twine(IDVal) + "'");
2264 return parseAssignment(Name, allow_redef, true);
2267 bool AsmParser::parseEscapedString(std::string &Data) {
2268 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
2271 StringRef Str = getTok().getStringContents();
2272 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2273 if (Str[i] != '\\') {
2278 // Recognize escaped characters. Note that this escape semantics currently
2279 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2282 return TokError("unexpected backslash at end of string");
2284 // Recognize octal sequences.
2285 if ((unsigned)(Str[i] - '0') <= 7) {
2286 // Consume up to three octal characters.
2287 unsigned Value = Str[i] - '0';
2289 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2291 Value = Value * 8 + (Str[i] - '0');
2293 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2295 Value = Value * 8 + (Str[i] - '0');
2300 return TokError("invalid octal escape sequence (out of range)");
2302 Data += (unsigned char)Value;
2306 // Otherwise recognize individual escapes.
2309 // Just reject invalid escape sequences for now.
2310 return TokError("invalid escape sequence (unrecognized character)");
2312 case 'b': Data += '\b'; break;
2313 case 'f': Data += '\f'; break;
2314 case 'n': Data += '\n'; break;
2315 case 'r': Data += '\r'; break;
2316 case 't': Data += '\t'; break;
2317 case '"': Data += '"'; break;
2318 case '\\': Data += '\\'; break;
2325 /// parseDirectiveAscii:
2326 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2327 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2328 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2329 checkForValidSection();
2332 if (getLexer().isNot(AsmToken::String))
2333 return TokError("expected string in '" + Twine(IDVal) + "' directive");
2336 if (parseEscapedString(Data))
2339 getStreamer().EmitBytes(Data);
2341 getStreamer().EmitBytes(StringRef("\0", 1));
2345 if (getLexer().is(AsmToken::EndOfStatement))
2348 if (getLexer().isNot(AsmToken::Comma))
2349 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2358 /// parseDirectiveValue
2359 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2360 bool AsmParser::parseDirectiveValue(unsigned Size) {
2361 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2362 checkForValidSection();
2365 const MCExpr *Value;
2366 SMLoc ExprLoc = getLexer().getLoc();
2367 if (parseExpression(Value))
2370 // Special case constant expressions to match code generator.
2371 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2372 assert(Size <= 8 && "Invalid size");
2373 uint64_t IntValue = MCE->getValue();
2374 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2375 return Error(ExprLoc, "literal value out of range for directive");
2376 getStreamer().EmitIntValue(IntValue, Size);
2378 getStreamer().EmitValue(Value, Size, ExprLoc);
2380 if (getLexer().is(AsmToken::EndOfStatement))
2383 // FIXME: Improve diagnostic.
2384 if (getLexer().isNot(AsmToken::Comma))
2385 return TokError("unexpected token in directive");
2394 /// ParseDirectiveOctaValue
2395 /// ::= .octa [ hexconstant (, hexconstant)* ]
2396 bool AsmParser::parseDirectiveOctaValue() {
2397 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2398 checkForValidSection();
2401 if (Lexer.getKind() == AsmToken::Error)
2403 if (Lexer.getKind() != AsmToken::Integer &&
2404 Lexer.getKind() != AsmToken::BigNum)
2405 return TokError("unknown token in expression");
2407 SMLoc ExprLoc = getLexer().getLoc();
2408 APInt IntValue = getTok().getAPIntVal();
2412 if (IntValue.isIntN(64)) {
2414 lo = IntValue.getZExtValue();
2415 } else if (IntValue.isIntN(128)) {
2416 // It might actually have more than 128 bits, but the top ones are zero.
2417 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2418 lo = IntValue.getLoBits(64).getZExtValue();
2420 return Error(ExprLoc, "literal value out of range for directive");
2422 if (MAI.isLittleEndian()) {
2423 getStreamer().EmitIntValue(lo, 8);
2424 getStreamer().EmitIntValue(hi, 8);
2426 getStreamer().EmitIntValue(hi, 8);
2427 getStreamer().EmitIntValue(lo, 8);
2430 if (getLexer().is(AsmToken::EndOfStatement))
2433 // FIXME: Improve diagnostic.
2434 if (getLexer().isNot(AsmToken::Comma))
2435 return TokError("unexpected token in directive");
2444 /// parseDirectiveRealValue
2445 /// ::= (.single | .double) [ expression (, expression)* ]
2446 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
2447 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2448 checkForValidSection();
2451 // We don't truly support arithmetic on floating point expressions, so we
2452 // have to manually parse unary prefixes.
2454 if (getLexer().is(AsmToken::Minus)) {
2457 } else if (getLexer().is(AsmToken::Plus))
2460 if (getLexer().isNot(AsmToken::Integer) &&
2461 getLexer().isNot(AsmToken::Real) &&
2462 getLexer().isNot(AsmToken::Identifier))
2463 return TokError("unexpected token in directive");
2465 // Convert to an APFloat.
2466 APFloat Value(Semantics);
2467 StringRef IDVal = getTok().getString();
2468 if (getLexer().is(AsmToken::Identifier)) {
2469 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2470 Value = APFloat::getInf(Semantics);
2471 else if (!IDVal.compare_lower("nan"))
2472 Value = APFloat::getNaN(Semantics, false, ~0);
2474 return TokError("invalid floating point literal");
2475 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2476 APFloat::opInvalidOp)
2477 return TokError("invalid floating point literal");
2481 // Consume the numeric token.
2484 // Emit the value as an integer.
2485 APInt AsInt = Value.bitcastToAPInt();
2486 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2487 AsInt.getBitWidth() / 8);
2489 if (getLexer().is(AsmToken::EndOfStatement))
2492 if (getLexer().isNot(AsmToken::Comma))
2493 return TokError("unexpected token in directive");
2502 /// parseDirectiveZero
2503 /// ::= .zero expression
2504 bool AsmParser::parseDirectiveZero() {
2505 checkForValidSection();
2508 if (parseAbsoluteExpression(NumBytes))
2512 if (getLexer().is(AsmToken::Comma)) {
2514 if (parseAbsoluteExpression(Val))
2518 if (getLexer().isNot(AsmToken::EndOfStatement))
2519 return TokError("unexpected token in '.zero' directive");
2523 getStreamer().EmitFill(NumBytes, Val);
2528 /// parseDirectiveFill
2529 /// ::= .fill expression [ , expression [ , expression ] ]
2530 bool AsmParser::parseDirectiveFill() {
2531 checkForValidSection();
2533 SMLoc RepeatLoc = getLexer().getLoc();
2535 if (parseAbsoluteExpression(NumValues))
2538 if (NumValues < 0) {
2540 "'.fill' directive with negative repeat count has no effect");
2544 int64_t FillSize = 1;
2545 int64_t FillExpr = 0;
2547 SMLoc SizeLoc, ExprLoc;
2548 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2549 if (getLexer().isNot(AsmToken::Comma))
2550 return TokError("unexpected token in '.fill' directive");
2553 SizeLoc = getLexer().getLoc();
2554 if (parseAbsoluteExpression(FillSize))
2557 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2558 if (getLexer().isNot(AsmToken::Comma))
2559 return TokError("unexpected token in '.fill' directive");
2562 ExprLoc = getLexer().getLoc();
2563 if (parseAbsoluteExpression(FillExpr))
2566 if (getLexer().isNot(AsmToken::EndOfStatement))
2567 return TokError("unexpected token in '.fill' directive");
2574 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2578 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2582 if (!isUInt<32>(FillExpr) && FillSize > 4)
2583 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2585 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2586 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2588 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2589 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2590 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2596 /// parseDirectiveOrg
2597 /// ::= .org expression [ , expression ]
2598 bool AsmParser::parseDirectiveOrg() {
2599 checkForValidSection();
2601 const MCExpr *Offset;
2602 SMLoc Loc = getTok().getLoc();
2603 if (parseExpression(Offset))
2606 // Parse optional fill expression.
2607 int64_t FillExpr = 0;
2608 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2609 if (getLexer().isNot(AsmToken::Comma))
2610 return TokError("unexpected token in '.org' directive");
2613 if (parseAbsoluteExpression(FillExpr))
2616 if (getLexer().isNot(AsmToken::EndOfStatement))
2617 return TokError("unexpected token in '.org' directive");
2622 // Only limited forms of relocatable expressions are accepted here, it
2623 // has to be relative to the current section. The streamer will return
2624 // 'true' if the expression wasn't evaluatable.
2625 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2626 return Error(Loc, "expected assembly-time absolute expression");
2631 /// parseDirectiveAlign
2632 /// ::= {.align, ...} expression [ , expression [ , expression ]]
2633 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
2634 checkForValidSection();
2636 SMLoc AlignmentLoc = getLexer().getLoc();
2638 if (parseAbsoluteExpression(Alignment))
2642 bool HasFillExpr = false;
2643 int64_t FillExpr = 0;
2644 int64_t MaxBytesToFill = 0;
2645 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2646 if (getLexer().isNot(AsmToken::Comma))
2647 return TokError("unexpected token in directive");
2650 // The fill expression can be omitted while specifying a maximum number of
2651 // alignment bytes, e.g:
2653 if (getLexer().isNot(AsmToken::Comma)) {
2655 if (parseAbsoluteExpression(FillExpr))
2659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2660 if (getLexer().isNot(AsmToken::Comma))
2661 return TokError("unexpected token in directive");
2664 MaxBytesLoc = getLexer().getLoc();
2665 if (parseAbsoluteExpression(MaxBytesToFill))
2668 if (getLexer().isNot(AsmToken::EndOfStatement))
2669 return TokError("unexpected token in directive");
2678 // Compute alignment in bytes.
2680 // FIXME: Diagnose overflow.
2681 if (Alignment >= 32) {
2682 Error(AlignmentLoc, "invalid alignment value");
2686 Alignment = 1ULL << Alignment;
2688 // Reject alignments that aren't a power of two, for gas compatibility.
2689 if (!isPowerOf2_64(Alignment))
2690 Error(AlignmentLoc, "alignment must be a power of 2");
2693 // Diagnose non-sensical max bytes to align.
2694 if (MaxBytesLoc.isValid()) {
2695 if (MaxBytesToFill < 1) {
2696 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2697 "many bytes, ignoring maximum bytes expression");
2701 if (MaxBytesToFill >= Alignment) {
2702 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2708 // Check whether we should use optimal code alignment for this .align
2710 const MCSection *Section = getStreamer().getCurrentSection().first;
2711 assert(Section && "must have section to emit alignment");
2712 bool UseCodeAlign = Section->UseCodeAlign();
2713 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2714 ValueSize == 1 && UseCodeAlign) {
2715 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
2717 // FIXME: Target specific behavior about how the "extra" bytes are filled.
2718 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2725 /// parseDirectiveFile
2726 /// ::= .file [number] filename
2727 /// ::= .file number directory filename
2728 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
2729 // FIXME: I'm not sure what this is.
2730 int64_t FileNumber = -1;
2731 SMLoc FileNumberLoc = getLexer().getLoc();
2732 if (getLexer().is(AsmToken::Integer)) {
2733 FileNumber = getTok().getIntVal();
2737 return TokError("file number less than one");
2740 if (getLexer().isNot(AsmToken::String))
2741 return TokError("unexpected token in '.file' directive");
2743 // Usually the directory and filename together, otherwise just the directory.
2744 // Allow the strings to have escaped octal character sequence.
2745 std::string Path = getTok().getString();
2746 if (parseEscapedString(Path))
2750 StringRef Directory;
2752 std::string FilenameData;
2753 if (getLexer().is(AsmToken::String)) {
2754 if (FileNumber == -1)
2755 return TokError("explicit path specified, but no file number");
2756 if (parseEscapedString(FilenameData))
2758 Filename = FilenameData;
2765 if (getLexer().isNot(AsmToken::EndOfStatement))
2766 return TokError("unexpected token in '.file' directive");
2768 if (FileNumber == -1)
2769 getStreamer().EmitFileDirective(Filename);
2771 if (getContext().getGenDwarfForAssembly() == true)
2773 "input can't have .file dwarf directives when -g is "
2774 "used to generate dwarf debug info for assembly code");
2776 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2778 Error(FileNumberLoc, "file number already allocated");
2784 /// parseDirectiveLine
2785 /// ::= .line [number]
2786 bool AsmParser::parseDirectiveLine() {
2787 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2788 if (getLexer().isNot(AsmToken::Integer))
2789 return TokError("unexpected token in '.line' directive");
2791 int64_t LineNumber = getTok().getIntVal();
2795 // FIXME: Do something with the .line.
2798 if (getLexer().isNot(AsmToken::EndOfStatement))
2799 return TokError("unexpected token in '.line' directive");
2804 /// parseDirectiveLoc
2805 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2806 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2807 /// The first number is a file number, must have been previously assigned with
2808 /// a .file directive, the second number is the line number and optionally the
2809 /// third number is a column position (zero if not specified). The remaining
2810 /// optional items are .loc sub-directives.
2811 bool AsmParser::parseDirectiveLoc() {
2812 if (getLexer().isNot(AsmToken::Integer))
2813 return TokError("unexpected token in '.loc' directive");
2814 int64_t FileNumber = getTok().getIntVal();
2816 return TokError("file number less than one in '.loc' directive");
2817 if (!getContext().isValidDwarfFileNumber(FileNumber))
2818 return TokError("unassigned file number in '.loc' directive");
2821 int64_t LineNumber = 0;
2822 if (getLexer().is(AsmToken::Integer)) {
2823 LineNumber = getTok().getIntVal();
2825 return TokError("line number less than zero in '.loc' directive");
2829 int64_t ColumnPos = 0;
2830 if (getLexer().is(AsmToken::Integer)) {
2831 ColumnPos = getTok().getIntVal();
2833 return TokError("column position less than zero in '.loc' directive");
2837 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2839 int64_t Discriminator = 0;
2840 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2842 if (getLexer().is(AsmToken::EndOfStatement))
2846 SMLoc Loc = getTok().getLoc();
2847 if (parseIdentifier(Name))
2848 return TokError("unexpected token in '.loc' directive");
2850 if (Name == "basic_block")
2851 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2852 else if (Name == "prologue_end")
2853 Flags |= DWARF2_FLAG_PROLOGUE_END;
2854 else if (Name == "epilogue_begin")
2855 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2856 else if (Name == "is_stmt") {
2857 Loc = getTok().getLoc();
2858 const MCExpr *Value;
2859 if (parseExpression(Value))
2861 // The expression must be the constant 0 or 1.
2862 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2863 int Value = MCE->getValue();
2865 Flags &= ~DWARF2_FLAG_IS_STMT;
2866 else if (Value == 1)
2867 Flags |= DWARF2_FLAG_IS_STMT;
2869 return Error(Loc, "is_stmt value not 0 or 1");
2871 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2873 } else if (Name == "isa") {
2874 Loc = getTok().getLoc();
2875 const MCExpr *Value;
2876 if (parseExpression(Value))
2878 // The expression must be a constant greater or equal to 0.
2879 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2880 int Value = MCE->getValue();
2882 return Error(Loc, "isa number less than zero");
2885 return Error(Loc, "isa number not a constant value");
2887 } else if (Name == "discriminator") {
2888 if (parseAbsoluteExpression(Discriminator))
2891 return Error(Loc, "unknown sub-directive in '.loc' directive");
2894 if (getLexer().is(AsmToken::EndOfStatement))
2899 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2900 Isa, Discriminator, StringRef());
2905 /// parseDirectiveStabs
2906 /// ::= .stabs string, number, number, number
2907 bool AsmParser::parseDirectiveStabs() {
2908 return TokError("unsupported directive '.stabs'");
2911 /// parseDirectiveCFISections
2912 /// ::= .cfi_sections section [, section]
2913 bool AsmParser::parseDirectiveCFISections() {
2918 if (parseIdentifier(Name))
2919 return TokError("Expected an identifier");
2921 if (Name == ".eh_frame")
2923 else if (Name == ".debug_frame")
2926 if (getLexer().is(AsmToken::Comma)) {
2929 if (parseIdentifier(Name))
2930 return TokError("Expected an identifier");
2932 if (Name == ".eh_frame")
2934 else if (Name == ".debug_frame")
2938 getStreamer().EmitCFISections(EH, Debug);
2942 /// parseDirectiveCFIStartProc
2943 /// ::= .cfi_startproc [simple]
2944 bool AsmParser::parseDirectiveCFIStartProc() {
2946 if (getLexer().isNot(AsmToken::EndOfStatement))
2947 if (parseIdentifier(Simple) || Simple != "simple")
2948 return TokError("unexpected token in .cfi_startproc directive");
2950 getStreamer().EmitCFIStartProc(!Simple.empty());
2954 /// parseDirectiveCFIEndProc
2955 /// ::= .cfi_endproc
2956 bool AsmParser::parseDirectiveCFIEndProc() {
2957 getStreamer().EmitCFIEndProc();
2961 /// \brief parse register name or number.
2962 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
2963 SMLoc DirectiveLoc) {
2966 if (getLexer().isNot(AsmToken::Integer)) {
2967 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2969 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
2971 return parseAbsoluteExpression(Register);
2976 /// parseDirectiveCFIDefCfa
2977 /// ::= .cfi_def_cfa register, offset
2978 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2979 int64_t Register = 0;
2980 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
2983 if (getLexer().isNot(AsmToken::Comma))
2984 return TokError("unexpected token in directive");
2988 if (parseAbsoluteExpression(Offset))
2991 getStreamer().EmitCFIDefCfa(Register, Offset);
2995 /// parseDirectiveCFIDefCfaOffset
2996 /// ::= .cfi_def_cfa_offset offset
2997 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
2999 if (parseAbsoluteExpression(Offset))
3002 getStreamer().EmitCFIDefCfaOffset(Offset);
3006 /// parseDirectiveCFIRegister
3007 /// ::= .cfi_register register, register
3008 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3009 int64_t Register1 = 0;
3010 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3013 if (getLexer().isNot(AsmToken::Comma))
3014 return TokError("unexpected token in directive");
3017 int64_t Register2 = 0;
3018 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3021 getStreamer().EmitCFIRegister(Register1, Register2);
3025 /// parseDirectiveCFIWindowSave
3026 /// ::= .cfi_window_save
3027 bool AsmParser::parseDirectiveCFIWindowSave() {
3028 getStreamer().EmitCFIWindowSave();
3032 /// parseDirectiveCFIAdjustCfaOffset
3033 /// ::= .cfi_adjust_cfa_offset adjustment
3034 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3035 int64_t Adjustment = 0;
3036 if (parseAbsoluteExpression(Adjustment))
3039 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3043 /// parseDirectiveCFIDefCfaRegister
3044 /// ::= .cfi_def_cfa_register register
3045 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3046 int64_t Register = 0;
3047 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3050 getStreamer().EmitCFIDefCfaRegister(Register);
3054 /// parseDirectiveCFIOffset
3055 /// ::= .cfi_offset register, offset
3056 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3057 int64_t Register = 0;
3060 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3063 if (getLexer().isNot(AsmToken::Comma))
3064 return TokError("unexpected token in directive");
3067 if (parseAbsoluteExpression(Offset))
3070 getStreamer().EmitCFIOffset(Register, Offset);
3074 /// parseDirectiveCFIRelOffset
3075 /// ::= .cfi_rel_offset register, offset
3076 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3077 int64_t Register = 0;
3079 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3082 if (getLexer().isNot(AsmToken::Comma))
3083 return TokError("unexpected token in directive");
3087 if (parseAbsoluteExpression(Offset))
3090 getStreamer().EmitCFIRelOffset(Register, Offset);
3094 static bool isValidEncoding(int64_t Encoding) {
3095 if (Encoding & ~0xff)
3098 if (Encoding == dwarf::DW_EH_PE_omit)
3101 const unsigned Format = Encoding & 0xf;
3102 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3103 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3104 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3105 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3108 const unsigned Application = Encoding & 0x70;
3109 if (Application != dwarf::DW_EH_PE_absptr &&
3110 Application != dwarf::DW_EH_PE_pcrel)
3116 /// parseDirectiveCFIPersonalityOrLsda
3117 /// IsPersonality true for cfi_personality, false for cfi_lsda
3118 /// ::= .cfi_personality encoding, [symbol_name]
3119 /// ::= .cfi_lsda encoding, [symbol_name]
3120 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
3121 int64_t Encoding = 0;
3122 if (parseAbsoluteExpression(Encoding))
3124 if (Encoding == dwarf::DW_EH_PE_omit)
3127 if (!isValidEncoding(Encoding))
3128 return TokError("unsupported encoding.");
3130 if (getLexer().isNot(AsmToken::Comma))
3131 return TokError("unexpected token in directive");
3135 if (parseIdentifier(Name))
3136 return TokError("expected identifier in directive");
3138 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3141 getStreamer().EmitCFIPersonality(Sym, Encoding);
3143 getStreamer().EmitCFILsda(Sym, Encoding);
3147 /// parseDirectiveCFIRememberState
3148 /// ::= .cfi_remember_state
3149 bool AsmParser::parseDirectiveCFIRememberState() {
3150 getStreamer().EmitCFIRememberState();
3154 /// parseDirectiveCFIRestoreState
3155 /// ::= .cfi_remember_state
3156 bool AsmParser::parseDirectiveCFIRestoreState() {
3157 getStreamer().EmitCFIRestoreState();
3161 /// parseDirectiveCFISameValue
3162 /// ::= .cfi_same_value register
3163 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
3164 int64_t Register = 0;
3166 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3169 getStreamer().EmitCFISameValue(Register);
3173 /// parseDirectiveCFIRestore
3174 /// ::= .cfi_restore register
3175 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
3176 int64_t Register = 0;
3177 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3180 getStreamer().EmitCFIRestore(Register);
3184 /// parseDirectiveCFIEscape
3185 /// ::= .cfi_escape expression[,...]
3186 bool AsmParser::parseDirectiveCFIEscape() {
3189 if (parseAbsoluteExpression(CurrValue))
3192 Values.push_back((uint8_t)CurrValue);
3194 while (getLexer().is(AsmToken::Comma)) {
3197 if (parseAbsoluteExpression(CurrValue))
3200 Values.push_back((uint8_t)CurrValue);
3203 getStreamer().EmitCFIEscape(Values);
3207 /// parseDirectiveCFISignalFrame
3208 /// ::= .cfi_signal_frame
3209 bool AsmParser::parseDirectiveCFISignalFrame() {
3210 if (getLexer().isNot(AsmToken::EndOfStatement))
3211 return Error(getLexer().getLoc(),
3212 "unexpected token in '.cfi_signal_frame'");
3214 getStreamer().EmitCFISignalFrame();
3218 /// parseDirectiveCFIUndefined
3219 /// ::= .cfi_undefined register
3220 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3221 int64_t Register = 0;
3223 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3226 getStreamer().EmitCFIUndefined(Register);
3230 /// parseDirectiveMacrosOnOff
3233 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
3234 if (getLexer().isNot(AsmToken::EndOfStatement))
3235 return Error(getLexer().getLoc(),
3236 "unexpected token in '" + Directive + "' directive");
3238 setMacrosEnabled(Directive == ".macros_on");
3242 /// parseDirectiveMacro
3243 /// ::= .macro name[,] [parameters]
3244 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
3246 if (parseIdentifier(Name))
3247 return TokError("expected identifier in '.macro' directive");
3249 if (getLexer().is(AsmToken::Comma))
3252 MCAsmMacroParameters Parameters;
3253 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3255 if (Parameters.size() && Parameters.back().Vararg)
3256 return Error(Lexer.getLoc(),
3257 "Vararg parameter '" + Parameters.back().Name +
3258 "' should be last one in the list of parameters.");
3260 MCAsmMacroParameter Parameter;
3261 if (parseIdentifier(Parameter.Name))
3262 return TokError("expected identifier in '.macro' directive");
3264 if (Lexer.is(AsmToken::Colon)) {
3265 Lex(); // consume ':'
3268 StringRef Qualifier;
3270 QualLoc = Lexer.getLoc();
3271 if (parseIdentifier(Qualifier))
3272 return Error(QualLoc, "missing parameter qualifier for "
3273 "'" + Parameter.Name + "' in macro '" + Name + "'");
3275 if (Qualifier == "req")
3276 Parameter.Required = true;
3277 else if (Qualifier == "vararg" && !IsDarwin)
3278 Parameter.Vararg = true;
3280 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3281 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3284 if (getLexer().is(AsmToken::Equal)) {
3289 ParamLoc = Lexer.getLoc();
3290 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
3293 if (Parameter.Required)
3294 Warning(ParamLoc, "pointless default value for required parameter "
3295 "'" + Parameter.Name + "' in macro '" + Name + "'");
3298 Parameters.push_back(Parameter);
3300 if (getLexer().is(AsmToken::Comma))
3304 // Eat the end of statement.
3307 AsmToken EndToken, StartToken = getTok();
3308 unsigned MacroDepth = 0;
3310 // Lex the macro definition.
3312 // Check whether we have reached the end of the file.
3313 if (getLexer().is(AsmToken::Eof))
3314 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3316 // Otherwise, check whether we have reach the .endmacro.
3317 if (getLexer().is(AsmToken::Identifier)) {
3318 if (getTok().getIdentifier() == ".endm" ||
3319 getTok().getIdentifier() == ".endmacro") {
3320 if (MacroDepth == 0) { // Outermost macro.
3321 EndToken = getTok();
3323 if (getLexer().isNot(AsmToken::EndOfStatement))
3324 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3328 // Otherwise we just found the end of an inner macro.
3331 } else if (getTok().getIdentifier() == ".macro") {
3332 // We allow nested macros. Those aren't instantiated until the outermost
3333 // macro is expanded so just ignore them for now.
3338 // Otherwise, scan til the end of the statement.
3339 eatToEndOfStatement();
3342 if (lookupMacro(Name)) {
3343 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3346 const char *BodyStart = StartToken.getLoc().getPointer();
3347 const char *BodyEnd = EndToken.getLoc().getPointer();
3348 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3349 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
3350 defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3354 /// checkForBadMacro
3356 /// With the support added for named parameters there may be code out there that
3357 /// is transitioning from positional parameters. In versions of gas that did
3358 /// not support named parameters they would be ignored on the macro definition.
3359 /// But to support both styles of parameters this is not possible so if a macro
3360 /// definition has named parameters but does not use them and has what appears
3361 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3362 /// warning that the positional parameter found in body which have no effect.
3363 /// Hoping the developer will either remove the named parameters from the macro
3364 /// definition so the positional parameters get used if that was what was
3365 /// intended or change the macro to use the named parameters. It is possible
3366 /// this warning will trigger when the none of the named parameters are used
3367 /// and the strings like $1 are infact to simply to be passed trough unchanged.
3368 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3370 ArrayRef<MCAsmMacroParameter> Parameters) {
3371 // If this macro is not defined with named parameters the warning we are
3372 // checking for here doesn't apply.
3373 unsigned NParameters = Parameters.size();
3374 if (NParameters == 0)
3377 bool NamedParametersFound = false;
3378 bool PositionalParametersFound = false;
3380 // Look at the body of the macro for use of both the named parameters and what
3381 // are likely to be positional parameters. This is what expandMacro() is
3382 // doing when it finds the parameters in the body.
3383 while (!Body.empty()) {
3384 // Scan for the next possible parameter.
3385 std::size_t End = Body.size(), Pos = 0;
3386 for (; Pos != End; ++Pos) {
3387 // Check for a substitution or escape.
3388 // This macro is defined with parameters, look for \foo, \bar, etc.
3389 if (Body[Pos] == '\\' && Pos + 1 != End)
3392 // This macro should have parameters, but look for $0, $1, ..., $n too.
3393 if (Body[Pos] != '$' || Pos + 1 == End)
3395 char Next = Body[Pos + 1];
3396 if (Next == '$' || Next == 'n' ||
3397 isdigit(static_cast<unsigned char>(Next)))
3401 // Check if we reached the end.
3405 if (Body[Pos] == '$') {
3406 switch (Body[Pos + 1]) {
3411 // $n => number of arguments
3413 PositionalParametersFound = true;
3416 // $[0-9] => argument
3418 PositionalParametersFound = true;
3424 unsigned I = Pos + 1;
3425 while (isIdentifierChar(Body[I]) && I + 1 != End)
3428 const char *Begin = Body.data() + Pos + 1;
3429 StringRef Argument(Begin, I - (Pos + 1));
3431 for (; Index < NParameters; ++Index)
3432 if (Parameters[Index].Name == Argument)
3435 if (Index == NParameters) {
3436 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3442 NamedParametersFound = true;
3443 Pos += 1 + Argument.size();
3446 // Update the scan point.
3447 Body = Body.substr(Pos);
3450 if (!NamedParametersFound && PositionalParametersFound)
3451 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3452 "used in macro body, possible positional parameter "
3453 "found in body which will have no effect");
3456 /// parseDirectiveEndMacro
3459 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
3460 if (getLexer().isNot(AsmToken::EndOfStatement))
3461 return TokError("unexpected token in '" + Directive + "' directive");
3463 // If we are inside a macro instantiation, terminate the current
3465 if (isInsideMacroInstantiation()) {
3470 // Otherwise, this .endmacro is a stray entry in the file; well formed
3471 // .endmacro directives are handled during the macro definition parsing.
3472 return TokError("unexpected '" + Directive + "' in file, "
3473 "no current macro definition");
3476 /// parseDirectivePurgeMacro
3478 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3480 if (parseIdentifier(Name))
3481 return TokError("expected identifier in '.purgem' directive");
3483 if (getLexer().isNot(AsmToken::EndOfStatement))
3484 return TokError("unexpected token in '.purgem' directive");
3486 if (!lookupMacro(Name))
3487 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3489 undefineMacro(Name);
3493 /// parseDirectiveBundleAlignMode
3494 /// ::= {.bundle_align_mode} expression
3495 bool AsmParser::parseDirectiveBundleAlignMode() {
3496 checkForValidSection();
3498 // Expect a single argument: an expression that evaluates to a constant
3499 // in the inclusive range 0-30.
3500 SMLoc ExprLoc = getLexer().getLoc();
3501 int64_t AlignSizePow2;
3502 if (parseAbsoluteExpression(AlignSizePow2))
3504 else if (getLexer().isNot(AsmToken::EndOfStatement))
3505 return TokError("unexpected token after expression in"
3506 " '.bundle_align_mode' directive");
3507 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3508 return Error(ExprLoc,
3509 "invalid bundle alignment size (expected between 0 and 30)");
3513 // Because of AlignSizePow2's verified range we can safely truncate it to
3515 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3519 /// parseDirectiveBundleLock
3520 /// ::= {.bundle_lock} [align_to_end]
3521 bool AsmParser::parseDirectiveBundleLock() {
3522 checkForValidSection();
3523 bool AlignToEnd = false;
3525 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3527 SMLoc Loc = getTok().getLoc();
3528 const char *kInvalidOptionError =
3529 "invalid option for '.bundle_lock' directive";
3531 if (parseIdentifier(Option))
3532 return Error(Loc, kInvalidOptionError);
3534 if (Option != "align_to_end")
3535 return Error(Loc, kInvalidOptionError);
3536 else if (getLexer().isNot(AsmToken::EndOfStatement))
3538 "unexpected token after '.bundle_lock' directive option");
3544 getStreamer().EmitBundleLock(AlignToEnd);
3548 /// parseDirectiveBundleLock
3549 /// ::= {.bundle_lock}
3550 bool AsmParser::parseDirectiveBundleUnlock() {
3551 checkForValidSection();
3553 if (getLexer().isNot(AsmToken::EndOfStatement))
3554 return TokError("unexpected token in '.bundle_unlock' directive");
3557 getStreamer().EmitBundleUnlock();
3561 /// parseDirectiveSpace
3562 /// ::= (.skip | .space) expression [ , expression ]
3563 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
3564 checkForValidSection();
3567 if (parseAbsoluteExpression(NumBytes))
3570 int64_t FillExpr = 0;
3571 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3572 if (getLexer().isNot(AsmToken::Comma))
3573 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3576 if (parseAbsoluteExpression(FillExpr))
3579 if (getLexer().isNot(AsmToken::EndOfStatement))
3580 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3586 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3589 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3590 getStreamer().EmitFill(NumBytes, FillExpr);
3595 /// parseDirectiveLEB128
3596 /// ::= (.sleb128 | .uleb128) expression
3597 bool AsmParser::parseDirectiveLEB128(bool Signed) {
3598 checkForValidSection();
3599 const MCExpr *Value;
3601 if (parseExpression(Value))
3604 if (getLexer().isNot(AsmToken::EndOfStatement))
3605 return TokError("unexpected token in directive");
3608 getStreamer().EmitSLEB128Value(Value);
3610 getStreamer().EmitULEB128Value(Value);
3615 /// parseDirectiveSymbolAttribute
3616 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
3617 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
3618 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3621 SMLoc Loc = getTok().getLoc();
3623 if (parseIdentifier(Name))
3624 return Error(Loc, "expected identifier in directive");
3626 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3628 // Assembler local symbols don't make any sense here. Complain loudly.
3629 if (Sym->isTemporary())
3630 return Error(Loc, "non-local symbol required in directive");
3632 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3633 return Error(Loc, "unable to emit symbol attribute");
3635 if (getLexer().is(AsmToken::EndOfStatement))
3638 if (getLexer().isNot(AsmToken::Comma))
3639 return TokError("unexpected token in directive");
3648 /// parseDirectiveComm
3649 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3650 bool AsmParser::parseDirectiveComm(bool IsLocal) {
3651 checkForValidSection();
3653 SMLoc IDLoc = getLexer().getLoc();
3655 if (parseIdentifier(Name))
3656 return TokError("expected identifier in directive");
3658 // Handle the identifier as the key symbol.
3659 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3661 if (getLexer().isNot(AsmToken::Comma))
3662 return TokError("unexpected token in directive");
3666 SMLoc SizeLoc = getLexer().getLoc();
3667 if (parseAbsoluteExpression(Size))
3670 int64_t Pow2Alignment = 0;
3671 SMLoc Pow2AlignmentLoc;
3672 if (getLexer().is(AsmToken::Comma)) {
3674 Pow2AlignmentLoc = getLexer().getLoc();
3675 if (parseAbsoluteExpression(Pow2Alignment))
3678 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3679 if (IsLocal && LCOMM == LCOMM::NoAlignment)
3680 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3682 // If this target takes alignments in bytes (not log) validate and convert.
3683 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3684 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
3685 if (!isPowerOf2_64(Pow2Alignment))
3686 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3687 Pow2Alignment = Log2_64(Pow2Alignment);
3691 if (getLexer().isNot(AsmToken::EndOfStatement))
3692 return TokError("unexpected token in '.comm' or '.lcomm' directive");
3696 // NOTE: a size of zero for a .comm should create a undefined symbol
3697 // but a size of .lcomm creates a bss symbol of size zero.
3699 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3700 "be less than zero");
3702 // NOTE: The alignment in the directive is a power of 2 value, the assembler
3703 // may internally end up wanting an alignment in bytes.
3704 // FIXME: Diagnose overflow.
3705 if (Pow2Alignment < 0)
3706 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3707 "alignment, can't be less than zero");
3709 if (!Sym->isUndefined())
3710 return Error(IDLoc, "invalid symbol redefinition");
3712 // Create the Symbol as a common or local common with Size and Pow2Alignment
3714 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3718 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
3722 /// parseDirectiveAbort
3723 /// ::= .abort [... message ...]
3724 bool AsmParser::parseDirectiveAbort() {
3725 // FIXME: Use loc from directive.
3726 SMLoc Loc = getLexer().getLoc();
3728 StringRef Str = parseStringToEndOfStatement();
3729 if (getLexer().isNot(AsmToken::EndOfStatement))
3730 return TokError("unexpected token in '.abort' directive");
3735 Error(Loc, ".abort detected. Assembly stopping.");
3737 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
3738 // FIXME: Actually abort assembly here.
3743 /// parseDirectiveInclude
3744 /// ::= .include "filename"
3745 bool AsmParser::parseDirectiveInclude() {
3746 if (getLexer().isNot(AsmToken::String))
3747 return TokError("expected string in '.include' directive");
3749 // Allow the strings to have escaped octal character sequence.
3750 std::string Filename;
3751 if (parseEscapedString(Filename))
3753 SMLoc IncludeLoc = getLexer().getLoc();
3756 if (getLexer().isNot(AsmToken::EndOfStatement))
3757 return TokError("unexpected token in '.include' directive");
3759 // Attempt to switch the lexer to the included file before consuming the end
3760 // of statement to avoid losing it when we switch.
3761 if (enterIncludeFile(Filename)) {
3762 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
3769 /// parseDirectiveIncbin
3770 /// ::= .incbin "filename"
3771 bool AsmParser::parseDirectiveIncbin() {
3772 if (getLexer().isNot(AsmToken::String))
3773 return TokError("expected string in '.incbin' directive");
3775 // Allow the strings to have escaped octal character sequence.
3776 std::string Filename;
3777 if (parseEscapedString(Filename))
3779 SMLoc IncbinLoc = getLexer().getLoc();
3782 if (getLexer().isNot(AsmToken::EndOfStatement))
3783 return TokError("unexpected token in '.incbin' directive");
3785 // Attempt to process the included file.
3786 if (processIncbinFile(Filename)) {
3787 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3794 /// parseDirectiveIf
3795 /// ::= .if expression
3796 /// ::= .ifne expression
3797 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc) {
3798 TheCondStack.push_back(TheCondState);
3799 TheCondState.TheCond = AsmCond::IfCond;
3800 if (TheCondState.Ignore) {
3801 eatToEndOfStatement();
3804 if (parseAbsoluteExpression(ExprValue))
3807 if (getLexer().isNot(AsmToken::EndOfStatement))
3808 return TokError("unexpected token in '.if' directive");
3812 TheCondState.CondMet = ExprValue;
3813 TheCondState.Ignore = !TheCondState.CondMet;
3819 /// parseDirectiveIfb
3821 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3822 TheCondStack.push_back(TheCondState);
3823 TheCondState.TheCond = AsmCond::IfCond;
3825 if (TheCondState.Ignore) {
3826 eatToEndOfStatement();
3828 StringRef Str = parseStringToEndOfStatement();
3830 if (getLexer().isNot(AsmToken::EndOfStatement))
3831 return TokError("unexpected token in '.ifb' directive");
3835 TheCondState.CondMet = ExpectBlank == Str.empty();
3836 TheCondState.Ignore = !TheCondState.CondMet;
3842 /// parseDirectiveIfc
3843 /// ::= .ifc string1, string2
3844 /// ::= .ifnc string1, string2
3845 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3846 TheCondStack.push_back(TheCondState);
3847 TheCondState.TheCond = AsmCond::IfCond;
3849 if (TheCondState.Ignore) {
3850 eatToEndOfStatement();
3852 StringRef Str1 = parseStringToComma();
3854 if (getLexer().isNot(AsmToken::Comma))
3855 return TokError("unexpected token in '.ifc' directive");
3859 StringRef Str2 = parseStringToEndOfStatement();
3861 if (getLexer().isNot(AsmToken::EndOfStatement))
3862 return TokError("unexpected token in '.ifc' directive");
3866 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
3867 TheCondState.Ignore = !TheCondState.CondMet;
3873 /// parseDirectiveIfeqs
3874 /// ::= .ifeqs string1, string2
3875 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
3876 if (Lexer.isNot(AsmToken::String)) {
3877 TokError("expected string parameter for '.ifeqs' directive");
3878 eatToEndOfStatement();
3882 StringRef String1 = getTok().getStringContents();
3885 if (Lexer.isNot(AsmToken::Comma)) {
3886 TokError("expected comma after first string for '.ifeqs' directive");
3887 eatToEndOfStatement();
3893 if (Lexer.isNot(AsmToken::String)) {
3894 TokError("expected string parameter for '.ifeqs' directive");
3895 eatToEndOfStatement();
3899 StringRef String2 = getTok().getStringContents();
3902 TheCondStack.push_back(TheCondState);
3903 TheCondState.TheCond = AsmCond::IfCond;
3904 TheCondState.CondMet = String1 == String2;
3905 TheCondState.Ignore = !TheCondState.CondMet;
3910 /// parseDirectiveIfdef
3911 /// ::= .ifdef symbol
3912 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3914 TheCondStack.push_back(TheCondState);
3915 TheCondState.TheCond = AsmCond::IfCond;
3917 if (TheCondState.Ignore) {
3918 eatToEndOfStatement();
3920 if (parseIdentifier(Name))
3921 return TokError("expected identifier after '.ifdef'");
3925 MCSymbol *Sym = getContext().LookupSymbol(Name);
3928 TheCondState.CondMet = (Sym && !Sym->isUndefined());
3930 TheCondState.CondMet = (!Sym || Sym->isUndefined());
3931 TheCondState.Ignore = !TheCondState.CondMet;
3937 /// parseDirectiveElseIf
3938 /// ::= .elseif expression
3939 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
3940 if (TheCondState.TheCond != AsmCond::IfCond &&
3941 TheCondState.TheCond != AsmCond::ElseIfCond)
3942 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3944 TheCondState.TheCond = AsmCond::ElseIfCond;
3946 bool LastIgnoreState = false;
3947 if (!TheCondStack.empty())
3948 LastIgnoreState = TheCondStack.back().Ignore;
3949 if (LastIgnoreState || TheCondState.CondMet) {
3950 TheCondState.Ignore = true;
3951 eatToEndOfStatement();
3954 if (parseAbsoluteExpression(ExprValue))
3957 if (getLexer().isNot(AsmToken::EndOfStatement))
3958 return TokError("unexpected token in '.elseif' directive");
3961 TheCondState.CondMet = ExprValue;
3962 TheCondState.Ignore = !TheCondState.CondMet;
3968 /// parseDirectiveElse
3970 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
3971 if (getLexer().isNot(AsmToken::EndOfStatement))
3972 return TokError("unexpected token in '.else' directive");
3976 if (TheCondState.TheCond != AsmCond::IfCond &&
3977 TheCondState.TheCond != AsmCond::ElseIfCond)
3978 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3980 TheCondState.TheCond = AsmCond::ElseCond;
3981 bool LastIgnoreState = false;
3982 if (!TheCondStack.empty())
3983 LastIgnoreState = TheCondStack.back().Ignore;
3984 if (LastIgnoreState || TheCondState.CondMet)
3985 TheCondState.Ignore = true;
3987 TheCondState.Ignore = false;
3992 /// parseDirectiveEnd
3994 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
3995 if (getLexer().isNot(AsmToken::EndOfStatement))
3996 return TokError("unexpected token in '.end' directive");
4000 while (Lexer.isNot(AsmToken::Eof))
4006 /// parseDirectiveError
4008 /// ::= .error [string]
4009 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4010 if (!TheCondStack.empty()) {
4011 if (TheCondStack.back().Ignore) {
4012 eatToEndOfStatement();
4018 return Error(L, ".err encountered");
4020 StringRef Message = ".error directive invoked in source file";
4021 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4022 if (Lexer.isNot(AsmToken::String)) {
4023 TokError(".error argument must be a string");
4024 eatToEndOfStatement();
4028 Message = getTok().getStringContents();
4036 /// parseDirectiveEndIf
4038 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
4039 if (getLexer().isNot(AsmToken::EndOfStatement))
4040 return TokError("unexpected token in '.endif' directive");
4044 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
4045 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4047 if (!TheCondStack.empty()) {
4048 TheCondState = TheCondStack.back();
4049 TheCondStack.pop_back();
4055 void AsmParser::initializeDirectiveKindMap() {
4056 DirectiveKindMap[".set"] = DK_SET;
4057 DirectiveKindMap[".equ"] = DK_EQU;
4058 DirectiveKindMap[".equiv"] = DK_EQUIV;
4059 DirectiveKindMap[".ascii"] = DK_ASCII;
4060 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4061 DirectiveKindMap[".string"] = DK_STRING;
4062 DirectiveKindMap[".byte"] = DK_BYTE;
4063 DirectiveKindMap[".short"] = DK_SHORT;
4064 DirectiveKindMap[".value"] = DK_VALUE;
4065 DirectiveKindMap[".2byte"] = DK_2BYTE;
4066 DirectiveKindMap[".long"] = DK_LONG;
4067 DirectiveKindMap[".int"] = DK_INT;
4068 DirectiveKindMap[".4byte"] = DK_4BYTE;
4069 DirectiveKindMap[".quad"] = DK_QUAD;
4070 DirectiveKindMap[".8byte"] = DK_8BYTE;
4071 DirectiveKindMap[".octa"] = DK_OCTA;
4072 DirectiveKindMap[".single"] = DK_SINGLE;
4073 DirectiveKindMap[".float"] = DK_FLOAT;
4074 DirectiveKindMap[".double"] = DK_DOUBLE;
4075 DirectiveKindMap[".align"] = DK_ALIGN;
4076 DirectiveKindMap[".align32"] = DK_ALIGN32;
4077 DirectiveKindMap[".balign"] = DK_BALIGN;
4078 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4079 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4080 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4081 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4082 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4083 DirectiveKindMap[".org"] = DK_ORG;
4084 DirectiveKindMap[".fill"] = DK_FILL;
4085 DirectiveKindMap[".zero"] = DK_ZERO;
4086 DirectiveKindMap[".extern"] = DK_EXTERN;
4087 DirectiveKindMap[".globl"] = DK_GLOBL;
4088 DirectiveKindMap[".global"] = DK_GLOBAL;
4089 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4090 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4091 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4092 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4093 DirectiveKindMap[".reference"] = DK_REFERENCE;
4094 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4095 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4096 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4097 DirectiveKindMap[".comm"] = DK_COMM;
4098 DirectiveKindMap[".common"] = DK_COMMON;
4099 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4100 DirectiveKindMap[".abort"] = DK_ABORT;
4101 DirectiveKindMap[".include"] = DK_INCLUDE;
4102 DirectiveKindMap[".incbin"] = DK_INCBIN;
4103 DirectiveKindMap[".code16"] = DK_CODE16;
4104 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4105 DirectiveKindMap[".rept"] = DK_REPT;
4106 DirectiveKindMap[".rep"] = DK_REPT;
4107 DirectiveKindMap[".irp"] = DK_IRP;
4108 DirectiveKindMap[".irpc"] = DK_IRPC;
4109 DirectiveKindMap[".endr"] = DK_ENDR;
4110 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4111 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4112 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4113 DirectiveKindMap[".if"] = DK_IF;
4114 DirectiveKindMap[".ifne"] = DK_IFNE;
4115 DirectiveKindMap[".ifb"] = DK_IFB;
4116 DirectiveKindMap[".ifnb"] = DK_IFNB;
4117 DirectiveKindMap[".ifc"] = DK_IFC;
4118 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
4119 DirectiveKindMap[".ifnc"] = DK_IFNC;
4120 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4121 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4122 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4123 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4124 DirectiveKindMap[".else"] = DK_ELSE;
4125 DirectiveKindMap[".end"] = DK_END;
4126 DirectiveKindMap[".endif"] = DK_ENDIF;
4127 DirectiveKindMap[".skip"] = DK_SKIP;
4128 DirectiveKindMap[".space"] = DK_SPACE;
4129 DirectiveKindMap[".file"] = DK_FILE;
4130 DirectiveKindMap[".line"] = DK_LINE;
4131 DirectiveKindMap[".loc"] = DK_LOC;
4132 DirectiveKindMap[".stabs"] = DK_STABS;
4133 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4134 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4135 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4136 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4137 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4138 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4139 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4140 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4141 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4142 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4143 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4144 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4145 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4146 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4147 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4148 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4149 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4150 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4151 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4152 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4153 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
4154 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
4155 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4156 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4157 DirectiveKindMap[".macro"] = DK_MACRO;
4158 DirectiveKindMap[".endm"] = DK_ENDM;
4159 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4160 DirectiveKindMap[".purgem"] = DK_PURGEM;
4161 DirectiveKindMap[".err"] = DK_ERR;
4162 DirectiveKindMap[".error"] = DK_ERROR;
4165 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
4166 AsmToken EndToken, StartToken = getTok();
4168 unsigned NestLevel = 0;
4170 // Check whether we have reached the end of the file.
4171 if (getLexer().is(AsmToken::Eof)) {
4172 Error(DirectiveLoc, "no matching '.endr' in definition");
4176 if (Lexer.is(AsmToken::Identifier) &&
4177 (getTok().getIdentifier() == ".rept")) {
4181 // Otherwise, check whether we have reached the .endr.
4182 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
4183 if (NestLevel == 0) {
4184 EndToken = getTok();
4186 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4187 TokError("unexpected token in '.endr' directive");
4195 // Otherwise, scan till the end of the statement.
4196 eatToEndOfStatement();
4199 const char *BodyStart = StartToken.getLoc().getPointer();
4200 const char *BodyEnd = EndToken.getLoc().getPointer();
4201 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4203 // We Are Anonymous.
4204 MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
4205 return &MacroLikeBodies.back();
4208 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
4209 raw_svector_ostream &OS) {
4212 MemoryBuffer *Instantiation =
4213 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
4215 // Create the macro instantiation object and add to the current macro
4216 // instantiation stack.
4217 MacroInstantiation *MI = new MacroInstantiation(
4218 M, DirectiveLoc, CurBuffer, getTok().getLoc(), Instantiation);
4219 ActiveMacros.push_back(MI);
4221 // Jump to the macro instantiation and prime the lexer.
4222 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
4223 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
4227 /// parseDirectiveRept
4228 /// ::= .rep | .rept count
4229 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
4230 const MCExpr *CountExpr;
4231 SMLoc CountLoc = getTok().getLoc();
4232 if (parseExpression(CountExpr))
4236 if (!CountExpr->EvaluateAsAbsolute(Count)) {
4237 eatToEndOfStatement();
4238 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4242 return Error(CountLoc, "Count is negative");
4244 if (Lexer.isNot(AsmToken::EndOfStatement))
4245 return TokError("unexpected token in '" + Dir + "' directive");
4247 // Eat the end of statement.
4250 // Lex the rept definition.
4251 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4255 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4256 // to hold the macro body with substitutions.
4257 SmallString<256> Buf;
4258 raw_svector_ostream OS(Buf);
4260 if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
4263 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4268 /// parseDirectiveIrp
4269 /// ::= .irp symbol,values
4270 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
4271 MCAsmMacroParameter Parameter;
4273 if (parseIdentifier(Parameter.Name))
4274 return TokError("expected identifier in '.irp' directive");
4276 if (Lexer.isNot(AsmToken::Comma))
4277 return TokError("expected comma in '.irp' directive");
4281 MCAsmMacroArguments A;
4282 if (parseMacroArguments(nullptr, A))
4285 // Eat the end of statement.
4288 // Lex the irp definition.
4289 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4293 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4294 // to hold the macro body with substitutions.
4295 SmallString<256> Buf;
4296 raw_svector_ostream OS(Buf);
4298 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
4299 if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
4303 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4308 /// parseDirectiveIrpc
4309 /// ::= .irpc symbol,values
4310 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
4311 MCAsmMacroParameter Parameter;
4313 if (parseIdentifier(Parameter.Name))
4314 return TokError("expected identifier in '.irpc' directive");
4316 if (Lexer.isNot(AsmToken::Comma))
4317 return TokError("expected comma in '.irpc' directive");
4321 MCAsmMacroArguments A;
4322 if (parseMacroArguments(nullptr, A))
4325 if (A.size() != 1 || A.front().size() != 1)
4326 return TokError("unexpected token in '.irpc' directive");
4328 // Eat the end of statement.
4331 // Lex the irpc definition.
4332 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
4336 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4337 // to hold the macro body with substitutions.
4338 SmallString<256> Buf;
4339 raw_svector_ostream OS(Buf);
4341 StringRef Values = A.front().front().getString();
4342 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
4343 MCAsmMacroArgument Arg;
4344 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
4346 if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
4350 instantiateMacroLikeBody(M, DirectiveLoc, OS);
4355 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
4356 if (ActiveMacros.empty())
4357 return TokError("unmatched '.endr' directive");
4359 // The only .repl that should get here are the ones created by
4360 // instantiateMacroLikeBody.
4361 assert(getLexer().is(AsmToken::EndOfStatement));
4367 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4369 const MCExpr *Value;
4370 SMLoc ExprLoc = getLexer().getLoc();
4371 if (parseExpression(Value))
4373 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4375 return Error(ExprLoc, "unexpected expression in _emit");
4376 uint64_t IntValue = MCE->getValue();
4377 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4378 return Error(ExprLoc, "literal value out of range for directive");
4380 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4384 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4385 const MCExpr *Value;
4386 SMLoc ExprLoc = getLexer().getLoc();
4387 if (parseExpression(Value))
4389 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4391 return Error(ExprLoc, "unexpected expression in align");
4392 uint64_t IntValue = MCE->getValue();
4393 if (!isPowerOf2_64(IntValue))
4394 return Error(ExprLoc, "literal value not a power of two greater then zero");
4396 Info.AsmRewrites->push_back(
4397 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
4401 // We are comparing pointers, but the pointers are relative to a single string.
4402 // Thus, this should always be deterministic.
4403 static int rewritesSort(const AsmRewrite *AsmRewriteA,
4404 const AsmRewrite *AsmRewriteB) {
4405 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4407 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4410 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4411 // rewrite to the same location. Make sure the SizeDirective rewrite is
4412 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4413 // ensures the sort algorithm is stable.
4414 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4415 AsmRewritePrecedence[AsmRewriteB->Kind])
4418 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4419 AsmRewritePrecedence[AsmRewriteB->Kind])
4421 llvm_unreachable("Unstable rewrite sort.");
4424 bool AsmParser::parseMSInlineAsm(
4425 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4426 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4427 SmallVectorImpl<std::string> &Constraints,
4428 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4429 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
4430 SmallVector<void *, 4> InputDecls;
4431 SmallVector<void *, 4> OutputDecls;
4432 SmallVector<bool, 4> InputDeclsAddressOf;
4433 SmallVector<bool, 4> OutputDeclsAddressOf;
4434 SmallVector<std::string, 4> InputConstraints;
4435 SmallVector<std::string, 4> OutputConstraints;
4436 SmallVector<unsigned, 4> ClobberRegs;
4438 SmallVector<AsmRewrite, 4> AsmStrRewrites;
4443 // While we have input, parse each statement.
4444 unsigned InputIdx = 0;
4445 unsigned OutputIdx = 0;
4446 while (getLexer().isNot(AsmToken::Eof)) {
4447 ParseStatementInfo Info(&AsmStrRewrites);
4448 if (parseStatement(Info))
4451 if (Info.ParseError)
4454 if (Info.Opcode == ~0U)
4457 const MCInstrDesc &Desc = MII->get(Info.Opcode);
4459 // Build the list of clobbers, outputs and inputs.
4460 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4461 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
4464 if (Operand.isImm())
4467 // Register operand.
4468 if (Operand.isReg() && !Operand.needAddressOf()) {
4469 unsigned NumDefs = Desc.getNumDefs();
4471 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4472 ClobberRegs.push_back(Operand.getReg());
4476 // Expr/Input or Output.
4477 StringRef SymName = Operand.getSymName();
4478 if (SymName.empty())
4481 void *OpDecl = Operand.getOpDecl();
4485 bool isOutput = (i == 1) && Desc.mayStore();
4486 SMLoc Start = SMLoc::getFromPointer(SymName.data());
4489 OutputDecls.push_back(OpDecl);
4490 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
4491 OutputConstraints.push_back('=' + Operand.getConstraint().str());
4492 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
4494 InputDecls.push_back(OpDecl);
4495 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4496 InputConstraints.push_back(Operand.getConstraint().str());
4497 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
4501 // Consider implicit defs to be clobbers. Think of cpuid and push.
4502 const uint16_t *ImpDefs = Desc.getImplicitDefs();
4503 for (unsigned I = 0, E = Desc.getNumImplicitDefs(); I != E; ++I)
4504 ClobberRegs.push_back(ImpDefs[I]);
4507 // Set the number of Outputs and Inputs.
4508 NumOutputs = OutputDecls.size();
4509 NumInputs = InputDecls.size();
4511 // Set the unique clobbers.
4512 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4513 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4515 Clobbers.assign(ClobberRegs.size(), std::string());
4516 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4517 raw_string_ostream OS(Clobbers[I]);
4518 IP->printRegName(OS, ClobberRegs[I]);
4521 // Merge the various outputs and inputs. Output are expected first.
4522 if (NumOutputs || NumInputs) {
4523 unsigned NumExprs = NumOutputs + NumInputs;
4524 OpDecls.resize(NumExprs);
4525 Constraints.resize(NumExprs);
4526 for (unsigned i = 0; i < NumOutputs; ++i) {
4527 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
4528 Constraints[i] = OutputConstraints[i];
4530 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
4531 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
4532 Constraints[j] = InputConstraints[i];
4536 // Build the IR assembly string.
4537 std::string AsmStringIR;
4538 raw_string_ostream OS(AsmStringIR);
4539 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4540 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4541 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
4542 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4543 E = AsmStrRewrites.end();
4545 AsmRewriteKind Kind = (*I).Kind;
4546 if (Kind == AOK_Delete)
4549 const char *Loc = (*I).Loc.getPointer();
4550 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
4552 // Emit everything up to the immediate/expression.
4553 unsigned Len = Loc - AsmStart;
4555 OS << StringRef(AsmStart, Len);
4557 // Skip the original expression.
4558 if (Kind == AOK_Skip) {
4559 AsmStart = Loc + (*I).Len;
4563 unsigned AdditionalSkip = 0;
4564 // Rewrite expressions in $N notation.
4569 OS << "$$" << (*I).Val;
4575 OS << '$' << InputIdx++;
4578 OS << '$' << OutputIdx++;
4580 case AOK_SizeDirective:
4583 case 8: OS << "byte ptr "; break;
4584 case 16: OS << "word ptr "; break;
4585 case 32: OS << "dword ptr "; break;
4586 case 64: OS << "qword ptr "; break;
4587 case 80: OS << "xword ptr "; break;
4588 case 128: OS << "xmmword ptr "; break;
4589 case 256: OS << "ymmword ptr "; break;
4596 unsigned Val = (*I).Val;
4597 OS << ".align " << Val;
4599 // Skip the original immediate.
4600 assert(Val < 10 && "Expected alignment less then 2^10.");
4601 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4604 case AOK_DotOperator:
4605 // Insert the dot if the user omitted it.
4607 if (AsmStringIR.back() != '.')
4613 // Skip the original expression.
4614 AsmStart = Loc + (*I).Len + AdditionalSkip;
4617 // Emit the remainder of the asm string.
4618 if (AsmStart != AsmEnd)
4619 OS << StringRef(AsmStart, AsmEnd - AsmStart);
4621 AsmString = OS.str();
4625 /// \brief Create an MCAsmParser instance.
4626 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4627 MCStreamer &Out, const MCAsmInfo &MAI) {
4628 return new AsmParser(SM, C, Out, MAI);