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/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/BinaryFormat/Dwarf.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeView.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDirectives.h"
30 #include "llvm/MC/MCDwarf.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCParser/AsmCond.h"
37 #include "llvm/MC/MCParser/AsmLexer.h"
38 #include "llvm/MC/MCParser/MCAsmLexer.h"
39 #include "llvm/MC/MCParser/MCAsmParser.h"
40 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
41 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
42 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
43 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
44 #include "llvm/MC/MCRegisterInfo.h"
45 #include "llvm/MC/MCSection.h"
46 #include "llvm/MC/MCStreamer.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/MC/MCTargetOptions.h"
49 #include "llvm/MC/MCValue.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MD5.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/SMLoc.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/raw_ostream.h"
75 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
77 static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
83 /// Helper types for tracking macro definitions.
84 typedef std::vector<AsmToken> MCAsmMacroArgument;
85 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
87 /// Helper class for storing information about an active macro
89 struct MacroInstantiation {
90 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
93 /// The buffer where parsing should resume upon instantiation completion.
96 /// The location where parsing should resume upon instantiation completion.
99 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
106 struct ParseStatementInfo {
107 /// The parsed operands from the last parsed statement.
108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
110 /// The opcode from the last parsed instruction.
111 unsigned Opcode = ~0U;
113 /// Was there an error parsing the inline assembly?
114 bool ParseError = false;
116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
118 ParseStatementInfo() = delete;
119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
120 : AsmRewrites(rewrites) {}
123 /// The concrete assembly parser instance.
124 class AsmParser : public MCAsmParser {
129 const MCAsmInfo &MAI;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
142 /// maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
147 /// Stack of active macro instantiations.
148 std::vector<MacroInstantiation*> ActiveMacros;
150 /// List of bodies of anonymous macros.
151 std::deque<MCAsmMacro> MacroLikeBodies;
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabledFlag : 1;
156 /// Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations;
159 /// The values from the last parsed cpp hash file line comment if any.
160 struct CppHashInfoTy {
162 int64_t LineNumber = 0;
166 CppHashInfoTy CppHashInfo;
168 /// List of forward directional labels for diagnosis at the end.
169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect = ~0U;
174 /// is Darwin compatibility enabled?
175 bool IsDarwin = false;
177 /// Are we parsing ms-style inline assembly?
178 bool ParsingInlineAsm = false;
180 /// Did we already inform the user about inconsistent MD5 usage?
181 bool ReportedInconsistentMD5 = false;
183 // Is alt macro mode enabled.
184 bool AltMacroMode = false;
187 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
188 const MCAsmInfo &MAI, unsigned CB);
189 AsmParser(const AsmParser &) = delete;
190 AsmParser &operator=(const AsmParser &) = delete;
191 ~AsmParser() override;
193 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
195 void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) override {
197 ExtensionDirectiveMap[Directive] = Handler;
200 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
201 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
204 /// @name MCAsmParser Interface
207 SourceMgr &getSourceManager() override { return SrcMgr; }
208 MCAsmLexer &getLexer() override { return Lexer; }
209 MCContext &getContext() override { return Ctx; }
210 MCStreamer &getStreamer() override { return Out; }
212 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
214 unsigned getAssemblerDialect() override {
215 if (AssemblerDialect == ~0U)
216 return MAI.getAssemblerDialect();
218 return AssemblerDialect;
220 void setAssemblerDialect(unsigned i) override {
221 AssemblerDialect = i;
224 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
225 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
226 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
228 const AsmToken &Lex() override;
230 void setParsingInlineAsm(bool V) override {
231 ParsingInlineAsm = V;
232 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
233 // hex integer literals.
234 Lexer.setLexMasmIntegers(V);
236 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
238 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
239 unsigned &NumOutputs, unsigned &NumInputs,
240 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
241 SmallVectorImpl<std::string> &Constraints,
242 SmallVectorImpl<std::string> &Clobbers,
243 const MCInstrInfo *MII, const MCInstPrinter *IP,
244 MCAsmParserSemaCallback &SI) override;
246 bool parseExpression(const MCExpr *&Res);
247 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
249 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
250 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
251 SMLoc &EndLoc) override;
252 bool parseAbsoluteExpression(int64_t &Res) override;
254 /// Parse a floating point expression using the float \p Semantics
255 /// and set \p Res to the value.
256 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
258 /// Parse an identifier or string (as a quoted identifier)
259 /// and set \p Res to the identifier contents.
260 bool parseIdentifier(StringRef &Res) override;
261 void eatToEndOfStatement() override;
263 bool checkForValidSection() override;
268 bool parseStatement(ParseStatementInfo &Info,
269 MCAsmParserSemaCallback *SI);
270 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
271 bool parseCppHashLineFilenameComment(SMLoc L);
273 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
274 ArrayRef<MCAsmMacroParameter> Parameters);
275 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
276 ArrayRef<MCAsmMacroParameter> Parameters,
277 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
280 /// Are macros enabled in the parser?
281 bool areMacrosEnabled() {return MacrosEnabledFlag;}
283 /// Control a flag in the parser that enables or disables macros.
284 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
286 /// Are we inside a macro instantiation?
287 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
289 /// Handle entry to macro instantiation.
291 /// \param M The macro.
292 /// \param NameLoc Instantiation location.
293 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
295 /// Handle exit from macro instantiation.
296 void handleMacroExit();
298 /// Extract AsmTokens for a macro argument.
299 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
301 /// Parse all macro arguments for a given macro.
302 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
304 void printMacroInstantiations();
305 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
306 SMRange Range = None) const {
307 ArrayRef<SMRange> Ranges(Range);
308 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
310 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
312 /// Should we emit DWARF describing this assembler source? (Returns false if
313 /// the source has .file directives, which means we don't want to generate
314 /// info describing the assembler source itself.)
315 bool enabledGenDwarfForAssembly();
317 /// Enter the specified file. This returns true on failure.
318 bool enterIncludeFile(const std::string &Filename);
320 /// Process the specified file for the .incbin directive.
321 /// This returns true on failure.
322 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
323 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
325 /// Reset the current lexer position to that given by \p Loc. The
326 /// current token is not set; clients should ensure Lex() is called
329 /// \param InBuffer If not 0, should be the known buffer id that contains the
331 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
333 /// Parse up to the end of statement and a return the contents from the
334 /// current token until the end of the statement; the current token on exit
335 /// will be either the EndOfStatement or EOF.
336 StringRef parseStringToEndOfStatement() override;
338 /// Parse until the end of a statement or a comma is encountered,
339 /// return the contents from the current token up to the end or comma.
340 StringRef parseStringToComma();
342 bool parseAssignment(StringRef Name, bool allow_redef,
343 bool NoDeadStrip = false);
345 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
346 MCBinaryExpr::Opcode &Kind);
348 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
349 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
350 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
352 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
354 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
355 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
357 // Generic (target and platform independent) directive parsing.
359 DK_NO_DIRECTIVE, // Placeholder
414 DK_BUNDLE_ALIGN_MODE,
428 DK_WEAK_DEF_CAN_BE_HIDDEN,
467 DK_CV_INLINE_SITE_ID,
470 DK_CV_INLINE_LINETABLE,
475 DK_CV_FILECHECKSUM_OFFSET,
481 DK_CFI_DEF_CFA_OFFSET,
482 DK_CFI_ADJUST_CFA_OFFSET,
483 DK_CFI_DEF_CFA_REGISTER,
488 DK_CFI_REMEMBER_STATE,
489 DK_CFI_RESTORE_STATE,
493 DK_CFI_RETURN_COLUMN,
519 /// Maps directive name --> DirectiveKind enum, for
520 /// directives parsed by this class.
521 StringMap<DirectiveKind> DirectiveKindMap;
523 // ".ascii", ".asciz", ".string"
524 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
525 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
526 bool parseDirectiveValue(StringRef IDVal,
527 unsigned Size); // ".byte", ".long", ...
528 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
529 bool parseDirectiveRealValue(StringRef IDVal,
530 const fltSemantics &); // ".single", ...
531 bool parseDirectiveFill(); // ".fill"
532 bool parseDirectiveZero(); // ".zero"
533 // ".set", ".equ", ".equiv"
534 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
535 bool parseDirectiveOrg(); // ".org"
536 // ".align{,32}", ".p2align{,w,l}"
537 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
539 // ".file", ".line", ".loc", ".stabs"
540 bool parseDirectiveFile(SMLoc DirectiveLoc);
541 bool parseDirectiveLine();
542 bool parseDirectiveLoc();
543 bool parseDirectiveStabs();
545 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
546 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
547 bool parseDirectiveCVFile();
548 bool parseDirectiveCVFuncId();
549 bool parseDirectiveCVInlineSiteId();
550 bool parseDirectiveCVLoc();
551 bool parseDirectiveCVLinetable();
552 bool parseDirectiveCVInlineLinetable();
553 bool parseDirectiveCVDefRange();
554 bool parseDirectiveCVString();
555 bool parseDirectiveCVStringTable();
556 bool parseDirectiveCVFileChecksums();
557 bool parseDirectiveCVFileChecksumOffset();
558 bool parseDirectiveCVFPOData();
561 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIWindowSave();
563 bool parseDirectiveCFISections();
564 bool parseDirectiveCFIStartProc();
565 bool parseDirectiveCFIEndProc();
566 bool parseDirectiveCFIDefCfaOffset();
567 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIAdjustCfaOffset();
569 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
570 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
571 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
572 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
573 bool parseDirectiveCFIRememberState();
574 bool parseDirectiveCFIRestoreState();
575 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
576 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
577 bool parseDirectiveCFIEscape();
578 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
579 bool parseDirectiveCFISignalFrame();
580 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
583 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
584 bool parseDirectiveExitMacro(StringRef Directive);
585 bool parseDirectiveEndMacro(StringRef Directive);
586 bool parseDirectiveMacro(SMLoc DirectiveLoc);
587 bool parseDirectiveMacrosOnOff(StringRef Directive);
588 // alternate macro mode directives
589 bool parseDirectiveAltmacro(StringRef Directive);
590 // ".bundle_align_mode"
591 bool parseDirectiveBundleAlignMode();
593 bool parseDirectiveBundleLock();
595 bool parseDirectiveBundleUnlock();
598 bool parseDirectiveSpace(StringRef IDVal);
601 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
602 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
604 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
606 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
607 bool parseDirectiveLEB128(bool Signed);
609 /// Parse a directive like ".globl" which
610 /// accepts a single symbol (which should be a label or an external).
611 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
613 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
615 bool parseDirectiveAbort(); // ".abort"
616 bool parseDirectiveInclude(); // ".include"
617 bool parseDirectiveIncbin(); // ".incbin"
619 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
620 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
621 // ".ifb" or ".ifnb", depending on ExpectBlank.
622 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
623 // ".ifc" or ".ifnc", depending on ExpectEqual.
624 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
625 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
626 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
627 // ".ifdef" or ".ifndef", depending on expect_defined
628 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
629 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
630 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
631 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
632 bool parseEscapedString(std::string &Data) override;
634 const MCExpr *applyModifierToExpr(const MCExpr *E,
635 MCSymbolRefExpr::VariantKind Variant);
637 // Macro-like directives
638 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
639 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
640 raw_svector_ostream &OS);
641 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
642 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
643 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
644 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
646 // "_emit" or "__emit"
647 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
651 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
654 bool parseDirectiveEnd(SMLoc DirectiveLoc);
656 // ".err" or ".error"
657 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
660 bool parseDirectiveWarning(SMLoc DirectiveLoc);
662 // .print <double-quotes-string>
663 bool parseDirectivePrint(SMLoc DirectiveLoc);
665 // Directives to support address-significance tables.
666 bool parseDirectiveAddrsig();
667 bool parseDirectiveAddrsigSym();
669 void initializeDirectiveKindMap();
672 } // end anonymous namespace
676 extern MCAsmParserExtension *createDarwinAsmParser();
677 extern MCAsmParserExtension *createELFAsmParser();
678 extern MCAsmParserExtension *createCOFFAsmParser();
679 extern MCAsmParserExtension *createWasmAsmParser();
681 } // end namespace llvm
683 enum { DEFAULT_ADDRSPACE = 0 };
685 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
686 const MCAsmInfo &MAI, unsigned CB = 0)
687 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
688 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
690 // Save the old handler.
691 SavedDiagHandler = SrcMgr.getDiagHandler();
692 SavedDiagContext = SrcMgr.getDiagContext();
693 // Set our own handler which calls the saved handler.
694 SrcMgr.setDiagHandler(DiagHandler, this);
695 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
697 // Initialize the platform / file format parser.
698 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
699 case MCObjectFileInfo::IsCOFF:
700 PlatformParser.reset(createCOFFAsmParser());
702 case MCObjectFileInfo::IsMachO:
703 PlatformParser.reset(createDarwinAsmParser());
706 case MCObjectFileInfo::IsELF:
707 PlatformParser.reset(createELFAsmParser());
709 case MCObjectFileInfo::IsWasm:
710 PlatformParser.reset(createWasmAsmParser());
714 PlatformParser->Initialize(*this);
715 initializeDirectiveKindMap();
717 NumOfMacroInstantiations = 0;
720 AsmParser::~AsmParser() {
721 assert((HadError || ActiveMacros.empty()) &&
722 "Unexpected active macro instantiation!");
724 // Restore the saved diagnostics handler and context for use during
726 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
729 void AsmParser::printMacroInstantiations() {
730 // Print the active macro instantiation stack.
731 for (std::vector<MacroInstantiation *>::const_reverse_iterator
732 it = ActiveMacros.rbegin(),
733 ie = ActiveMacros.rend();
735 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
736 "while in macro instantiation");
739 void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
740 printPendingErrors();
741 printMessage(L, SourceMgr::DK_Note, Msg, Range);
742 printMacroInstantiations();
745 bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
746 if(getTargetParser().getTargetOptions().MCNoWarn)
748 if (getTargetParser().getTargetOptions().MCFatalWarnings)
749 return Error(L, Msg, Range);
750 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
751 printMacroInstantiations();
755 bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
757 printMessage(L, SourceMgr::DK_Error, Msg, Range);
758 printMacroInstantiations();
762 bool AsmParser::enterIncludeFile(const std::string &Filename) {
763 std::string IncludedFile;
765 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
770 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
774 /// Process the specified .incbin file by searching for it in the include paths
775 /// then just emitting the byte contents of the file to the streamer. This
776 /// returns true on failure.
777 bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
778 const MCExpr *Count, SMLoc Loc) {
779 std::string IncludedFile;
781 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
785 // Pick up the bytes from the file and emit them.
786 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
787 Bytes = Bytes.drop_front(Skip);
790 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
791 return Error(Loc, "expected absolute expression");
793 return Warning(Loc, "negative count has no effect");
794 Bytes = Bytes.take_front(Res);
796 getStreamer().EmitBytes(Bytes);
800 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
801 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
802 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
806 const AsmToken &AsmParser::Lex() {
807 if (Lexer.getTok().is(AsmToken::Error))
808 Error(Lexer.getErrLoc(), Lexer.getErr());
810 // if it's a end of statement with a comment in it
811 if (getTok().is(AsmToken::EndOfStatement)) {
812 // if this is a line comment output it.
813 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
814 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
815 Out.addExplicitComment(Twine(getTok().getString()));
818 const AsmToken *tok = &Lexer.Lex();
820 // Parse comments here to be deferred until end of next statement.
821 while (tok->is(AsmToken::Comment)) {
822 if (MAI.preserveAsmComments())
823 Out.addExplicitComment(Twine(tok->getString()));
827 if (tok->is(AsmToken::Eof)) {
828 // If this is the end of an included file, pop the parent file off the
830 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
831 if (ParentIncludeLoc != SMLoc()) {
832 jumpToLoc(ParentIncludeLoc);
840 bool AsmParser::enabledGenDwarfForAssembly() {
841 // Check whether the user specified -g.
842 if (!getContext().getGenDwarfForAssembly())
844 // If we haven't encountered any .file directives (which would imply that
845 // the assembler source was produced with debug info already) then emit one
846 // describing the assembler source file itself.
847 if (getContext().getGenDwarfFileNumber() == 0)
848 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
849 0, StringRef(), getContext().getMainFileName()));
853 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
854 // Create the initial section, if requested.
855 if (!NoInitialTextSection)
856 Out.InitSections(false);
862 AsmCond StartingCondState = TheCondState;
863 SmallVector<AsmRewrite, 4> AsmStrRewrites;
865 // If we are generating dwarf for assembly source files save the initial text
866 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
867 // emitting any actual debug info yet and haven't had a chance to parse any
868 // embedded .file directives.)
869 if (getContext().getGenDwarfForAssembly()) {
870 MCSection *Sec = getStreamer().getCurrentSectionOnly();
871 if (!Sec->getBeginSymbol()) {
872 MCSymbol *SectionStartSym = getContext().createTempSymbol();
873 getStreamer().EmitLabel(SectionStartSym);
874 Sec->setBeginSymbol(SectionStartSym);
876 bool InsertResult = getContext().addGenDwarfSection(Sec);
877 assert(InsertResult && ".text section should not have debug info yet");
881 // While we have input, parse each statement.
882 while (Lexer.isNot(AsmToken::Eof)) {
883 ParseStatementInfo Info(&AsmStrRewrites);
884 if (!parseStatement(Info, nullptr))
887 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
888 // for printing ErrMsg via Lex() only if no (presumably better) parser error
890 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
894 // parseStatement returned true so may need to emit an error.
895 printPendingErrors();
897 // Skipping to the next line if needed.
898 if (!getLexer().isAtStartOfStatement())
899 eatToEndOfStatement();
902 getTargetParser().onEndOfFile();
903 printPendingErrors();
905 // All errors should have been emitted.
906 assert(!hasPendingError() && "unexpected error from parseStatement");
908 getTargetParser().flushPendingInstructions(getStreamer());
910 if (TheCondState.TheCond != StartingCondState.TheCond ||
911 TheCondState.Ignore != StartingCondState.Ignore)
912 printError(getTok().getLoc(), "unmatched .ifs or .elses");
913 // Check to see there are no empty DwarfFile slots.
914 const auto &LineTables = getContext().getMCDwarfLineTables();
915 if (!LineTables.empty()) {
917 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
918 if (File.Name.empty() && Index != 0)
919 printError(getTok().getLoc(), "unassigned file number: " +
921 " for .file directives");
926 // Check to see that all assembler local symbols were actually defined.
927 // Targets that don't do subsections via symbols may not want this, though,
928 // so conservatively exclude them. Only do this if we're finalizing, though,
929 // as otherwise we won't necessarilly have seen everything yet.
931 if (MAI.hasSubsectionsViaSymbols()) {
932 for (const auto &TableEntry : getContext().getSymbols()) {
933 MCSymbol *Sym = TableEntry.getValue();
934 // Variable symbols may not be marked as defined, so check those
935 // explicitly. If we know it's a variable, we have a definition for
936 // the purposes of this check.
937 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
938 // FIXME: We would really like to refer back to where the symbol was
939 // first referenced for a source location. We need to add something
940 // to track that. Currently, we just point to the end of the file.
941 printError(getTok().getLoc(), "assembler local symbol '" +
942 Sym->getName() + "' not defined");
946 // Temporary symbols like the ones for directional jumps don't go in the
947 // symbol table. They also need to be diagnosed in all (final) cases.
948 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
949 if (std::get<2>(LocSym)->isUndefined()) {
950 // Reset the state of any "# line file" directives we've seen to the
951 // context as it was at the diagnostic site.
952 CppHashInfo = std::get<1>(LocSym);
953 printError(std::get<0>(LocSym), "directional label undefined");
958 // Finalize the output stream if there are no errors and if the client wants
960 if (!HadError && !NoFinalize)
963 return HadError || getContext().hadError();
966 bool AsmParser::checkForValidSection() {
967 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
968 Out.InitSections(false);
969 return Error(getTok().getLoc(),
970 "expected section directive before assembly directive");
975 /// Throw away the rest of the line for testing purposes.
976 void AsmParser::eatToEndOfStatement() {
977 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
981 if (Lexer.is(AsmToken::EndOfStatement))
985 StringRef AsmParser::parseStringToEndOfStatement() {
986 const char *Start = getTok().getLoc().getPointer();
988 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
991 const char *End = getTok().getLoc().getPointer();
992 return StringRef(Start, End - Start);
995 StringRef AsmParser::parseStringToComma() {
996 const char *Start = getTok().getLoc().getPointer();
998 while (Lexer.isNot(AsmToken::EndOfStatement) &&
999 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
1002 const char *End = getTok().getLoc().getPointer();
1003 return StringRef(Start, End - Start);
1006 /// Parse a paren expression and return it.
1007 /// NOTE: This assumes the leading '(' has already been consumed.
1009 /// parenexpr ::= expr)
1011 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1012 if (parseExpression(Res))
1014 if (Lexer.isNot(AsmToken::RParen))
1015 return TokError("expected ')' in parentheses expression");
1016 EndLoc = Lexer.getTok().getEndLoc();
1021 /// Parse a bracket expression and return it.
1022 /// NOTE: This assumes the leading '[' has already been consumed.
1024 /// bracketexpr ::= expr]
1026 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1027 if (parseExpression(Res))
1029 EndLoc = getTok().getEndLoc();
1030 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1035 /// Parse a primary expression and return it.
1036 /// primaryexpr ::= (parenexpr
1037 /// primaryexpr ::= symbol
1038 /// primaryexpr ::= number
1039 /// primaryexpr ::= '.'
1040 /// primaryexpr ::= ~,+,- primaryexpr
1041 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1042 SMLoc FirstTokenLoc = getLexer().getLoc();
1043 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1044 switch (FirstTokenKind) {
1046 return TokError("unknown token in expression");
1047 // If we have an error assume that we've already handled it.
1048 case AsmToken::Error:
1050 case AsmToken::Exclaim:
1051 Lex(); // Eat the operator.
1052 if (parsePrimaryExpr(Res, EndLoc))
1054 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
1056 case AsmToken::Dollar:
1058 case AsmToken::String:
1059 case AsmToken::Identifier: {
1060 StringRef Identifier;
1061 if (parseIdentifier(Identifier)) {
1062 // We may have failed but $ may be a valid token.
1063 if (getTok().is(AsmToken::Dollar)) {
1064 if (Lexer.getMAI().getDollarIsPC()) {
1066 // This is a '$' reference, which references the current PC. Emit a
1067 // temporary label to the streamer and refer to it.
1068 MCSymbol *Sym = Ctx.createTempSymbol();
1070 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1072 EndLoc = FirstTokenLoc;
1075 return Error(FirstTokenLoc, "invalid token in expression");
1078 // Parse symbol variant
1079 std::pair<StringRef, StringRef> Split;
1080 if (!MAI.useParensForSymbolVariant()) {
1081 if (FirstTokenKind == AsmToken::String) {
1082 if (Lexer.is(AsmToken::At)) {
1084 SMLoc AtLoc = getLexer().getLoc();
1086 if (parseIdentifier(VName))
1087 return Error(AtLoc, "expected symbol variant after '@'");
1089 Split = std::make_pair(Identifier, VName);
1092 Split = Identifier.split('@');
1094 } else if (Lexer.is(AsmToken::LParen)) {
1097 parseIdentifier(VName);
1099 if (parseToken(AsmToken::RParen,
1100 "unexpected token in variant, expected ')'"))
1102 Split = std::make_pair(Identifier, VName);
1105 EndLoc = SMLoc::getFromPointer(Identifier.end());
1107 // This is a symbol reference.
1108 StringRef SymbolName = Identifier;
1109 if (SymbolName.empty())
1110 return Error(getLexer().getLoc(), "expected a symbol reference");
1112 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1114 // Lookup the symbol variant if used.
1115 if (!Split.second.empty()) {
1116 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1117 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1118 SymbolName = Split.first;
1119 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
1120 Variant = MCSymbolRefExpr::VK_None;
1122 return Error(SMLoc::getFromPointer(Split.second.begin()),
1123 "invalid variant '" + Split.second + "'");
1127 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
1129 // If this is an absolute variable reference, substitute it now to preserve
1130 // semantics in the face of reassignment.
1131 if (Sym->isVariable()) {
1132 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1133 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
1134 if (auto TV = dyn_cast<MCTargetExpr>(V))
1135 DoInline = TV->inlineAssignedExpr();
1138 return Error(EndLoc, "unexpected modifier on variable reference");
1139 Res = Sym->getVariableValue(/*SetUsed*/ false);
1144 // Otherwise create a symbol ref.
1145 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1148 case AsmToken::BigNum:
1149 return TokError("literal value out of range for directive");
1150 case AsmToken::Integer: {
1151 SMLoc Loc = getTok().getLoc();
1152 int64_t IntVal = getTok().getIntVal();
1153 Res = MCConstantExpr::create(IntVal, getContext());
1154 EndLoc = Lexer.getTok().getEndLoc();
1155 Lex(); // Eat token.
1156 // Look for 'b' or 'f' following an Integer as a directional label
1157 if (Lexer.getKind() == AsmToken::Identifier) {
1158 StringRef IDVal = getTok().getString();
1159 // Lookup the symbol variant if used.
1160 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1161 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1162 if (Split.first.size() != IDVal.size()) {
1163 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1164 if (Variant == MCSymbolRefExpr::VK_Invalid)
1165 return TokError("invalid variant '" + Split.second + "'");
1166 IDVal = Split.first;
1168 if (IDVal == "f" || IDVal == "b") {
1170 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1171 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1172 if (IDVal == "b" && Sym->isUndefined())
1173 return Error(Loc, "directional label undefined");
1174 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1175 EndLoc = Lexer.getTok().getEndLoc();
1176 Lex(); // Eat identifier.
1181 case AsmToken::Real: {
1182 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1183 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1184 Res = MCConstantExpr::create(IntVal, getContext());
1185 EndLoc = Lexer.getTok().getEndLoc();
1186 Lex(); // Eat token.
1189 case AsmToken::Dot: {
1190 // This is a '.' reference, which references the current PC. Emit a
1191 // temporary label to the streamer and refer to it.
1192 MCSymbol *Sym = Ctx.createTempSymbol();
1194 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1195 EndLoc = Lexer.getTok().getEndLoc();
1196 Lex(); // Eat identifier.
1199 case AsmToken::LParen:
1200 Lex(); // Eat the '('.
1201 return parseParenExpr(Res, EndLoc);
1202 case AsmToken::LBrac:
1203 if (!PlatformParser->HasBracketExpressions())
1204 return TokError("brackets expression not supported on this target");
1205 Lex(); // Eat the '['.
1206 return parseBracketExpr(Res, EndLoc);
1207 case AsmToken::Minus:
1208 Lex(); // Eat the operator.
1209 if (parsePrimaryExpr(Res, EndLoc))
1211 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1213 case AsmToken::Plus:
1214 Lex(); // Eat the operator.
1215 if (parsePrimaryExpr(Res, EndLoc))
1217 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1219 case AsmToken::Tilde:
1220 Lex(); // Eat the operator.
1221 if (parsePrimaryExpr(Res, EndLoc))
1223 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1225 // MIPS unary expression operators. The lexer won't generate these tokens if
1226 // MCAsmInfo::HasMipsExpressions is false for the target.
1227 case AsmToken::PercentCall16:
1228 case AsmToken::PercentCall_Hi:
1229 case AsmToken::PercentCall_Lo:
1230 case AsmToken::PercentDtprel_Hi:
1231 case AsmToken::PercentDtprel_Lo:
1232 case AsmToken::PercentGot:
1233 case AsmToken::PercentGot_Disp:
1234 case AsmToken::PercentGot_Hi:
1235 case AsmToken::PercentGot_Lo:
1236 case AsmToken::PercentGot_Ofst:
1237 case AsmToken::PercentGot_Page:
1238 case AsmToken::PercentGottprel:
1239 case AsmToken::PercentGp_Rel:
1240 case AsmToken::PercentHi:
1241 case AsmToken::PercentHigher:
1242 case AsmToken::PercentHighest:
1243 case AsmToken::PercentLo:
1244 case AsmToken::PercentNeg:
1245 case AsmToken::PercentPcrel_Hi:
1246 case AsmToken::PercentPcrel_Lo:
1247 case AsmToken::PercentTlsgd:
1248 case AsmToken::PercentTlsldm:
1249 case AsmToken::PercentTprel_Hi:
1250 case AsmToken::PercentTprel_Lo:
1251 Lex(); // Eat the operator.
1252 if (Lexer.isNot(AsmToken::LParen))
1253 return TokError("expected '(' after operator");
1254 Lex(); // Eat the operator.
1255 if (parseExpression(Res, EndLoc))
1257 if (Lexer.isNot(AsmToken::RParen))
1258 return TokError("expected ')'");
1259 Lex(); // Eat the operator.
1260 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1265 bool AsmParser::parseExpression(const MCExpr *&Res) {
1267 return parseExpression(Res, EndLoc);
1271 AsmParser::applyModifierToExpr(const MCExpr *E,
1272 MCSymbolRefExpr::VariantKind Variant) {
1273 // Ask the target implementation about this expression first.
1274 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1277 // Recurse over the given expression, rebuilding it to apply the given variant
1278 // if there is exactly one symbol.
1279 switch (E->getKind()) {
1280 case MCExpr::Target:
1281 case MCExpr::Constant:
1284 case MCExpr::SymbolRef: {
1285 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1287 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1288 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1289 "' (already modified)");
1293 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1296 case MCExpr::Unary: {
1297 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1298 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1301 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1304 case MCExpr::Binary: {
1305 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1306 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1307 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1317 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1321 llvm_unreachable("Invalid expression kind!");
1324 /// This function checks if the next token is <string> type or arithmetic.
1325 /// string that begin with character '<' must end with character '>'.
1326 /// otherwise it is arithmetics.
1327 /// If the function returns a 'true' value,
1328 /// the End argument will be filled with the last location pointed to the '>'
1331 /// There is a gap between the AltMacro's documentation and the single quote
1332 /// implementation. GCC does not fully support this feature and so we will not
1334 /// TODO: Adding single quote as a string.
1335 static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1336 assert((StrLoc.getPointer() != nullptr) &&
1337 "Argument to the function cannot be a NULL value");
1338 const char *CharPtr = StrLoc.getPointer();
1339 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1340 (*CharPtr != '\0')) {
1341 if (*CharPtr == '!')
1345 if (*CharPtr == '>') {
1346 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1352 /// creating a string without the escape characters '!'.
1353 static std::string altMacroString(StringRef AltMacroStr) {
1355 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1356 if (AltMacroStr[Pos] == '!')
1358 Res += AltMacroStr[Pos];
1363 /// Parse an expression and return it.
1365 /// expr ::= expr &&,|| expr -> lowest.
1366 /// expr ::= expr |,^,&,! expr
1367 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1368 /// expr ::= expr <<,>> expr
1369 /// expr ::= expr +,- expr
1370 /// expr ::= expr *,/,% expr -> highest.
1371 /// expr ::= primaryexpr
1373 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1374 // Parse the expression.
1376 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1377 parseBinOpRHS(1, Res, EndLoc))
1380 // As a special case, we support 'a op b @ modifier' by rewriting the
1381 // expression to include the modifier. This is inefficient, but in general we
1382 // expect users to use 'a@modifier op b'.
1383 if (Lexer.getKind() == AsmToken::At) {
1386 if (Lexer.isNot(AsmToken::Identifier))
1387 return TokError("unexpected symbol modifier following '@'");
1389 MCSymbolRefExpr::VariantKind Variant =
1390 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1391 if (Variant == MCSymbolRefExpr::VK_Invalid)
1392 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1394 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1396 return TokError("invalid modifier '" + getTok().getIdentifier() +
1397 "' (no symbols present)");
1404 // Try to constant fold it up front, if possible. Do not exploit
1407 if (Res->evaluateAsAbsolute(Value))
1408 Res = MCConstantExpr::create(Value, getContext());
1413 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1415 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1418 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1420 if (parseParenExpr(Res, EndLoc))
1423 for (; ParenDepth > 0; --ParenDepth) {
1424 if (parseBinOpRHS(1, Res, EndLoc))
1427 // We don't Lex() the last RParen.
1428 // This is the same behavior as parseParenExpression().
1429 if (ParenDepth - 1 > 0) {
1430 EndLoc = getTok().getEndLoc();
1431 if (parseToken(AsmToken::RParen,
1432 "expected ')' in parentheses expression"))
1439 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1442 SMLoc StartLoc = Lexer.getLoc();
1443 if (parseExpression(Expr))
1446 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
1447 return Error(StartLoc, "expected absolute expression");
1452 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1453 MCBinaryExpr::Opcode &Kind,
1454 bool ShouldUseLogicalShr) {
1457 return 0; // not a binop.
1459 // Lowest Precedence: &&, ||
1460 case AsmToken::AmpAmp:
1461 Kind = MCBinaryExpr::LAnd;
1463 case AsmToken::PipePipe:
1464 Kind = MCBinaryExpr::LOr;
1467 // Low Precedence: |, &, ^
1469 // FIXME: gas seems to support '!' as an infix operator?
1470 case AsmToken::Pipe:
1471 Kind = MCBinaryExpr::Or;
1473 case AsmToken::Caret:
1474 Kind = MCBinaryExpr::Xor;
1477 Kind = MCBinaryExpr::And;
1480 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1481 case AsmToken::EqualEqual:
1482 Kind = MCBinaryExpr::EQ;
1484 case AsmToken::ExclaimEqual:
1485 case AsmToken::LessGreater:
1486 Kind = MCBinaryExpr::NE;
1488 case AsmToken::Less:
1489 Kind = MCBinaryExpr::LT;
1491 case AsmToken::LessEqual:
1492 Kind = MCBinaryExpr::LTE;
1494 case AsmToken::Greater:
1495 Kind = MCBinaryExpr::GT;
1497 case AsmToken::GreaterEqual:
1498 Kind = MCBinaryExpr::GTE;
1501 // Intermediate Precedence: <<, >>
1502 case AsmToken::LessLess:
1503 Kind = MCBinaryExpr::Shl;
1505 case AsmToken::GreaterGreater:
1506 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1509 // High Intermediate Precedence: +, -
1510 case AsmToken::Plus:
1511 Kind = MCBinaryExpr::Add;
1513 case AsmToken::Minus:
1514 Kind = MCBinaryExpr::Sub;
1517 // Highest Precedence: *, /, %
1518 case AsmToken::Star:
1519 Kind = MCBinaryExpr::Mul;
1521 case AsmToken::Slash:
1522 Kind = MCBinaryExpr::Div;
1524 case AsmToken::Percent:
1525 Kind = MCBinaryExpr::Mod;
1530 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1531 MCBinaryExpr::Opcode &Kind,
1532 bool ShouldUseLogicalShr) {
1535 return 0; // not a binop.
1537 // Lowest Precedence: &&, ||
1538 case AsmToken::AmpAmp:
1539 Kind = MCBinaryExpr::LAnd;
1541 case AsmToken::PipePipe:
1542 Kind = MCBinaryExpr::LOr;
1545 // Low Precedence: ==, !=, <>, <, <=, >, >=
1546 case AsmToken::EqualEqual:
1547 Kind = MCBinaryExpr::EQ;
1549 case AsmToken::ExclaimEqual:
1550 case AsmToken::LessGreater:
1551 Kind = MCBinaryExpr::NE;
1553 case AsmToken::Less:
1554 Kind = MCBinaryExpr::LT;
1556 case AsmToken::LessEqual:
1557 Kind = MCBinaryExpr::LTE;
1559 case AsmToken::Greater:
1560 Kind = MCBinaryExpr::GT;
1562 case AsmToken::GreaterEqual:
1563 Kind = MCBinaryExpr::GTE;
1566 // Low Intermediate Precedence: +, -
1567 case AsmToken::Plus:
1568 Kind = MCBinaryExpr::Add;
1570 case AsmToken::Minus:
1571 Kind = MCBinaryExpr::Sub;
1574 // High Intermediate Precedence: |, &, ^
1576 // FIXME: gas seems to support '!' as an infix operator?
1577 case AsmToken::Pipe:
1578 Kind = MCBinaryExpr::Or;
1580 case AsmToken::Caret:
1581 Kind = MCBinaryExpr::Xor;
1584 Kind = MCBinaryExpr::And;
1587 // Highest Precedence: *, /, %, <<, >>
1588 case AsmToken::Star:
1589 Kind = MCBinaryExpr::Mul;
1591 case AsmToken::Slash:
1592 Kind = MCBinaryExpr::Div;
1594 case AsmToken::Percent:
1595 Kind = MCBinaryExpr::Mod;
1597 case AsmToken::LessLess:
1598 Kind = MCBinaryExpr::Shl;
1600 case AsmToken::GreaterGreater:
1601 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1606 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1607 MCBinaryExpr::Opcode &Kind) {
1608 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1609 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1610 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1613 /// Parse all binary operators with precedence >= 'Precedence'.
1614 /// Res contains the LHS of the expression on input.
1615 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1617 SMLoc StartLoc = Lexer.getLoc();
1619 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1620 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1622 // If the next token is lower precedence than we are allowed to eat, return
1623 // successfully with what we ate already.
1624 if (TokPrec < Precedence)
1629 // Eat the next primary expression.
1631 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
1634 // If BinOp binds less tightly with RHS than the operator after RHS, let
1635 // the pending operator take RHS as its LHS.
1636 MCBinaryExpr::Opcode Dummy;
1637 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1638 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1641 // Merge LHS and RHS according to operator.
1642 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1647 /// ::= EndOfStatement
1648 /// ::= Label* Directive ...Operands... EndOfStatement
1649 /// ::= Label* Identifier OperandList* EndOfStatement
1650 bool AsmParser::parseStatement(ParseStatementInfo &Info,
1651 MCAsmParserSemaCallback *SI) {
1652 assert(!hasPendingError() && "parseStatement started with pending error");
1653 // Eat initial spaces and comments
1654 while (Lexer.is(AsmToken::Space))
1656 if (Lexer.is(AsmToken::EndOfStatement)) {
1657 // if this is a line comment we can drop it safely
1658 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1659 getTok().getString().front() == '\n')
1664 // Statements always start with an identifier.
1665 AsmToken ID = getTok();
1666 SMLoc IDLoc = ID.getLoc();
1668 int64_t LocalLabelVal = -1;
1669 if (Lexer.is(AsmToken::HashDirective))
1670 return parseCppHashLineFilenameComment(IDLoc);
1671 // Allow an integer followed by a ':' as a directional local label.
1672 if (Lexer.is(AsmToken::Integer)) {
1673 LocalLabelVal = getTok().getIntVal();
1674 if (LocalLabelVal < 0) {
1675 if (!TheCondState.Ignore) {
1676 Lex(); // always eat a token
1677 return Error(IDLoc, "unexpected token at start of statement");
1681 IDVal = getTok().getString();
1682 Lex(); // Consume the integer token to be used as an identifier token.
1683 if (Lexer.getKind() != AsmToken::Colon) {
1684 if (!TheCondState.Ignore) {
1685 Lex(); // always eat a token
1686 return Error(IDLoc, "unexpected token at start of statement");
1690 } else if (Lexer.is(AsmToken::Dot)) {
1691 // Treat '.' as a valid identifier in this context.
1694 } else if (Lexer.is(AsmToken::LCurly)) {
1695 // Treat '{' as a valid identifier in this context.
1699 } else if (Lexer.is(AsmToken::RCurly)) {
1700 // Treat '}' as a valid identifier in this context.
1703 } else if (Lexer.is(AsmToken::Star) &&
1704 getTargetParser().starIsStartOfStatement()) {
1705 // Accept '*' as a valid start of statement.
1708 } else if (parseIdentifier(IDVal)) {
1709 if (!TheCondState.Ignore) {
1710 Lex(); // always eat a token
1711 return Error(IDLoc, "unexpected token at start of statement");
1716 // Handle conditional assembly here before checking for skipping. We
1717 // have to do this so that .endif isn't skipped in a ".if 0" block for
1719 StringMap<DirectiveKind>::const_iterator DirKindIt =
1720 DirectiveKindMap.find(IDVal);
1721 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1723 : DirKindIt->getValue();
1734 return parseDirectiveIf(IDLoc, DirKind);
1736 return parseDirectiveIfb(IDLoc, true);
1738 return parseDirectiveIfb(IDLoc, false);
1740 return parseDirectiveIfc(IDLoc, true);
1742 return parseDirectiveIfeqs(IDLoc, true);
1744 return parseDirectiveIfc(IDLoc, false);
1746 return parseDirectiveIfeqs(IDLoc, false);
1748 return parseDirectiveIfdef(IDLoc, true);
1751 return parseDirectiveIfdef(IDLoc, false);
1753 return parseDirectiveElseIf(IDLoc);
1755 return parseDirectiveElse(IDLoc);
1757 return parseDirectiveEndIf(IDLoc);
1760 // Ignore the statement if in the middle of inactive conditional
1762 if (TheCondState.Ignore) {
1763 eatToEndOfStatement();
1767 // FIXME: Recurse on local labels?
1769 // See what kind of statement we have.
1770 switch (Lexer.getKind()) {
1771 case AsmToken::Colon: {
1772 if (!getTargetParser().isLabel(ID))
1774 if (checkForValidSection())
1777 // identifier ':' -> Label.
1780 // Diagnose attempt to use '.' as a label.
1782 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1784 // Diagnose attempt to use a variable as a label.
1786 // FIXME: Diagnostics. Note the location of the definition as a label.
1787 // FIXME: This doesn't diagnose assignment to a symbol which has been
1788 // implicitly marked as external.
1790 if (LocalLabelVal == -1) {
1791 if (ParsingInlineAsm && SI) {
1792 StringRef RewrittenLabel =
1793 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1794 assert(!RewrittenLabel.empty() &&
1795 "We should have an internal name here.");
1796 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1798 IDVal = RewrittenLabel;
1800 Sym = getContext().getOrCreateSymbol(IDVal);
1802 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1803 // End of Labels should be treated as end of line for lexing
1804 // purposes but that information is not available to the Lexer who
1805 // does not understand Labels. This may cause us to see a Hash
1806 // here instead of a preprocessor line comment.
1807 if (getTok().is(AsmToken::Hash)) {
1808 StringRef CommentStr = parseStringToEndOfStatement();
1810 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1813 // Consume any end of statement token, if present, to avoid spurious
1814 // AddBlankLine calls().
1815 if (getTok().is(AsmToken::EndOfStatement)) {
1819 getTargetParser().doBeforeLabelEmit(Sym);
1822 if (!getTargetParser().isParsingInlineAsm())
1823 Out.EmitLabel(Sym, IDLoc);
1825 // If we are generating dwarf for assembly source files then gather the
1826 // info to make a dwarf label entry for this label if needed.
1827 if (enabledGenDwarfForAssembly())
1828 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1831 getTargetParser().onLabelParsed(Sym);
1836 case AsmToken::Equal:
1837 if (!getTargetParser().equalIsAsmAssignment())
1839 // identifier '=' ... -> assignment statement
1842 return parseAssignment(IDVal, true);
1844 default: // Normal instruction or directive.
1848 // If macros are enabled, check to see if this is a macro instantiation.
1849 if (areMacrosEnabled())
1850 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1851 return handleMacroEntry(M, IDLoc);
1854 // Otherwise, we have a normal instruction or directive.
1856 // Directives start with "."
1857 if (IDVal.startswith(".") && IDVal != ".") {
1858 // There are several entities interested in parsing directives:
1860 // 1. The target-specific assembly parser. Some directives are target
1861 // specific or may potentially behave differently on certain targets.
1862 // 2. Asm parser extensions. For example, platform-specific parsers
1863 // (like the ELF parser) register themselves as extensions.
1864 // 3. The generic directive parser implemented by this class. These are
1865 // all the directives that behave in a target and platform independent
1866 // manner, or at least have a default behavior that's shared between
1867 // all targets and platforms.
1869 getTargetParser().flushPendingInstructions(getStreamer());
1871 SMLoc StartTokLoc = getTok().getLoc();
1872 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1874 if (hasPendingError())
1876 // Currently the return value should be true if we are
1877 // uninterested but as this is at odds with the standard parsing
1878 // convention (return true = error) we have instances of a parsed
1879 // directive that fails returning true as an error. Catch these
1880 // cases as best as possible errors here.
1881 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1883 // Return if we did some parsing or believe we succeeded.
1884 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1887 // Next, check the extension directive map to see if any extension has
1888 // registered itself to parse this directive.
1889 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1890 ExtensionDirectiveMap.lookup(IDVal);
1892 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1894 // Finally, if no one else is interested in this directive, it must be
1895 // generic and familiar to this class.
1901 return parseDirectiveSet(IDVal, true);
1903 return parseDirectiveSet(IDVal, false);
1905 return parseDirectiveAscii(IDVal, false);
1908 return parseDirectiveAscii(IDVal, true);
1911 return parseDirectiveValue(IDVal, 1);
1917 return parseDirectiveValue(IDVal, 2);
1922 return parseDirectiveValue(IDVal, 4);
1925 return parseDirectiveValue(IDVal, 8);
1927 return parseDirectiveValue(
1928 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1930 return parseDirectiveOctaValue(IDVal);
1934 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1937 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1939 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1940 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1943 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1944 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1947 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1949 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1951 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1953 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1955 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1957 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1959 return parseDirectiveOrg();
1961 return parseDirectiveFill();
1963 return parseDirectiveZero();
1965 eatToEndOfStatement(); // .extern is the default, ignore it.
1969 return parseDirectiveSymbolAttribute(MCSA_Global);
1970 case DK_LAZY_REFERENCE:
1971 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1972 case DK_NO_DEAD_STRIP:
1973 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1974 case DK_SYMBOL_RESOLVER:
1975 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1976 case DK_PRIVATE_EXTERN:
1977 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1979 return parseDirectiveSymbolAttribute(MCSA_Reference);
1980 case DK_WEAK_DEFINITION:
1981 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1982 case DK_WEAK_REFERENCE:
1983 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1984 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1985 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1988 return parseDirectiveComm(/*IsLocal=*/false);
1990 return parseDirectiveComm(/*IsLocal=*/true);
1992 return parseDirectiveAbort();
1994 return parseDirectiveInclude();
1996 return parseDirectiveIncbin();
1999 return TokError(Twine(IDVal) +
2000 " not currently supported for this target");
2002 return parseDirectiveRept(IDLoc, IDVal);
2004 return parseDirectiveIrp(IDLoc);
2006 return parseDirectiveIrpc(IDLoc);
2008 return parseDirectiveEndr(IDLoc);
2009 case DK_BUNDLE_ALIGN_MODE:
2010 return parseDirectiveBundleAlignMode();
2011 case DK_BUNDLE_LOCK:
2012 return parseDirectiveBundleLock();
2013 case DK_BUNDLE_UNLOCK:
2014 return parseDirectiveBundleUnlock();
2016 return parseDirectiveLEB128(true);
2018 return parseDirectiveLEB128(false);
2021 return parseDirectiveSpace(IDVal);
2023 return parseDirectiveFile(IDLoc);
2025 return parseDirectiveLine();
2027 return parseDirectiveLoc();
2029 return parseDirectiveStabs();
2031 return parseDirectiveCVFile();
2033 return parseDirectiveCVFuncId();
2034 case DK_CV_INLINE_SITE_ID:
2035 return parseDirectiveCVInlineSiteId();
2037 return parseDirectiveCVLoc();
2038 case DK_CV_LINETABLE:
2039 return parseDirectiveCVLinetable();
2040 case DK_CV_INLINE_LINETABLE:
2041 return parseDirectiveCVInlineLinetable();
2042 case DK_CV_DEF_RANGE:
2043 return parseDirectiveCVDefRange();
2045 return parseDirectiveCVString();
2046 case DK_CV_STRINGTABLE:
2047 return parseDirectiveCVStringTable();
2048 case DK_CV_FILECHECKSUMS:
2049 return parseDirectiveCVFileChecksums();
2050 case DK_CV_FILECHECKSUM_OFFSET:
2051 return parseDirectiveCVFileChecksumOffset();
2052 case DK_CV_FPO_DATA:
2053 return parseDirectiveCVFPOData();
2054 case DK_CFI_SECTIONS:
2055 return parseDirectiveCFISections();
2056 case DK_CFI_STARTPROC:
2057 return parseDirectiveCFIStartProc();
2058 case DK_CFI_ENDPROC:
2059 return parseDirectiveCFIEndProc();
2060 case DK_CFI_DEF_CFA:
2061 return parseDirectiveCFIDefCfa(IDLoc);
2062 case DK_CFI_DEF_CFA_OFFSET:
2063 return parseDirectiveCFIDefCfaOffset();
2064 case DK_CFI_ADJUST_CFA_OFFSET:
2065 return parseDirectiveCFIAdjustCfaOffset();
2066 case DK_CFI_DEF_CFA_REGISTER:
2067 return parseDirectiveCFIDefCfaRegister(IDLoc);
2069 return parseDirectiveCFIOffset(IDLoc);
2070 case DK_CFI_REL_OFFSET:
2071 return parseDirectiveCFIRelOffset(IDLoc);
2072 case DK_CFI_PERSONALITY:
2073 return parseDirectiveCFIPersonalityOrLsda(true);
2075 return parseDirectiveCFIPersonalityOrLsda(false);
2076 case DK_CFI_REMEMBER_STATE:
2077 return parseDirectiveCFIRememberState();
2078 case DK_CFI_RESTORE_STATE:
2079 return parseDirectiveCFIRestoreState();
2080 case DK_CFI_SAME_VALUE:
2081 return parseDirectiveCFISameValue(IDLoc);
2082 case DK_CFI_RESTORE:
2083 return parseDirectiveCFIRestore(IDLoc);
2085 return parseDirectiveCFIEscape();
2086 case DK_CFI_RETURN_COLUMN:
2087 return parseDirectiveCFIReturnColumn(IDLoc);
2088 case DK_CFI_SIGNAL_FRAME:
2089 return parseDirectiveCFISignalFrame();
2090 case DK_CFI_UNDEFINED:
2091 return parseDirectiveCFIUndefined(IDLoc);
2092 case DK_CFI_REGISTER:
2093 return parseDirectiveCFIRegister(IDLoc);
2094 case DK_CFI_WINDOW_SAVE:
2095 return parseDirectiveCFIWindowSave();
2098 return parseDirectiveMacrosOnOff(IDVal);
2100 return parseDirectiveMacro(IDLoc);
2103 return parseDirectiveAltmacro(IDVal);
2105 return parseDirectiveExitMacro(IDVal);
2108 return parseDirectiveEndMacro(IDVal);
2110 return parseDirectivePurgeMacro(IDLoc);
2112 return parseDirectiveEnd(IDLoc);
2114 return parseDirectiveError(IDLoc, false);
2116 return parseDirectiveError(IDLoc, true);
2118 return parseDirectiveWarning(IDLoc);
2120 return parseDirectiveReloc(IDLoc);
2123 return parseDirectiveDCB(IDVal, 2);
2125 return parseDirectiveDCB(IDVal, 1);
2127 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2129 return parseDirectiveDCB(IDVal, 4);
2131 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2134 return TokError(Twine(IDVal) +
2135 " not currently supported for this target");
2138 return parseDirectiveDS(IDVal, 2);
2140 return parseDirectiveDS(IDVal, 1);
2142 return parseDirectiveDS(IDVal, 8);
2145 return parseDirectiveDS(IDVal, 4);
2148 return parseDirectiveDS(IDVal, 12);
2150 return parseDirectivePrint(IDLoc);
2152 return parseDirectiveAddrsig();
2153 case DK_ADDRSIG_SYM:
2154 return parseDirectiveAddrsigSym();
2157 return Error(IDLoc, "unknown directive");
2160 // __asm _emit or __asm __emit
2161 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2162 IDVal == "_EMIT" || IDVal == "__EMIT"))
2163 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2166 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2167 return parseDirectiveMSAlign(IDLoc, Info);
2169 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2170 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2171 if (checkForValidSection())
2174 // Canonicalize the opcode to lower case.
2175 std::string OpcodeStr = IDVal.lower();
2176 ParseInstructionInfo IInfo(Info.AsmRewrites);
2177 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2178 Info.ParsedOperands);
2179 Info.ParseError = ParseHadError;
2181 // Dump the parsed representation, if requested.
2182 if (getShowParsedOperands()) {
2183 SmallString<256> Str;
2184 raw_svector_ostream OS(Str);
2185 OS << "parsed instruction: [";
2186 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2189 Info.ParsedOperands[i]->print(OS);
2193 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2196 // Fail even if ParseInstruction erroneously returns false.
2197 if (hasPendingError() || ParseHadError)
2200 // If we are generating dwarf for the current section then generate a .loc
2201 // directive for the instruction.
2202 if (!ParseHadError && enabledGenDwarfForAssembly() &&
2203 getContext().getGenDwarfSectionSyms().count(
2204 getStreamer().getCurrentSectionOnly())) {
2206 if (ActiveMacros.empty())
2207 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2209 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2210 ActiveMacros.front()->ExitBuffer);
2212 // If we previously parsed a cpp hash file line comment then make sure the
2213 // current Dwarf File is for the CppHashFilename if not then emit the
2214 // Dwarf File table for it and adjust the line number for the .loc.
2215 if (!CppHashInfo.Filename.empty()) {
2216 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2217 0, StringRef(), CppHashInfo.Filename);
2218 getContext().setGenDwarfFileNumber(FileNumber);
2220 unsigned CppHashLocLineNo =
2221 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2222 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2225 getStreamer().EmitDwarfLocDirective(
2226 getContext().getGenDwarfFileNumber(), Line, 0,
2227 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2231 // If parsing succeeded, match the instruction.
2232 if (!ParseHadError) {
2234 if (getTargetParser().MatchAndEmitInstruction(
2235 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2236 getTargetParser().isParsingInlineAsm()))
2242 // Parse and erase curly braces marking block start/end
2244 AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2245 // Identify curly brace marking block start/end
2246 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2249 SMLoc StartLoc = Lexer.getLoc();
2250 Lex(); // Eat the brace
2251 if (Lexer.is(AsmToken::EndOfStatement))
2252 Lex(); // Eat EndOfStatement following the brace
2254 // Erase the block start/end brace from the output asm string
2255 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2256 StartLoc.getPointer());
2260 /// parseCppHashLineFilenameComment as this:
2261 /// ::= # number "filename"
2262 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2263 Lex(); // Eat the hash token.
2264 // Lexer only ever emits HashDirective if it fully formed if it's
2265 // done the checking already so this is an internal error.
2266 assert(getTok().is(AsmToken::Integer) &&
2267 "Lexing Cpp line comment: Expected Integer");
2268 int64_t LineNumber = getTok().getIntVal();
2270 assert(getTok().is(AsmToken::String) &&
2271 "Lexing Cpp line comment: Expected String");
2272 StringRef Filename = getTok().getString();
2275 // Get rid of the enclosing quotes.
2276 Filename = Filename.substr(1, Filename.size() - 2);
2278 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2279 CppHashInfo.Loc = L;
2280 CppHashInfo.Filename = Filename;
2281 CppHashInfo.LineNumber = LineNumber;
2282 CppHashInfo.Buf = CurBuffer;
2286 /// will use the last parsed cpp hash line filename comment
2287 /// for the Filename and LineNo if any in the diagnostic.
2288 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2289 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2290 raw_ostream &OS = errs();
2292 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2293 SMLoc DiagLoc = Diag.getLoc();
2294 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2295 unsigned CppHashBuf =
2296 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2298 // Like SourceMgr::printMessage() we need to print the include stack if any
2299 // before printing the message.
2300 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2301 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2302 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2303 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2304 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2307 // If we have not parsed a cpp hash line filename comment or the source
2308 // manager changed or buffer changed (like in a nested include) then just
2309 // print the normal diagnostic using its Filename and LineNo.
2310 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2311 DiagBuf != CppHashBuf) {
2312 if (Parser->SavedDiagHandler)
2313 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2315 Diag.print(nullptr, OS);
2319 // Use the CppHashFilename and calculate a line number based on the
2320 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2321 // for the diagnostic.
2322 const std::string &Filename = Parser->CppHashInfo.Filename;
2324 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2325 int CppHashLocLineNo =
2326 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2328 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2330 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2331 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2332 Diag.getLineContents(), Diag.getRanges());
2334 if (Parser->SavedDiagHandler)
2335 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2337 NewDiag.print(nullptr, OS);
2340 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2341 // difference being that that function accepts '@' as part of identifiers and
2342 // we can't do that. AsmLexer.cpp should probably be changed to handle
2343 // '@' as a special case when needed.
2344 static bool isIdentifierChar(char c) {
2345 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2349 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2350 ArrayRef<MCAsmMacroParameter> Parameters,
2351 ArrayRef<MCAsmMacroArgument> A,
2352 bool EnableAtPseudoVariable, SMLoc L) {
2353 unsigned NParameters = Parameters.size();
2354 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2355 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2356 return Error(L, "Wrong number of arguments");
2358 // A macro without parameters is handled differently on Darwin:
2359 // gas accepts no arguments and does no substitutions
2360 while (!Body.empty()) {
2361 // Scan for the next substitution.
2362 std::size_t End = Body.size(), Pos = 0;
2363 for (; Pos != End; ++Pos) {
2364 // Check for a substitution or escape.
2365 if (IsDarwin && !NParameters) {
2366 // This macro has no parameters, look for $0, $1, etc.
2367 if (Body[Pos] != '$' || Pos + 1 == End)
2370 char Next = Body[Pos + 1];
2371 if (Next == '$' || Next == 'n' ||
2372 isdigit(static_cast<unsigned char>(Next)))
2375 // This macro has parameters, look for \foo, \bar, etc.
2376 if (Body[Pos] == '\\' && Pos + 1 != End)
2382 OS << Body.slice(0, Pos);
2384 // Check if we reached the end.
2388 if (IsDarwin && !NParameters) {
2389 switch (Body[Pos + 1]) {
2395 // $n => number of arguments
2400 // $[0-9] => argument
2402 // Missing arguments are ignored.
2403 unsigned Index = Body[Pos + 1] - '0';
2404 if (Index >= A.size())
2407 // Otherwise substitute with the token values, with spaces eliminated.
2408 for (const AsmToken &Token : A[Index])
2409 OS << Token.getString();
2415 unsigned I = Pos + 1;
2417 // Check for the \@ pseudo-variable.
2418 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2421 while (isIdentifierChar(Body[I]) && I + 1 != End)
2424 const char *Begin = Body.data() + Pos + 1;
2425 StringRef Argument(Begin, I - (Pos + 1));
2428 if (Argument == "@") {
2429 OS << NumOfMacroInstantiations;
2432 for (; Index < NParameters; ++Index)
2433 if (Parameters[Index].Name == Argument)
2436 if (Index == NParameters) {
2437 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2440 OS << '\\' << Argument;
2444 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2445 for (const AsmToken &Token : A[Index])
2446 // For altmacro mode, you can write '%expr'.
2447 // The prefix '%' evaluates the expression 'expr'
2448 // and uses the result as a string (e.g. replace %(1+2) with the
2450 // Here, we identify the integer token which is the result of the
2451 // absolute expression evaluation and replace it with its string
2453 if (AltMacroMode && Token.getString().front() == '%' &&
2454 Token.is(AsmToken::Integer))
2455 // Emit an integer value to the buffer.
2456 OS << Token.getIntVal();
2457 // Only Token that was validated as a string and begins with '<'
2458 // is considered altMacroString!!!
2459 else if (AltMacroMode && Token.getString().front() == '<' &&
2460 Token.is(AsmToken::String)) {
2461 OS << altMacroString(Token.getStringContents());
2463 // We expect no quotes around the string's contents when
2464 // parsing for varargs.
2465 else if (Token.isNot(AsmToken::String) || VarargParameter)
2466 OS << Token.getString();
2468 OS << Token.getStringContents();
2470 Pos += 1 + Argument.size();
2474 // Update the scan point.
2475 Body = Body.substr(Pos);
2481 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2482 size_t CondStackDepth)
2483 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2484 CondStackDepth(CondStackDepth) {}
2486 static bool isOperator(AsmToken::TokenKind kind) {
2490 case AsmToken::Plus:
2491 case AsmToken::Minus:
2492 case AsmToken::Tilde:
2493 case AsmToken::Slash:
2494 case AsmToken::Star:
2496 case AsmToken::Equal:
2497 case AsmToken::EqualEqual:
2498 case AsmToken::Pipe:
2499 case AsmToken::PipePipe:
2500 case AsmToken::Caret:
2502 case AsmToken::AmpAmp:
2503 case AsmToken::Exclaim:
2504 case AsmToken::ExclaimEqual:
2505 case AsmToken::Less:
2506 case AsmToken::LessEqual:
2507 case AsmToken::LessLess:
2508 case AsmToken::LessGreater:
2509 case AsmToken::Greater:
2510 case AsmToken::GreaterEqual:
2511 case AsmToken::GreaterGreater:
2518 class AsmLexerSkipSpaceRAII {
2520 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2521 Lexer.setSkipSpace(SkipSpace);
2524 ~AsmLexerSkipSpaceRAII() {
2525 Lexer.setSkipSpace(true);
2532 } // end anonymous namespace
2534 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2537 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2538 StringRef Str = parseStringToEndOfStatement();
2539 MA.emplace_back(AsmToken::String, Str);
2544 unsigned ParenLevel = 0;
2546 // Darwin doesn't use spaces to delmit arguments.
2547 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2553 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2554 return TokError("unexpected token in macro instantiation");
2556 if (ParenLevel == 0) {
2558 if (Lexer.is(AsmToken::Comma))
2561 if (Lexer.is(AsmToken::Space)) {
2563 Lexer.Lex(); // Eat spaces
2566 // Spaces can delimit parameters, but could also be part an expression.
2567 // If the token after a space is an operator, add the token and the next
2568 // one into this argument
2570 if (isOperator(Lexer.getKind())) {
2571 MA.push_back(getTok());
2574 // Whitespace after an operator can be ignored.
2575 if (Lexer.is(AsmToken::Space))
2585 // handleMacroEntry relies on not advancing the lexer here
2586 // to be able to fill in the remaining default parameter values
2587 if (Lexer.is(AsmToken::EndOfStatement))
2590 // Adjust the current parentheses level.
2591 if (Lexer.is(AsmToken::LParen))
2593 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2596 // Append the token to the current argument list.
2597 MA.push_back(getTok());
2601 if (ParenLevel != 0)
2602 return TokError("unbalanced parentheses in macro argument");
2606 // Parse the macro instantiation arguments.
2607 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2608 MCAsmMacroArguments &A) {
2609 const unsigned NParameters = M ? M->Parameters.size() : 0;
2610 bool NamedParametersFound = false;
2611 SmallVector<SMLoc, 4> FALocs;
2613 A.resize(NParameters);
2614 FALocs.resize(NParameters);
2616 // Parse two kinds of macro invocations:
2617 // - macros defined without any parameters accept an arbitrary number of them
2618 // - macros defined with parameters accept at most that many of them
2619 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2620 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2622 SMLoc IDLoc = Lexer.getLoc();
2623 MCAsmMacroParameter FA;
2625 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2626 if (parseIdentifier(FA.Name))
2627 return Error(IDLoc, "invalid argument identifier for formal argument");
2629 if (Lexer.isNot(AsmToken::Equal))
2630 return TokError("expected '=' after formal parameter identifier");
2634 NamedParametersFound = true;
2636 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2638 if (NamedParametersFound && FA.Name.empty())
2639 return Error(IDLoc, "cannot mix positional and keyword arguments");
2641 SMLoc StrLoc = Lexer.getLoc();
2643 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
2644 const MCExpr *AbsoluteExp;
2648 if (parseExpression(AbsoluteExp, EndLoc))
2650 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2651 getStreamer().getAssemblerPtr()))
2652 return Error(StrLoc, "expected absolute expression");
2653 const char *StrChar = StrLoc.getPointer();
2654 const char *EndChar = EndLoc.getPointer();
2655 AsmToken newToken(AsmToken::Integer,
2656 StringRef(StrChar, EndChar - StrChar), Value);
2657 FA.Value.push_back(newToken);
2658 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
2659 isAltmacroString(StrLoc, EndLoc)) {
2660 const char *StrChar = StrLoc.getPointer();
2661 const char *EndChar = EndLoc.getPointer();
2662 jumpToLoc(EndLoc, CurBuffer);
2663 /// Eat from '<' to '>'
2665 AsmToken newToken(AsmToken::String,
2666 StringRef(StrChar, EndChar - StrChar));
2667 FA.Value.push_back(newToken);
2668 } else if(parseMacroArgument(FA.Value, Vararg))
2671 unsigned PI = Parameter;
2672 if (!FA.Name.empty()) {
2674 for (FAI = 0; FAI < NParameters; ++FAI)
2675 if (M->Parameters[FAI].Name == FA.Name)
2678 if (FAI >= NParameters) {
2679 assert(M && "expected macro to be defined");
2680 return Error(IDLoc, "parameter named '" + FA.Name +
2681 "' does not exist for macro '" + M->Name + "'");
2686 if (!FA.Value.empty()) {
2691 if (FALocs.size() <= PI)
2692 FALocs.resize(PI + 1);
2694 FALocs[PI] = Lexer.getLoc();
2697 // At the end of the statement, fill in remaining arguments that have
2698 // default values. If there aren't any, then the next argument is
2699 // required but missing
2700 if (Lexer.is(AsmToken::EndOfStatement)) {
2701 bool Failure = false;
2702 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2703 if (A[FAI].empty()) {
2704 if (M->Parameters[FAI].Required) {
2705 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2706 "missing value for required parameter "
2707 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2711 if (!M->Parameters[FAI].Value.empty())
2712 A[FAI] = M->Parameters[FAI].Value;
2718 if (Lexer.is(AsmToken::Comma))
2722 return TokError("too many positional arguments");
2725 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2726 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2727 // eliminate this, although we should protect against infinite loops.
2728 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2729 if (ActiveMacros.size() == MaxNestingDepth) {
2730 std::ostringstream MaxNestingDepthError;
2731 MaxNestingDepthError << "macros cannot be nested more than "
2732 << MaxNestingDepth << " levels deep."
2733 << " Use -asm-macro-max-nesting-depth to increase "
2735 return TokError(MaxNestingDepthError.str());
2738 MCAsmMacroArguments A;
2739 if (parseMacroArguments(M, A))
2742 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2743 // to hold the macro body with substitutions.
2744 SmallString<256> Buf;
2745 StringRef Body = M->Body;
2746 raw_svector_ostream OS(Buf);
2748 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2751 // We include the .endmacro in the buffer as our cue to exit the macro
2753 OS << ".endmacro\n";
2755 std::unique_ptr<MemoryBuffer> Instantiation =
2756 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2758 // Create the macro instantiation object and add to the current macro
2759 // instantiation stack.
2760 MacroInstantiation *MI = new MacroInstantiation(
2761 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2762 ActiveMacros.push_back(MI);
2764 ++NumOfMacroInstantiations;
2766 // Jump to the macro instantiation and prime the lexer.
2767 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2768 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2774 void AsmParser::handleMacroExit() {
2775 // Jump to the EndOfStatement we should return to, and consume it.
2776 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2779 // Pop the instantiation entry.
2780 delete ActiveMacros.back();
2781 ActiveMacros.pop_back();
2784 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2787 const MCExpr *Value;
2788 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2793 // In the case where we parse an expression starting with a '.', we will
2794 // not generate an error, nor will we create a symbol. In this case we
2795 // should just return out.
2799 // Do the assignment.
2800 Out.EmitAssignment(Sym, Value);
2802 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2807 /// parseIdentifier:
2810 bool AsmParser::parseIdentifier(StringRef &Res) {
2811 // The assembler has relaxed rules for accepting identifiers, in particular we
2812 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2813 // separate tokens. At this level, we have already lexed so we cannot (currently)
2814 // handle this as a context dependent token, instead we detect adjacent tokens
2815 // and return the combined identifier.
2816 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2817 SMLoc PrefixLoc = getLexer().getLoc();
2819 // Consume the prefix character, and check for a following identifier.
2822 Lexer.peekTokens(Buf, false);
2824 if (Buf[0].isNot(AsmToken::Identifier))
2827 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2828 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2832 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2833 // Construct the joined identifier and consume the token.
2835 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2836 Lex(); // Parser Lex to maintain invariants.
2840 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2843 Res = getTok().getIdentifier();
2845 Lex(); // Consume the identifier token.
2850 /// parseDirectiveSet:
2851 /// ::= .equ identifier ',' expression
2852 /// ::= .equiv identifier ',' expression
2853 /// ::= .set identifier ',' expression
2854 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2856 if (check(parseIdentifier(Name), "expected identifier") ||
2857 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2858 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2862 bool AsmParser::parseEscapedString(std::string &Data) {
2863 if (check(getTok().isNot(AsmToken::String), "expected string"))
2867 StringRef Str = getTok().getStringContents();
2868 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2869 if (Str[i] != '\\') {
2874 // Recognize escaped characters. Note that this escape semantics currently
2875 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2878 return TokError("unexpected backslash at end of string");
2880 // Recognize octal sequences.
2881 if ((unsigned)(Str[i] - '0') <= 7) {
2882 // Consume up to three octal characters.
2883 unsigned Value = Str[i] - '0';
2885 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2887 Value = Value * 8 + (Str[i] - '0');
2889 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2891 Value = Value * 8 + (Str[i] - '0');
2896 return TokError("invalid octal escape sequence (out of range)");
2898 Data += (unsigned char)Value;
2902 // Otherwise recognize individual escapes.
2905 // Just reject invalid escape sequences for now.
2906 return TokError("invalid escape sequence (unrecognized character)");
2908 case 'b': Data += '\b'; break;
2909 case 'f': Data += '\f'; break;
2910 case 'n': Data += '\n'; break;
2911 case 'r': Data += '\r'; break;
2912 case 't': Data += '\t'; break;
2913 case '"': Data += '"'; break;
2914 case '\\': Data += '\\'; break;
2922 /// parseDirectiveAscii:
2923 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2924 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2925 auto parseOp = [&]() -> bool {
2927 if (checkForValidSection() || parseEscapedString(Data))
2929 getStreamer().EmitBytes(Data);
2931 getStreamer().EmitBytes(StringRef("\0", 1));
2935 if (parseMany(parseOp))
2936 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2940 /// parseDirectiveReloc
2941 /// ::= .reloc expression , identifier [ , expression ]
2942 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2943 const MCExpr *Offset;
2944 const MCExpr *Expr = nullptr;
2945 int64_t OffsetValue;
2946 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2948 if (parseExpression(Offset))
2951 if ((Offset->evaluateAsAbsolute(OffsetValue,
2952 getStreamer().getAssemblerPtr()) &&
2953 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
2954 (check(Offset->getKind() != llvm::MCExpr::Constant &&
2955 Offset->getKind() != llvm::MCExpr::SymbolRef,
2956 OffsetLoc, "expected non-negative number or a label")) ||
2957 (parseToken(AsmToken::Comma, "expected comma") ||
2958 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
2961 SMLoc NameLoc = Lexer.getTok().getLoc();
2962 StringRef Name = Lexer.getTok().getIdentifier();
2965 if (Lexer.is(AsmToken::Comma)) {
2967 SMLoc ExprLoc = Lexer.getLoc();
2968 if (parseExpression(Expr))
2972 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2973 return Error(ExprLoc, "expression must be relocatable");
2976 if (parseToken(AsmToken::EndOfStatement,
2977 "unexpected token in .reloc directive"))
2980 const MCTargetAsmParser &MCT = getTargetParser();
2981 const MCSubtargetInfo &STI = MCT.getSTI();
2982 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
2983 return Error(NameLoc, "unknown relocation name");
2988 /// parseDirectiveValue
2989 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2990 bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2991 auto parseOp = [&]() -> bool {
2992 const MCExpr *Value;
2993 SMLoc ExprLoc = getLexer().getLoc();
2994 if (checkForValidSection() || parseExpression(Value))
2996 // Special case constant expressions to match code generator.
2997 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2998 assert(Size <= 8 && "Invalid size");
2999 uint64_t IntValue = MCE->getValue();
3000 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3001 return Error(ExprLoc, "out of range literal value");
3002 getStreamer().EmitIntValue(IntValue, Size);
3004 getStreamer().EmitValue(Value, Size, ExprLoc);
3008 if (parseMany(parseOp))
3009 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3013 static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3014 if (Asm.getTok().isNot(AsmToken::Integer) &&
3015 Asm.getTok().isNot(AsmToken::BigNum))
3016 return Asm.TokError("unknown token in expression");
3017 SMLoc ExprLoc = Asm.getTok().getLoc();
3018 APInt IntValue = Asm.getTok().getAPIntVal();
3020 if (!IntValue.isIntN(128))
3021 return Asm.Error(ExprLoc, "out of range literal value");
3022 if (!IntValue.isIntN(64)) {
3023 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3024 lo = IntValue.getLoBits(64).getZExtValue();
3027 lo = IntValue.getZExtValue();
3032 /// ParseDirectiveOctaValue
3033 /// ::= .octa [ hexconstant (, hexconstant)* ]
3035 bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3036 auto parseOp = [&]() -> bool {
3037 if (checkForValidSection())
3040 if (parseHexOcta(*this, hi, lo))
3042 if (MAI.isLittleEndian()) {
3043 getStreamer().EmitIntValue(lo, 8);
3044 getStreamer().EmitIntValue(hi, 8);
3046 getStreamer().EmitIntValue(hi, 8);
3047 getStreamer().EmitIntValue(lo, 8);
3052 if (parseMany(parseOp))
3053 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3057 bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3058 // We don't truly support arithmetic on floating point expressions, so we
3059 // have to manually parse unary prefixes.
3061 if (getLexer().is(AsmToken::Minus)) {
3064 } else if (getLexer().is(AsmToken::Plus))
3067 if (Lexer.is(AsmToken::Error))
3068 return TokError(Lexer.getErr());
3069 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3070 Lexer.isNot(AsmToken::Identifier))
3071 return TokError("unexpected token in directive");
3073 // Convert to an APFloat.
3074 APFloat Value(Semantics);
3075 StringRef IDVal = getTok().getString();
3076 if (getLexer().is(AsmToken::Identifier)) {
3077 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3078 Value = APFloat::getInf(Semantics);
3079 else if (!IDVal.compare_lower("nan"))
3080 Value = APFloat::getNaN(Semantics, false, ~0);
3082 return TokError("invalid floating point literal");
3083 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3084 APFloat::opInvalidOp)
3085 return TokError("invalid floating point literal");
3089 // Consume the numeric token.
3092 Res = Value.bitcastToAPInt();
3097 /// parseDirectiveRealValue
3098 /// ::= (.single | .double) [ expression (, expression)* ]
3099 bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3100 const fltSemantics &Semantics) {
3101 auto parseOp = [&]() -> bool {
3103 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3105 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3106 AsInt.getBitWidth() / 8);
3110 if (parseMany(parseOp))
3111 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3115 /// parseDirectiveZero
3116 /// ::= .zero expression
3117 bool AsmParser::parseDirectiveZero() {
3118 SMLoc NumBytesLoc = Lexer.getLoc();
3119 const MCExpr *NumBytes;
3120 if (checkForValidSection() || parseExpression(NumBytes))
3124 if (getLexer().is(AsmToken::Comma)) {
3126 if (parseAbsoluteExpression(Val))
3130 if (parseToken(AsmToken::EndOfStatement,
3131 "unexpected token in '.zero' directive"))
3133 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3138 /// parseDirectiveFill
3139 /// ::= .fill expression [ , expression [ , expression ] ]
3140 bool AsmParser::parseDirectiveFill() {
3141 SMLoc NumValuesLoc = Lexer.getLoc();
3142 const MCExpr *NumValues;
3143 if (checkForValidSection() || parseExpression(NumValues))
3146 int64_t FillSize = 1;
3147 int64_t FillExpr = 0;
3149 SMLoc SizeLoc, ExprLoc;
3151 if (parseOptionalToken(AsmToken::Comma)) {
3152 SizeLoc = getTok().getLoc();
3153 if (parseAbsoluteExpression(FillSize))
3155 if (parseOptionalToken(AsmToken::Comma)) {
3156 ExprLoc = getTok().getLoc();
3157 if (parseAbsoluteExpression(FillExpr))
3161 if (parseToken(AsmToken::EndOfStatement,
3162 "unexpected token in '.fill' directive"))
3166 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3170 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3174 if (!isUInt<32>(FillExpr) && FillSize > 4)
3175 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3177 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3182 /// parseDirectiveOrg
3183 /// ::= .org expression [ , expression ]
3184 bool AsmParser::parseDirectiveOrg() {
3185 const MCExpr *Offset;
3186 SMLoc OffsetLoc = Lexer.getLoc();
3187 if (checkForValidSection() || parseExpression(Offset))
3190 // Parse optional fill expression.
3191 int64_t FillExpr = 0;
3192 if (parseOptionalToken(AsmToken::Comma))
3193 if (parseAbsoluteExpression(FillExpr))
3194 return addErrorSuffix(" in '.org' directive");
3195 if (parseToken(AsmToken::EndOfStatement))
3196 return addErrorSuffix(" in '.org' directive");
3198 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3202 /// parseDirectiveAlign
3203 /// ::= {.align, ...} expression [ , expression [ , expression ]]
3204 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3205 SMLoc AlignmentLoc = getLexer().getLoc();
3208 bool HasFillExpr = false;
3209 int64_t FillExpr = 0;
3210 int64_t MaxBytesToFill = 0;
3212 auto parseAlign = [&]() -> bool {
3213 if (parseAbsoluteExpression(Alignment))
3215 if (parseOptionalToken(AsmToken::Comma)) {
3216 // The fill expression can be omitted while specifying a maximum number of
3217 // alignment bytes, e.g:
3219 if (getTok().isNot(AsmToken::Comma)) {
3221 if (parseAbsoluteExpression(FillExpr))
3224 if (parseOptionalToken(AsmToken::Comma))
3225 if (parseTokenLoc(MaxBytesLoc) ||
3226 parseAbsoluteExpression(MaxBytesToFill))
3229 return parseToken(AsmToken::EndOfStatement);
3232 if (checkForValidSection())
3233 return addErrorSuffix(" in directive");
3234 // Ignore empty '.p2align' directives for GNU-as compatibility
3235 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3236 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3237 return parseToken(AsmToken::EndOfStatement);
3240 return addErrorSuffix(" in directive");
3242 // Always emit an alignment here even if we thrown an error.
3243 bool ReturnVal = false;
3245 // Compute alignment in bytes.
3247 // FIXME: Diagnose overflow.
3248 if (Alignment >= 32) {
3249 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3253 Alignment = 1ULL << Alignment;
3255 // Reject alignments that aren't either a power of two or zero,
3256 // for gas compatibility. Alignment of zero is silently rounded
3260 if (!isPowerOf2_64(Alignment))
3261 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3264 // Diagnose non-sensical max bytes to align.
3265 if (MaxBytesLoc.isValid()) {
3266 if (MaxBytesToFill < 1) {
3267 ReturnVal |= Error(MaxBytesLoc,
3268 "alignment directive can never be satisfied in this "
3269 "many bytes, ignoring maximum bytes expression");
3273 if (MaxBytesToFill >= Alignment) {
3274 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3280 // Check whether we should use optimal code alignment for this .align
3282 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3283 assert(Section && "must have section to emit alignment");
3284 bool UseCodeAlign = Section->UseCodeAlign();
3285 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3286 ValueSize == 1 && UseCodeAlign) {
3287 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3289 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3290 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3297 /// parseDirectiveFile
3298 /// ::= .file filename
3299 /// ::= .file number [directory] filename [md5 checksum] [source source-text]
3300 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3301 // FIXME: I'm not sure what this is.
3302 int64_t FileNumber = -1;
3303 if (getLexer().is(AsmToken::Integer)) {
3304 FileNumber = getTok().getIntVal();
3308 return TokError("negative file number");
3313 // Usually the directory and filename together, otherwise just the directory.
3314 // Allow the strings to have escaped octal character sequence.
3315 if (check(getTok().isNot(AsmToken::String),
3316 "unexpected token in '.file' directive") ||
3317 parseEscapedString(Path))
3320 StringRef Directory;
3322 std::string FilenameData;
3323 if (getLexer().is(AsmToken::String)) {
3324 if (check(FileNumber == -1,
3325 "explicit path specified, but no file number") ||
3326 parseEscapedString(FilenameData))
3328 Filename = FilenameData;
3334 uint64_t MD5Hi, MD5Lo;
3335 bool HasMD5 = false;
3337 Optional<StringRef> Source;
3338 bool HasSource = false;
3339 std::string SourceString;
3341 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3343 if (check(getTok().isNot(AsmToken::Identifier),
3344 "unexpected token in '.file' directive") ||
3345 parseIdentifier(Keyword))
3347 if (Keyword == "md5") {
3349 if (check(FileNumber == -1,
3350 "MD5 checksum specified, but no file number") ||
3351 parseHexOcta(*this, MD5Hi, MD5Lo))
3353 } else if (Keyword == "source") {
3355 if (check(FileNumber == -1,
3356 "source specified, but no file number") ||
3357 check(getTok().isNot(AsmToken::String),
3358 "unexpected token in '.file' directive") ||
3359 parseEscapedString(SourceString))
3362 return TokError("unexpected token in '.file' directive");
3366 if (FileNumber == -1) {
3367 // Ignore the directive if there is no number and the target doesn't support
3368 // numberless .file directives. This allows some portability of assembler
3369 // between different object file formats.
3370 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3371 getStreamer().EmitFileDirective(Filename);
3373 // In case there is a -g option as well as debug info from directive .file,
3374 // we turn off the -g option, directly use the existing debug info instead.
3375 // Also reset any implicit ".file 0" for the assembler source.
3376 if (Ctx.getGenDwarfForAssembly()) {
3377 Ctx.getMCDwarfLineTable(0).resetRootFile();
3378 Ctx.setGenDwarfForAssembly(false);
3381 MD5::MD5Result *CKMem = nullptr;
3383 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
3384 for (unsigned i = 0; i != 8; ++i) {
3385 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3386 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3390 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3391 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3392 Source = StringRef(SourceBuf, SourceString.size());
3394 if (FileNumber == 0) {
3395 if (Ctx.getDwarfVersion() < 5)
3396 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
3397 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3399 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3400 FileNumber, Directory, Filename, CKMem, Source);
3402 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3403 FileNumber = FileNumOrErr.get();
3405 // Alert the user if there are some .file directives with MD5 and some not.
3406 // But only do that once.
3407 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3408 ReportedInconsistentMD5 = true;
3409 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3416 /// parseDirectiveLine
3417 /// ::= .line [number]
3418 bool AsmParser::parseDirectiveLine() {
3420 if (getLexer().is(AsmToken::Integer)) {
3421 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3424 // FIXME: Do something with the .line.
3426 if (parseToken(AsmToken::EndOfStatement,
3427 "unexpected token in '.line' directive"))
3433 /// parseDirectiveLoc
3434 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3435 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3436 /// The first number is a file number, must have been previously assigned with
3437 /// a .file directive, the second number is the line number and optionally the
3438 /// third number is a column position (zero if not specified). The remaining
3439 /// optional items are .loc sub-directives.
3440 bool AsmParser::parseDirectiveLoc() {
3441 int64_t FileNumber = 0, LineNumber = 0;
3442 SMLoc Loc = getTok().getLoc();
3443 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3444 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
3445 "file number less than one in '.loc' directive") ||
3446 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3447 "unassigned file number in '.loc' directive"))
3451 if (getLexer().is(AsmToken::Integer)) {
3452 LineNumber = getTok().getIntVal();
3454 return TokError("line number less than zero in '.loc' directive");
3458 int64_t ColumnPos = 0;
3459 if (getLexer().is(AsmToken::Integer)) {
3460 ColumnPos = getTok().getIntVal();
3462 return TokError("column position less than zero in '.loc' directive");
3466 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3468 int64_t Discriminator = 0;
3470 auto parseLocOp = [&]() -> bool {
3472 SMLoc Loc = getTok().getLoc();
3473 if (parseIdentifier(Name))
3474 return TokError("unexpected token in '.loc' directive");
3476 if (Name == "basic_block")
3477 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3478 else if (Name == "prologue_end")
3479 Flags |= DWARF2_FLAG_PROLOGUE_END;
3480 else if (Name == "epilogue_begin")
3481 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3482 else if (Name == "is_stmt") {
3483 Loc = getTok().getLoc();
3484 const MCExpr *Value;
3485 if (parseExpression(Value))
3487 // The expression must be the constant 0 or 1.
3488 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3489 int Value = MCE->getValue();
3491 Flags &= ~DWARF2_FLAG_IS_STMT;
3492 else if (Value == 1)
3493 Flags |= DWARF2_FLAG_IS_STMT;
3495 return Error(Loc, "is_stmt value not 0 or 1");
3497 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3499 } else if (Name == "isa") {
3500 Loc = getTok().getLoc();
3501 const MCExpr *Value;
3502 if (parseExpression(Value))
3504 // The expression must be a constant greater or equal to 0.
3505 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3506 int Value = MCE->getValue();
3508 return Error(Loc, "isa number less than zero");
3511 return Error(Loc, "isa number not a constant value");
3513 } else if (Name == "discriminator") {
3514 if (parseAbsoluteExpression(Discriminator))
3517 return Error(Loc, "unknown sub-directive in '.loc' directive");
3522 if (parseMany(parseLocOp, false /*hasComma*/))
3525 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3526 Isa, Discriminator, StringRef());
3531 /// parseDirectiveStabs
3532 /// ::= .stabs string, number, number, number
3533 bool AsmParser::parseDirectiveStabs() {
3534 return TokError("unsupported directive '.stabs'");
3537 /// parseDirectiveCVFile
3538 /// ::= .cv_file number filename [checksum] [checksumkind]
3539 bool AsmParser::parseDirectiveCVFile() {
3540 SMLoc FileNumberLoc = getTok().getLoc();
3542 std::string Filename;
3543 std::string Checksum;
3544 int64_t ChecksumKind = 0;
3546 if (parseIntToken(FileNumber,
3547 "expected file number in '.cv_file' directive") ||
3548 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3549 check(getTok().isNot(AsmToken::String),
3550 "unexpected token in '.cv_file' directive") ||
3551 parseEscapedString(Filename))
3553 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3554 if (check(getTok().isNot(AsmToken::String),
3555 "unexpected token in '.cv_file' directive") ||
3556 parseEscapedString(Checksum) ||
3557 parseIntToken(ChecksumKind,
3558 "expected checksum kind in '.cv_file' directive") ||
3559 parseToken(AsmToken::EndOfStatement,
3560 "unexpected token in '.cv_file' directive"))
3564 Checksum = fromHex(Checksum);
3565 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3566 memcpy(CKMem, Checksum.data(), Checksum.size());
3567 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3570 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3571 static_cast<uint8_t>(ChecksumKind)))
3572 return Error(FileNumberLoc, "file number already allocated");
3577 bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3578 StringRef DirectiveName) {
3580 return parseTokenLoc(Loc) ||
3581 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3583 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3584 "expected function id within range [0, UINT_MAX)");
3587 bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3589 return parseTokenLoc(Loc) ||
3590 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3592 check(FileNumber < 1, Loc, "file number less than one in '" +
3593 DirectiveName + "' directive") ||
3594 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3595 "unassigned file number in '" + DirectiveName + "' directive");
3598 /// parseDirectiveCVFuncId
3599 /// ::= .cv_func_id FunctionId
3601 /// Introduces a function ID that can be used with .cv_loc.
3602 bool AsmParser::parseDirectiveCVFuncId() {
3603 SMLoc FunctionIdLoc = getTok().getLoc();
3606 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3607 parseToken(AsmToken::EndOfStatement,
3608 "unexpected token in '.cv_func_id' directive"))
3611 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3612 return Error(FunctionIdLoc, "function id already allocated");
3617 /// parseDirectiveCVInlineSiteId
3618 /// ::= .cv_inline_site_id FunctionId
3620 /// "inlined_at" IAFile IALine [IACol]
3622 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3623 /// at" source location information for use in the line table of the caller,
3624 /// whether the caller is a real function or another inlined call site.
3625 bool AsmParser::parseDirectiveCVInlineSiteId() {
3626 SMLoc FunctionIdLoc = getTok().getLoc();
3634 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3638 if (check((getLexer().isNot(AsmToken::Identifier) ||
3639 getTok().getIdentifier() != "within"),
3640 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3645 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3649 if (check((getLexer().isNot(AsmToken::Identifier) ||
3650 getTok().getIdentifier() != "inlined_at"),
3651 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3657 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3658 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3662 if (getLexer().is(AsmToken::Integer)) {
3663 IACol = getTok().getIntVal();
3667 if (parseToken(AsmToken::EndOfStatement,
3668 "unexpected token in '.cv_inline_site_id' directive"))
3671 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3672 IALine, IACol, FunctionIdLoc))
3673 return Error(FunctionIdLoc, "function id already allocated");
3678 /// parseDirectiveCVLoc
3679 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3681 /// The first number is a file number, must have been previously assigned with
3682 /// a .file directive, the second number is the line number and optionally the
3683 /// third number is a column position (zero if not specified). The remaining
3684 /// optional items are .loc sub-directives.
3685 bool AsmParser::parseDirectiveCVLoc() {
3686 SMLoc DirectiveLoc = getTok().getLoc();
3687 int64_t FunctionId, FileNumber;
3688 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3689 parseCVFileId(FileNumber, ".cv_loc"))
3692 int64_t LineNumber = 0;
3693 if (getLexer().is(AsmToken::Integer)) {
3694 LineNumber = getTok().getIntVal();
3696 return TokError("line number less than zero in '.cv_loc' directive");
3700 int64_t ColumnPos = 0;
3701 if (getLexer().is(AsmToken::Integer)) {
3702 ColumnPos = getTok().getIntVal();
3704 return TokError("column position less than zero in '.cv_loc' directive");
3708 bool PrologueEnd = false;
3709 uint64_t IsStmt = 0;
3711 auto parseOp = [&]() -> bool {
3713 SMLoc Loc = getTok().getLoc();
3714 if (parseIdentifier(Name))
3715 return TokError("unexpected token in '.cv_loc' directive");
3716 if (Name == "prologue_end")
3718 else if (Name == "is_stmt") {
3719 Loc = getTok().getLoc();
3720 const MCExpr *Value;
3721 if (parseExpression(Value))
3723 // The expression must be the constant 0 or 1.
3725 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3726 IsStmt = MCE->getValue();
3729 return Error(Loc, "is_stmt value not 0 or 1");
3731 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3736 if (parseMany(parseOp, false /*hasComma*/))
3739 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3740 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3745 /// parseDirectiveCVLinetable
3746 /// ::= .cv_linetable FunctionId, FnStart, FnEnd
3747 bool AsmParser::parseDirectiveCVLinetable() {
3749 StringRef FnStartName, FnEndName;
3750 SMLoc Loc = getTok().getLoc();
3751 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3752 parseToken(AsmToken::Comma,
3753 "unexpected token in '.cv_linetable' directive") ||
3754 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3755 "expected identifier in directive") ||
3756 parseToken(AsmToken::Comma,
3757 "unexpected token in '.cv_linetable' directive") ||
3758 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3759 "expected identifier in directive"))
3762 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3763 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3765 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3769 /// parseDirectiveCVInlineLinetable
3770 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3771 bool AsmParser::parseDirectiveCVInlineLinetable() {
3772 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3773 StringRef FnStartName, FnEndName;
3774 SMLoc Loc = getTok().getLoc();
3775 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3776 parseTokenLoc(Loc) ||
3779 "expected SourceField in '.cv_inline_linetable' directive") ||
3780 check(SourceFileId <= 0, Loc,
3781 "File id less than zero in '.cv_inline_linetable' directive") ||
3782 parseTokenLoc(Loc) ||
3785 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3786 check(SourceLineNum < 0, Loc,
3787 "Line number less than zero in '.cv_inline_linetable' directive") ||
3788 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3789 "expected identifier in directive") ||
3790 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3791 "expected identifier in directive"))
3794 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3797 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3798 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3799 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3800 SourceLineNum, FnStartSym,
3805 /// parseDirectiveCVDefRange
3806 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3807 bool AsmParser::parseDirectiveCVDefRange() {
3809 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3810 while (getLexer().is(AsmToken::Identifier)) {
3811 Loc = getLexer().getLoc();
3812 StringRef GapStartName;
3813 if (parseIdentifier(GapStartName))
3814 return Error(Loc, "expected identifier in directive");
3815 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3817 Loc = getLexer().getLoc();
3818 StringRef GapEndName;
3819 if (parseIdentifier(GapEndName))
3820 return Error(Loc, "expected identifier in directive");
3821 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3823 Ranges.push_back({GapStartSym, GapEndSym});
3826 std::string FixedSizePortion;
3827 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3828 parseEscapedString(FixedSizePortion))
3831 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3835 /// parseDirectiveCVString
3836 /// ::= .cv_stringtable "string"
3837 bool AsmParser::parseDirectiveCVString() {
3839 if (checkForValidSection() || parseEscapedString(Data))
3840 return addErrorSuffix(" in '.cv_string' directive");
3842 // Put the string in the table and emit the offset.
3843 std::pair<StringRef, unsigned> Insertion =
3844 getCVContext().addToStringTable(Data);
3845 getStreamer().EmitIntValue(Insertion.second, 4);
3849 /// parseDirectiveCVStringTable
3850 /// ::= .cv_stringtable
3851 bool AsmParser::parseDirectiveCVStringTable() {
3852 getStreamer().EmitCVStringTableDirective();
3856 /// parseDirectiveCVFileChecksums
3857 /// ::= .cv_filechecksums
3858 bool AsmParser::parseDirectiveCVFileChecksums() {
3859 getStreamer().EmitCVFileChecksumsDirective();
3863 /// parseDirectiveCVFileChecksumOffset
3864 /// ::= .cv_filechecksumoffset fileno
3865 bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3867 if (parseIntToken(FileNo, "expected identifier in directive"))
3869 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3871 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3875 /// parseDirectiveCVFPOData
3876 /// ::= .cv_fpo_data procsym
3877 bool AsmParser::parseDirectiveCVFPOData() {
3878 SMLoc DirLoc = getLexer().getLoc();
3880 if (parseIdentifier(ProcName))
3881 return TokError("expected symbol name");
3882 if (parseEOL("unexpected tokens"))
3883 return addErrorSuffix(" in '.cv_fpo_data' directive");
3884 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3885 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3889 /// parseDirectiveCFISections
3890 /// ::= .cfi_sections section [, section]
3891 bool AsmParser::parseDirectiveCFISections() {
3896 if (parseIdentifier(Name))
3897 return TokError("Expected an identifier");
3899 if (Name == ".eh_frame")
3901 else if (Name == ".debug_frame")
3904 if (getLexer().is(AsmToken::Comma)) {
3907 if (parseIdentifier(Name))
3908 return TokError("Expected an identifier");
3910 if (Name == ".eh_frame")
3912 else if (Name == ".debug_frame")
3916 getStreamer().EmitCFISections(EH, Debug);
3920 /// parseDirectiveCFIStartProc
3921 /// ::= .cfi_startproc [simple]
3922 bool AsmParser::parseDirectiveCFIStartProc() {
3924 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3925 if (check(parseIdentifier(Simple) || Simple != "simple",
3926 "unexpected token") ||
3927 parseToken(AsmToken::EndOfStatement))
3928 return addErrorSuffix(" in '.cfi_startproc' directive");
3931 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
3932 // being produced if this directive is emitted as part of preprocessor macro
3933 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
3934 // Tools like llvm-mc on the other hand are not affected by it, and report
3935 // correct context information.
3936 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
3940 /// parseDirectiveCFIEndProc
3941 /// ::= .cfi_endproc
3942 bool AsmParser::parseDirectiveCFIEndProc() {
3943 getStreamer().EmitCFIEndProc();
3947 /// parse register name or number.
3948 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3949 SMLoc DirectiveLoc) {
3952 if (getLexer().isNot(AsmToken::Integer)) {
3953 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3955 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3957 return parseAbsoluteExpression(Register);
3962 /// parseDirectiveCFIDefCfa
3963 /// ::= .cfi_def_cfa register, offset
3964 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3965 int64_t Register = 0, Offset = 0;
3966 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3967 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3968 parseAbsoluteExpression(Offset))
3971 getStreamer().EmitCFIDefCfa(Register, Offset);
3975 /// parseDirectiveCFIDefCfaOffset
3976 /// ::= .cfi_def_cfa_offset offset
3977 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3979 if (parseAbsoluteExpression(Offset))
3982 getStreamer().EmitCFIDefCfaOffset(Offset);
3986 /// parseDirectiveCFIRegister
3987 /// ::= .cfi_register register, register
3988 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3989 int64_t Register1 = 0, Register2 = 0;
3990 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3991 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3992 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3995 getStreamer().EmitCFIRegister(Register1, Register2);
3999 /// parseDirectiveCFIWindowSave
4000 /// ::= .cfi_window_save
4001 bool AsmParser::parseDirectiveCFIWindowSave() {
4002 getStreamer().EmitCFIWindowSave();
4006 /// parseDirectiveCFIAdjustCfaOffset
4007 /// ::= .cfi_adjust_cfa_offset adjustment
4008 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
4009 int64_t Adjustment = 0;
4010 if (parseAbsoluteExpression(Adjustment))
4013 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4017 /// parseDirectiveCFIDefCfaRegister
4018 /// ::= .cfi_def_cfa_register register
4019 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
4020 int64_t Register = 0;
4021 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4024 getStreamer().EmitCFIDefCfaRegister(Register);
4028 /// parseDirectiveCFIOffset
4029 /// ::= .cfi_offset register, offset
4030 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
4031 int64_t Register = 0;
4034 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4035 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4036 parseAbsoluteExpression(Offset))
4039 getStreamer().EmitCFIOffset(Register, Offset);
4043 /// parseDirectiveCFIRelOffset
4044 /// ::= .cfi_rel_offset register, offset
4045 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
4046 int64_t Register = 0, Offset = 0;
4048 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4049 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4050 parseAbsoluteExpression(Offset))
4053 getStreamer().EmitCFIRelOffset(Register, Offset);
4057 static bool isValidEncoding(int64_t Encoding) {
4058 if (Encoding & ~0xff)
4061 if (Encoding == dwarf::DW_EH_PE_omit)
4064 const unsigned Format = Encoding & 0xf;
4065 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4066 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4067 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4068 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4071 const unsigned Application = Encoding & 0x70;
4072 if (Application != dwarf::DW_EH_PE_absptr &&
4073 Application != dwarf::DW_EH_PE_pcrel)
4079 /// parseDirectiveCFIPersonalityOrLsda
4080 /// IsPersonality true for cfi_personality, false for cfi_lsda
4081 /// ::= .cfi_personality encoding, [symbol_name]
4082 /// ::= .cfi_lsda encoding, [symbol_name]
4083 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4084 int64_t Encoding = 0;
4085 if (parseAbsoluteExpression(Encoding))
4087 if (Encoding == dwarf::DW_EH_PE_omit)
4091 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4092 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4093 check(parseIdentifier(Name), "expected identifier in directive"))
4096 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4099 getStreamer().EmitCFIPersonality(Sym, Encoding);
4101 getStreamer().EmitCFILsda(Sym, Encoding);
4105 /// parseDirectiveCFIRememberState
4106 /// ::= .cfi_remember_state
4107 bool AsmParser::parseDirectiveCFIRememberState() {
4108 getStreamer().EmitCFIRememberState();
4112 /// parseDirectiveCFIRestoreState
4113 /// ::= .cfi_remember_state
4114 bool AsmParser::parseDirectiveCFIRestoreState() {
4115 getStreamer().EmitCFIRestoreState();
4119 /// parseDirectiveCFISameValue
4120 /// ::= .cfi_same_value register
4121 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4122 int64_t Register = 0;
4124 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4127 getStreamer().EmitCFISameValue(Register);
4131 /// parseDirectiveCFIRestore
4132 /// ::= .cfi_restore register
4133 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4134 int64_t Register = 0;
4135 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4138 getStreamer().EmitCFIRestore(Register);
4142 /// parseDirectiveCFIEscape
4143 /// ::= .cfi_escape expression[,...]
4144 bool AsmParser::parseDirectiveCFIEscape() {
4147 if (parseAbsoluteExpression(CurrValue))
4150 Values.push_back((uint8_t)CurrValue);
4152 while (getLexer().is(AsmToken::Comma)) {
4155 if (parseAbsoluteExpression(CurrValue))
4158 Values.push_back((uint8_t)CurrValue);
4161 getStreamer().EmitCFIEscape(Values);
4165 /// parseDirectiveCFIReturnColumn
4166 /// ::= .cfi_return_column register
4167 bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4168 int64_t Register = 0;
4169 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4171 getStreamer().EmitCFIReturnColumn(Register);
4175 /// parseDirectiveCFISignalFrame
4176 /// ::= .cfi_signal_frame
4177 bool AsmParser::parseDirectiveCFISignalFrame() {
4178 if (parseToken(AsmToken::EndOfStatement,
4179 "unexpected token in '.cfi_signal_frame'"))
4182 getStreamer().EmitCFISignalFrame();
4186 /// parseDirectiveCFIUndefined
4187 /// ::= .cfi_undefined register
4188 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4189 int64_t Register = 0;
4191 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4194 getStreamer().EmitCFIUndefined(Register);
4198 /// parseDirectiveAltmacro
4201 bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4202 if (getLexer().isNot(AsmToken::EndOfStatement))
4203 return TokError("unexpected token in '" + Directive + "' directive");
4204 AltMacroMode = (Directive == ".altmacro");
4208 /// parseDirectiveMacrosOnOff
4211 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4212 if (parseToken(AsmToken::EndOfStatement,
4213 "unexpected token in '" + Directive + "' directive"))
4216 setMacrosEnabled(Directive == ".macros_on");
4220 /// parseDirectiveMacro
4221 /// ::= .macro name[,] [parameters]
4222 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4224 if (parseIdentifier(Name))
4225 return TokError("expected identifier in '.macro' directive");
4227 if (getLexer().is(AsmToken::Comma))
4230 MCAsmMacroParameters Parameters;
4231 while (getLexer().isNot(AsmToken::EndOfStatement)) {
4233 if (!Parameters.empty() && Parameters.back().Vararg)
4234 return Error(Lexer.getLoc(),
4235 "Vararg parameter '" + Parameters.back().Name +
4236 "' should be last one in the list of parameters.");
4238 MCAsmMacroParameter Parameter;
4239 if (parseIdentifier(Parameter.Name))
4240 return TokError("expected identifier in '.macro' directive");
4242 // Emit an error if two (or more) named parameters share the same name
4243 for (const MCAsmMacroParameter& CurrParam : Parameters)
4244 if (CurrParam.Name.equals(Parameter.Name))
4245 return TokError("macro '" + Name + "' has multiple parameters"
4246 " named '" + Parameter.Name + "'");
4248 if (Lexer.is(AsmToken::Colon)) {
4249 Lex(); // consume ':'
4252 StringRef Qualifier;
4254 QualLoc = Lexer.getLoc();
4255 if (parseIdentifier(Qualifier))
4256 return Error(QualLoc, "missing parameter qualifier for "
4257 "'" + Parameter.Name + "' in macro '" + Name + "'");
4259 if (Qualifier == "req")
4260 Parameter.Required = true;
4261 else if (Qualifier == "vararg")
4262 Parameter.Vararg = true;
4264 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4265 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4268 if (getLexer().is(AsmToken::Equal)) {
4273 ParamLoc = Lexer.getLoc();
4274 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4277 if (Parameter.Required)
4278 Warning(ParamLoc, "pointless default value for required parameter "
4279 "'" + Parameter.Name + "' in macro '" + Name + "'");
4282 Parameters.push_back(std::move(Parameter));
4284 if (getLexer().is(AsmToken::Comma))
4288 // Eat just the end of statement.
4291 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4292 AsmToken EndToken, StartToken = getTok();
4293 unsigned MacroDepth = 0;
4294 // Lex the macro definition.
4296 // Ignore Lexing errors in macros.
4297 while (Lexer.is(AsmToken::Error)) {
4301 // Check whether we have reached the end of the file.
4302 if (getLexer().is(AsmToken::Eof))
4303 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4305 // Otherwise, check whether we have reach the .endmacro.
4306 if (getLexer().is(AsmToken::Identifier)) {
4307 if (getTok().getIdentifier() == ".endm" ||
4308 getTok().getIdentifier() == ".endmacro") {
4309 if (MacroDepth == 0) { // Outermost macro.
4310 EndToken = getTok();
4312 if (getLexer().isNot(AsmToken::EndOfStatement))
4313 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4317 // Otherwise we just found the end of an inner macro.
4320 } else if (getTok().getIdentifier() == ".macro") {
4321 // We allow nested macros. Those aren't instantiated until the outermost
4322 // macro is expanded so just ignore them for now.
4327 // Otherwise, scan til the end of the statement.
4328 eatToEndOfStatement();
4331 if (getContext().lookupMacro(Name)) {
4332 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4335 const char *BodyStart = StartToken.getLoc().getPointer();
4336 const char *BodyEnd = EndToken.getLoc().getPointer();
4337 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4338 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4339 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4340 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4342 getContext().defineMacro(Name, std::move(Macro));
4346 /// checkForBadMacro
4348 /// With the support added for named parameters there may be code out there that
4349 /// is transitioning from positional parameters. In versions of gas that did
4350 /// not support named parameters they would be ignored on the macro definition.
4351 /// But to support both styles of parameters this is not possible so if a macro
4352 /// definition has named parameters but does not use them and has what appears
4353 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4354 /// warning that the positional parameter found in body which have no effect.
4355 /// Hoping the developer will either remove the named parameters from the macro
4356 /// definition so the positional parameters get used if that was what was
4357 /// intended or change the macro to use the named parameters. It is possible
4358 /// this warning will trigger when the none of the named parameters are used
4359 /// and the strings like $1 are infact to simply to be passed trough unchanged.
4360 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4362 ArrayRef<MCAsmMacroParameter> Parameters) {
4363 // If this macro is not defined with named parameters the warning we are
4364 // checking for here doesn't apply.
4365 unsigned NParameters = Parameters.size();
4366 if (NParameters == 0)
4369 bool NamedParametersFound = false;
4370 bool PositionalParametersFound = false;
4372 // Look at the body of the macro for use of both the named parameters and what
4373 // are likely to be positional parameters. This is what expandMacro() is
4374 // doing when it finds the parameters in the body.
4375 while (!Body.empty()) {
4376 // Scan for the next possible parameter.
4377 std::size_t End = Body.size(), Pos = 0;
4378 for (; Pos != End; ++Pos) {
4379 // Check for a substitution or escape.
4380 // This macro is defined with parameters, look for \foo, \bar, etc.
4381 if (Body[Pos] == '\\' && Pos + 1 != End)
4384 // This macro should have parameters, but look for $0, $1, ..., $n too.
4385 if (Body[Pos] != '$' || Pos + 1 == End)
4387 char Next = Body[Pos + 1];
4388 if (Next == '$' || Next == 'n' ||
4389 isdigit(static_cast<unsigned char>(Next)))
4393 // Check if we reached the end.
4397 if (Body[Pos] == '$') {
4398 switch (Body[Pos + 1]) {
4403 // $n => number of arguments
4405 PositionalParametersFound = true;
4408 // $[0-9] => argument
4410 PositionalParametersFound = true;
4416 unsigned I = Pos + 1;
4417 while (isIdentifierChar(Body[I]) && I + 1 != End)
4420 const char *Begin = Body.data() + Pos + 1;
4421 StringRef Argument(Begin, I - (Pos + 1));
4423 for (; Index < NParameters; ++Index)
4424 if (Parameters[Index].Name == Argument)
4427 if (Index == NParameters) {
4428 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4434 NamedParametersFound = true;
4435 Pos += 1 + Argument.size();
4438 // Update the scan point.
4439 Body = Body.substr(Pos);
4442 if (!NamedParametersFound && PositionalParametersFound)
4443 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4444 "used in macro body, possible positional parameter "
4445 "found in body which will have no effect");
4448 /// parseDirectiveExitMacro
4450 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4451 if (parseToken(AsmToken::EndOfStatement,
4452 "unexpected token in '" + Directive + "' directive"))
4455 if (!isInsideMacroInstantiation())
4456 return TokError("unexpected '" + Directive + "' in file, "
4457 "no current macro definition");
4459 // Exit all conditionals that are active in the current macro.
4460 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4461 TheCondState = TheCondStack.back();
4462 TheCondStack.pop_back();
4469 /// parseDirectiveEndMacro
4472 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4473 if (getLexer().isNot(AsmToken::EndOfStatement))
4474 return TokError("unexpected token in '" + Directive + "' directive");
4476 // If we are inside a macro instantiation, terminate the current
4478 if (isInsideMacroInstantiation()) {
4483 // Otherwise, this .endmacro is a stray entry in the file; well formed
4484 // .endmacro directives are handled during the macro definition parsing.
4485 return TokError("unexpected '" + Directive + "' in file, "
4486 "no current macro definition");
4489 /// parseDirectivePurgeMacro
4491 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4494 if (parseTokenLoc(Loc) ||
4495 check(parseIdentifier(Name), Loc,
4496 "expected identifier in '.purgem' directive") ||
4497 parseToken(AsmToken::EndOfStatement,
4498 "unexpected token in '.purgem' directive"))
4501 if (!getContext().lookupMacro(Name))
4502 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4504 getContext().undefineMacro(Name);
4505 DEBUG_WITH_TYPE("asm-macros", dbgs()
4506 << "Un-defining macro: " << Name << "\n");
4510 /// parseDirectiveBundleAlignMode
4511 /// ::= {.bundle_align_mode} expression
4512 bool AsmParser::parseDirectiveBundleAlignMode() {
4513 // Expect a single argument: an expression that evaluates to a constant
4514 // in the inclusive range 0-30.
4515 SMLoc ExprLoc = getLexer().getLoc();
4516 int64_t AlignSizePow2;
4517 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4518 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4519 "in '.bundle_align_mode' "
4521 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4522 "invalid bundle alignment size (expected between 0 and 30)"))
4525 // Because of AlignSizePow2's verified range we can safely truncate it to
4527 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4531 /// parseDirectiveBundleLock
4532 /// ::= {.bundle_lock} [align_to_end]
4533 bool AsmParser::parseDirectiveBundleLock() {
4534 if (checkForValidSection())
4536 bool AlignToEnd = false;
4539 SMLoc Loc = getTok().getLoc();
4540 const char *kInvalidOptionError =
4541 "invalid option for '.bundle_lock' directive";
4543 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4544 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4545 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4546 parseToken(AsmToken::EndOfStatement,
4547 "unexpected token after '.bundle_lock' directive option"))
4552 getStreamer().EmitBundleLock(AlignToEnd);
4556 /// parseDirectiveBundleLock
4557 /// ::= {.bundle_lock}
4558 bool AsmParser::parseDirectiveBundleUnlock() {
4559 if (checkForValidSection() ||
4560 parseToken(AsmToken::EndOfStatement,
4561 "unexpected token in '.bundle_unlock' directive"))
4564 getStreamer().EmitBundleUnlock();
4568 /// parseDirectiveSpace
4569 /// ::= (.skip | .space) expression [ , expression ]
4570 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4571 SMLoc NumBytesLoc = Lexer.getLoc();
4572 const MCExpr *NumBytes;
4573 if (checkForValidSection() || parseExpression(NumBytes))
4576 int64_t FillExpr = 0;
4577 if (parseOptionalToken(AsmToken::Comma))
4578 if (parseAbsoluteExpression(FillExpr))
4579 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4580 if (parseToken(AsmToken::EndOfStatement))
4581 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4583 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4584 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4589 /// parseDirectiveDCB
4590 /// ::= .dcb.{b, l, w} expression, expression
4591 bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4592 SMLoc NumValuesLoc = Lexer.getLoc();
4594 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4597 if (NumValues < 0) {
4598 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4602 if (parseToken(AsmToken::Comma,
4603 "unexpected token in '" + Twine(IDVal) + "' directive"))
4606 const MCExpr *Value;
4607 SMLoc ExprLoc = getLexer().getLoc();
4608 if (parseExpression(Value))
4611 // Special case constant expressions to match code generator.
4612 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4613 assert(Size <= 8 && "Invalid size");
4614 uint64_t IntValue = MCE->getValue();
4615 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4616 return Error(ExprLoc, "literal value out of range for directive");
4617 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4618 getStreamer().EmitIntValue(IntValue, Size);
4620 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4621 getStreamer().EmitValue(Value, Size, ExprLoc);
4624 if (parseToken(AsmToken::EndOfStatement,
4625 "unexpected token in '" + Twine(IDVal) + "' directive"))
4631 /// parseDirectiveRealDCB
4632 /// ::= .dcb.{d, s} expression, expression
4633 bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4634 SMLoc NumValuesLoc = Lexer.getLoc();
4636 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4639 if (NumValues < 0) {
4640 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4644 if (parseToken(AsmToken::Comma,
4645 "unexpected token in '" + Twine(IDVal) + "' directive"))
4649 if (parseRealValue(Semantics, AsInt))
4652 if (parseToken(AsmToken::EndOfStatement,
4653 "unexpected token in '" + Twine(IDVal) + "' directive"))
4656 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4657 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4658 AsInt.getBitWidth() / 8);
4663 /// parseDirectiveDS
4664 /// ::= .ds.{b, d, l, p, s, w, x} expression
4665 bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4666 SMLoc NumValuesLoc = Lexer.getLoc();
4668 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4671 if (NumValues < 0) {
4672 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4676 if (parseToken(AsmToken::EndOfStatement,
4677 "unexpected token in '" + Twine(IDVal) + "' directive"))
4680 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4681 getStreamer().emitFill(Size, 0);
4686 /// parseDirectiveLEB128
4687 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4688 bool AsmParser::parseDirectiveLEB128(bool Signed) {
4689 if (checkForValidSection())
4692 auto parseOp = [&]() -> bool {
4693 const MCExpr *Value;
4694 if (parseExpression(Value))
4697 getStreamer().EmitSLEB128Value(Value);
4699 getStreamer().EmitULEB128Value(Value);
4703 if (parseMany(parseOp))
4704 return addErrorSuffix(" in directive");
4709 /// parseDirectiveSymbolAttribute
4710 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4711 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4712 auto parseOp = [&]() -> bool {
4714 SMLoc Loc = getTok().getLoc();
4715 if (parseIdentifier(Name))
4716 return Error(Loc, "expected identifier");
4717 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4719 // Assembler local symbols don't make any sense here. Complain loudly.
4720 if (Sym->isTemporary())
4721 return Error(Loc, "non-local symbol required");
4723 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4724 return Error(Loc, "unable to emit symbol attribute");
4728 if (parseMany(parseOp))
4729 return addErrorSuffix(" in directive");
4733 /// parseDirectiveComm
4734 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4735 bool AsmParser::parseDirectiveComm(bool IsLocal) {
4736 if (checkForValidSection())
4739 SMLoc IDLoc = getLexer().getLoc();
4741 if (parseIdentifier(Name))
4742 return TokError("expected identifier in directive");
4744 // Handle the identifier as the key symbol.
4745 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4747 if (getLexer().isNot(AsmToken::Comma))
4748 return TokError("unexpected token in directive");
4752 SMLoc SizeLoc = getLexer().getLoc();
4753 if (parseAbsoluteExpression(Size))
4756 int64_t Pow2Alignment = 0;
4757 SMLoc Pow2AlignmentLoc;
4758 if (getLexer().is(AsmToken::Comma)) {
4760 Pow2AlignmentLoc = getLexer().getLoc();
4761 if (parseAbsoluteExpression(Pow2Alignment))
4764 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4765 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4766 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4768 // If this target takes alignments in bytes (not log) validate and convert.
4769 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4770 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4771 if (!isPowerOf2_64(Pow2Alignment))
4772 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4773 Pow2Alignment = Log2_64(Pow2Alignment);
4777 if (parseToken(AsmToken::EndOfStatement,
4778 "unexpected token in '.comm' or '.lcomm' directive"))
4781 // NOTE: a size of zero for a .comm should create a undefined symbol
4782 // but a size of .lcomm creates a bss symbol of size zero.
4784 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4785 "be less than zero");
4787 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4788 // may internally end up wanting an alignment in bytes.
4789 // FIXME: Diagnose overflow.
4790 if (Pow2Alignment < 0)
4791 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4792 "alignment, can't be less than zero");
4794 Sym->redefineIfPossible();
4795 if (!Sym->isUndefined())
4796 return Error(IDLoc, "invalid symbol redefinition");
4798 // Create the Symbol as a common or local common with Size and Pow2Alignment
4800 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4804 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4808 /// parseDirectiveAbort
4809 /// ::= .abort [... message ...]
4810 bool AsmParser::parseDirectiveAbort() {
4811 // FIXME: Use loc from directive.
4812 SMLoc Loc = getLexer().getLoc();
4814 StringRef Str = parseStringToEndOfStatement();
4815 if (parseToken(AsmToken::EndOfStatement,
4816 "unexpected token in '.abort' directive"))
4820 return Error(Loc, ".abort detected. Assembly stopping.");
4822 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4823 // FIXME: Actually abort assembly here.
4828 /// parseDirectiveInclude
4829 /// ::= .include "filename"
4830 bool AsmParser::parseDirectiveInclude() {
4831 // Allow the strings to have escaped octal character sequence.
4832 std::string Filename;
4833 SMLoc IncludeLoc = getTok().getLoc();
4835 if (check(getTok().isNot(AsmToken::String),
4836 "expected string in '.include' directive") ||
4837 parseEscapedString(Filename) ||
4838 check(getTok().isNot(AsmToken::EndOfStatement),
4839 "unexpected token in '.include' directive") ||
4840 // Attempt to switch the lexer to the included file before consuming the
4841 // end of statement to avoid losing it when we switch.
4842 check(enterIncludeFile(Filename), IncludeLoc,
4843 "Could not find include file '" + Filename + "'"))
4849 /// parseDirectiveIncbin
4850 /// ::= .incbin "filename" [ , skip [ , count ] ]
4851 bool AsmParser::parseDirectiveIncbin() {
4852 // Allow the strings to have escaped octal character sequence.
4853 std::string Filename;
4854 SMLoc IncbinLoc = getTok().getLoc();
4855 if (check(getTok().isNot(AsmToken::String),
4856 "expected string in '.incbin' directive") ||
4857 parseEscapedString(Filename))
4861 const MCExpr *Count = nullptr;
4862 SMLoc SkipLoc, CountLoc;
4863 if (parseOptionalToken(AsmToken::Comma)) {
4864 // The skip expression can be omitted while specifying the count, e.g:
4865 // .incbin "filename",,4
4866 if (getTok().isNot(AsmToken::Comma)) {
4867 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4870 if (parseOptionalToken(AsmToken::Comma)) {
4871 CountLoc = getTok().getLoc();
4872 if (parseExpression(Count))
4877 if (parseToken(AsmToken::EndOfStatement,
4878 "unexpected token in '.incbin' directive"))
4881 if (check(Skip < 0, SkipLoc, "skip is negative"))
4884 // Attempt to process the included file.
4885 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4886 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4890 /// parseDirectiveIf
4891 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
4892 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4893 TheCondStack.push_back(TheCondState);
4894 TheCondState.TheCond = AsmCond::IfCond;
4895 if (TheCondState.Ignore) {
4896 eatToEndOfStatement();
4899 if (parseAbsoluteExpression(ExprValue) ||
4900 parseToken(AsmToken::EndOfStatement,
4901 "unexpected token in '.if' directive"))
4906 llvm_unreachable("unsupported directive");
4911 ExprValue = ExprValue == 0;
4914 ExprValue = ExprValue >= 0;
4917 ExprValue = ExprValue > 0;
4920 ExprValue = ExprValue <= 0;
4923 ExprValue = ExprValue < 0;
4927 TheCondState.CondMet = ExprValue;
4928 TheCondState.Ignore = !TheCondState.CondMet;
4934 /// parseDirectiveIfb
4936 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4937 TheCondStack.push_back(TheCondState);
4938 TheCondState.TheCond = AsmCond::IfCond;
4940 if (TheCondState.Ignore) {
4941 eatToEndOfStatement();
4943 StringRef Str = parseStringToEndOfStatement();
4945 if (parseToken(AsmToken::EndOfStatement,
4946 "unexpected token in '.ifb' directive"))
4949 TheCondState.CondMet = ExpectBlank == Str.empty();
4950 TheCondState.Ignore = !TheCondState.CondMet;
4956 /// parseDirectiveIfc
4957 /// ::= .ifc string1, string2
4958 /// ::= .ifnc string1, string2
4959 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4960 TheCondStack.push_back(TheCondState);
4961 TheCondState.TheCond = AsmCond::IfCond;
4963 if (TheCondState.Ignore) {
4964 eatToEndOfStatement();
4966 StringRef Str1 = parseStringToComma();
4968 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4971 StringRef Str2 = parseStringToEndOfStatement();
4973 if (parseToken(AsmToken::EndOfStatement,
4974 "unexpected token in '.ifc' directive"))
4977 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4978 TheCondState.Ignore = !TheCondState.CondMet;
4984 /// parseDirectiveIfeqs
4985 /// ::= .ifeqs string1, string2
4986 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4987 if (Lexer.isNot(AsmToken::String)) {
4989 return TokError("expected string parameter for '.ifeqs' directive");
4990 return TokError("expected string parameter for '.ifnes' directive");
4993 StringRef String1 = getTok().getStringContents();
4996 if (Lexer.isNot(AsmToken::Comma)) {
4999 "expected comma after first string for '.ifeqs' directive");
5000 return TokError("expected comma after first string for '.ifnes' directive");
5005 if (Lexer.isNot(AsmToken::String)) {
5007 return TokError("expected string parameter for '.ifeqs' directive");
5008 return TokError("expected string parameter for '.ifnes' directive");
5011 StringRef String2 = getTok().getStringContents();
5014 TheCondStack.push_back(TheCondState);
5015 TheCondState.TheCond = AsmCond::IfCond;
5016 TheCondState.CondMet = ExpectEqual == (String1 == String2);
5017 TheCondState.Ignore = !TheCondState.CondMet;
5022 /// parseDirectiveIfdef
5023 /// ::= .ifdef symbol
5024 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5026 TheCondStack.push_back(TheCondState);
5027 TheCondState.TheCond = AsmCond::IfCond;
5029 if (TheCondState.Ignore) {
5030 eatToEndOfStatement();
5032 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5033 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5036 MCSymbol *Sym = getContext().lookupSymbol(Name);
5039 TheCondState.CondMet = (Sym && !Sym->isUndefined());
5041 TheCondState.CondMet = (!Sym || Sym->isUndefined());
5042 TheCondState.Ignore = !TheCondState.CondMet;
5048 /// parseDirectiveElseIf
5049 /// ::= .elseif expression
5050 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
5051 if (TheCondState.TheCond != AsmCond::IfCond &&
5052 TheCondState.TheCond != AsmCond::ElseIfCond)
5053 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5054 " .if or an .elseif");
5055 TheCondState.TheCond = AsmCond::ElseIfCond;
5057 bool LastIgnoreState = false;
5058 if (!TheCondStack.empty())
5059 LastIgnoreState = TheCondStack.back().Ignore;
5060 if (LastIgnoreState || TheCondState.CondMet) {
5061 TheCondState.Ignore = true;
5062 eatToEndOfStatement();
5065 if (parseAbsoluteExpression(ExprValue))
5068 if (parseToken(AsmToken::EndOfStatement,
5069 "unexpected token in '.elseif' directive"))
5072 TheCondState.CondMet = ExprValue;
5073 TheCondState.Ignore = !TheCondState.CondMet;
5079 /// parseDirectiveElse
5081 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
5082 if (parseToken(AsmToken::EndOfStatement,
5083 "unexpected token in '.else' directive"))
5086 if (TheCondState.TheCond != AsmCond::IfCond &&
5087 TheCondState.TheCond != AsmCond::ElseIfCond)
5088 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5089 " an .if or an .elseif");
5090 TheCondState.TheCond = AsmCond::ElseCond;
5091 bool LastIgnoreState = false;
5092 if (!TheCondStack.empty())
5093 LastIgnoreState = TheCondStack.back().Ignore;
5094 if (LastIgnoreState || TheCondState.CondMet)
5095 TheCondState.Ignore = true;
5097 TheCondState.Ignore = false;
5102 /// parseDirectiveEnd
5104 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5105 if (parseToken(AsmToken::EndOfStatement,
5106 "unexpected token in '.end' directive"))
5109 while (Lexer.isNot(AsmToken::Eof))
5115 /// parseDirectiveError
5117 /// ::= .error [string]
5118 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5119 if (!TheCondStack.empty()) {
5120 if (TheCondStack.back().Ignore) {
5121 eatToEndOfStatement();
5127 return Error(L, ".err encountered");
5129 StringRef Message = ".error directive invoked in source file";
5130 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5131 if (Lexer.isNot(AsmToken::String))
5132 return TokError(".error argument must be a string");
5134 Message = getTok().getStringContents();
5138 return Error(L, Message);
5141 /// parseDirectiveWarning
5142 /// ::= .warning [string]
5143 bool AsmParser::parseDirectiveWarning(SMLoc L) {
5144 if (!TheCondStack.empty()) {
5145 if (TheCondStack.back().Ignore) {
5146 eatToEndOfStatement();
5151 StringRef Message = ".warning directive invoked in source file";
5153 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5154 if (Lexer.isNot(AsmToken::String))
5155 return TokError(".warning argument must be a string");
5157 Message = getTok().getStringContents();
5159 if (parseToken(AsmToken::EndOfStatement,
5160 "expected end of statement in '.warning' directive"))
5164 return Warning(L, Message);
5167 /// parseDirectiveEndIf
5169 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5170 if (parseToken(AsmToken::EndOfStatement,
5171 "unexpected token in '.endif' directive"))
5174 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5175 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5177 if (!TheCondStack.empty()) {
5178 TheCondState = TheCondStack.back();
5179 TheCondStack.pop_back();
5185 void AsmParser::initializeDirectiveKindMap() {
5186 DirectiveKindMap[".set"] = DK_SET;
5187 DirectiveKindMap[".equ"] = DK_EQU;
5188 DirectiveKindMap[".equiv"] = DK_EQUIV;
5189 DirectiveKindMap[".ascii"] = DK_ASCII;
5190 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5191 DirectiveKindMap[".string"] = DK_STRING;
5192 DirectiveKindMap[".byte"] = DK_BYTE;
5193 DirectiveKindMap[".short"] = DK_SHORT;
5194 DirectiveKindMap[".value"] = DK_VALUE;
5195 DirectiveKindMap[".2byte"] = DK_2BYTE;
5196 DirectiveKindMap[".long"] = DK_LONG;
5197 DirectiveKindMap[".int"] = DK_INT;
5198 DirectiveKindMap[".4byte"] = DK_4BYTE;
5199 DirectiveKindMap[".quad"] = DK_QUAD;
5200 DirectiveKindMap[".8byte"] = DK_8BYTE;
5201 DirectiveKindMap[".octa"] = DK_OCTA;
5202 DirectiveKindMap[".single"] = DK_SINGLE;
5203 DirectiveKindMap[".float"] = DK_FLOAT;
5204 DirectiveKindMap[".double"] = DK_DOUBLE;
5205 DirectiveKindMap[".align"] = DK_ALIGN;
5206 DirectiveKindMap[".align32"] = DK_ALIGN32;
5207 DirectiveKindMap[".balign"] = DK_BALIGN;
5208 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5209 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5210 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5211 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5212 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5213 DirectiveKindMap[".org"] = DK_ORG;
5214 DirectiveKindMap[".fill"] = DK_FILL;
5215 DirectiveKindMap[".zero"] = DK_ZERO;
5216 DirectiveKindMap[".extern"] = DK_EXTERN;
5217 DirectiveKindMap[".globl"] = DK_GLOBL;
5218 DirectiveKindMap[".global"] = DK_GLOBAL;
5219 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5220 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5221 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5222 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5223 DirectiveKindMap[".reference"] = DK_REFERENCE;
5224 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5225 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5226 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5227 DirectiveKindMap[".comm"] = DK_COMM;
5228 DirectiveKindMap[".common"] = DK_COMMON;
5229 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5230 DirectiveKindMap[".abort"] = DK_ABORT;
5231 DirectiveKindMap[".include"] = DK_INCLUDE;
5232 DirectiveKindMap[".incbin"] = DK_INCBIN;
5233 DirectiveKindMap[".code16"] = DK_CODE16;
5234 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5235 DirectiveKindMap[".rept"] = DK_REPT;
5236 DirectiveKindMap[".rep"] = DK_REPT;
5237 DirectiveKindMap[".irp"] = DK_IRP;
5238 DirectiveKindMap[".irpc"] = DK_IRPC;
5239 DirectiveKindMap[".endr"] = DK_ENDR;
5240 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5241 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5242 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5243 DirectiveKindMap[".if"] = DK_IF;
5244 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5245 DirectiveKindMap[".ifge"] = DK_IFGE;
5246 DirectiveKindMap[".ifgt"] = DK_IFGT;
5247 DirectiveKindMap[".ifle"] = DK_IFLE;
5248 DirectiveKindMap[".iflt"] = DK_IFLT;
5249 DirectiveKindMap[".ifne"] = DK_IFNE;
5250 DirectiveKindMap[".ifb"] = DK_IFB;
5251 DirectiveKindMap[".ifnb"] = DK_IFNB;
5252 DirectiveKindMap[".ifc"] = DK_IFC;
5253 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5254 DirectiveKindMap[".ifnc"] = DK_IFNC;
5255 DirectiveKindMap[".ifnes"] = DK_IFNES;
5256 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5257 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5258 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5259 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5260 DirectiveKindMap[".else"] = DK_ELSE;
5261 DirectiveKindMap[".end"] = DK_END;
5262 DirectiveKindMap[".endif"] = DK_ENDIF;
5263 DirectiveKindMap[".skip"] = DK_SKIP;
5264 DirectiveKindMap[".space"] = DK_SPACE;
5265 DirectiveKindMap[".file"] = DK_FILE;
5266 DirectiveKindMap[".line"] = DK_LINE;
5267 DirectiveKindMap[".loc"] = DK_LOC;
5268 DirectiveKindMap[".stabs"] = DK_STABS;
5269 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5270 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5271 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5272 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5273 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5274 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5275 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5276 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
5277 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5278 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5279 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5280 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5281 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5282 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5283 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5284 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5285 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5286 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5287 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5288 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5289 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5290 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5291 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5292 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5293 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5294 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5295 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5296 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5297 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5298 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5299 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5300 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5301 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5302 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5303 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5304 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
5305 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5306 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5307 DirectiveKindMap[".macro"] = DK_MACRO;
5308 DirectiveKindMap[".exitm"] = DK_EXITM;
5309 DirectiveKindMap[".endm"] = DK_ENDM;
5310 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5311 DirectiveKindMap[".purgem"] = DK_PURGEM;
5312 DirectiveKindMap[".err"] = DK_ERR;
5313 DirectiveKindMap[".error"] = DK_ERROR;
5314 DirectiveKindMap[".warning"] = DK_WARNING;
5315 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5316 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5317 DirectiveKindMap[".reloc"] = DK_RELOC;
5318 DirectiveKindMap[".dc"] = DK_DC;
5319 DirectiveKindMap[".dc.a"] = DK_DC_A;
5320 DirectiveKindMap[".dc.b"] = DK_DC_B;
5321 DirectiveKindMap[".dc.d"] = DK_DC_D;
5322 DirectiveKindMap[".dc.l"] = DK_DC_L;
5323 DirectiveKindMap[".dc.s"] = DK_DC_S;
5324 DirectiveKindMap[".dc.w"] = DK_DC_W;
5325 DirectiveKindMap[".dc.x"] = DK_DC_X;
5326 DirectiveKindMap[".dcb"] = DK_DCB;
5327 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5328 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5329 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5330 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5331 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5332 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5333 DirectiveKindMap[".ds"] = DK_DS;
5334 DirectiveKindMap[".ds.b"] = DK_DS_B;
5335 DirectiveKindMap[".ds.d"] = DK_DS_D;
5336 DirectiveKindMap[".ds.l"] = DK_DS_L;
5337 DirectiveKindMap[".ds.p"] = DK_DS_P;
5338 DirectiveKindMap[".ds.s"] = DK_DS_S;
5339 DirectiveKindMap[".ds.w"] = DK_DS_W;
5340 DirectiveKindMap[".ds.x"] = DK_DS_X;
5341 DirectiveKindMap[".print"] = DK_PRINT;
5342 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5343 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
5346 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5347 AsmToken EndToken, StartToken = getTok();
5349 unsigned NestLevel = 0;
5351 // Check whether we have reached the end of the file.
5352 if (getLexer().is(AsmToken::Eof)) {
5353 printError(DirectiveLoc, "no matching '.endr' in definition");
5357 if (Lexer.is(AsmToken::Identifier) &&
5358 (getTok().getIdentifier() == ".rep" ||
5359 getTok().getIdentifier() == ".rept" ||
5360 getTok().getIdentifier() == ".irp" ||
5361 getTok().getIdentifier() == ".irpc")) {
5365 // Otherwise, check whether we have reached the .endr.
5366 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5367 if (NestLevel == 0) {
5368 EndToken = getTok();
5370 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5371 printError(getTok().getLoc(),
5372 "unexpected token in '.endr' directive");
5380 // Otherwise, scan till the end of the statement.
5381 eatToEndOfStatement();
5384 const char *BodyStart = StartToken.getLoc().getPointer();
5385 const char *BodyEnd = EndToken.getLoc().getPointer();
5386 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5388 // We Are Anonymous.
5389 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5390 return &MacroLikeBodies.back();
5393 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5394 raw_svector_ostream &OS) {
5397 std::unique_ptr<MemoryBuffer> Instantiation =
5398 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5400 // Create the macro instantiation object and add to the current macro
5401 // instantiation stack.
5402 MacroInstantiation *MI = new MacroInstantiation(
5403 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5404 ActiveMacros.push_back(MI);
5406 // Jump to the macro instantiation and prime the lexer.
5407 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5408 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5412 /// parseDirectiveRept
5413 /// ::= .rep | .rept count
5414 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5415 const MCExpr *CountExpr;
5416 SMLoc CountLoc = getTok().getLoc();
5417 if (parseExpression(CountExpr))
5421 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
5422 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5425 if (check(Count < 0, CountLoc, "Count is negative") ||
5426 parseToken(AsmToken::EndOfStatement,
5427 "unexpected token in '" + Dir + "' directive"))
5430 // Lex the rept definition.
5431 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5435 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5436 // to hold the macro body with substitutions.
5437 SmallString<256> Buf;
5438 raw_svector_ostream OS(Buf);
5440 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5441 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5444 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5449 /// parseDirectiveIrp
5450 /// ::= .irp symbol,values
5451 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5452 MCAsmMacroParameter Parameter;
5453 MCAsmMacroArguments A;
5454 if (check(parseIdentifier(Parameter.Name),
5455 "expected identifier in '.irp' directive") ||
5456 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5457 parseMacroArguments(nullptr, A) ||
5458 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5461 // Lex the irp definition.
5462 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5466 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5467 // to hold the macro body with substitutions.
5468 SmallString<256> Buf;
5469 raw_svector_ostream OS(Buf);
5471 for (const MCAsmMacroArgument &Arg : A) {
5472 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5473 // This is undocumented, but GAS seems to support it.
5474 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5478 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5483 /// parseDirectiveIrpc
5484 /// ::= .irpc symbol,values
5485 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5486 MCAsmMacroParameter Parameter;
5487 MCAsmMacroArguments A;
5489 if (check(parseIdentifier(Parameter.Name),
5490 "expected identifier in '.irpc' directive") ||
5491 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5492 parseMacroArguments(nullptr, A))
5495 if (A.size() != 1 || A.front().size() != 1)
5496 return TokError("unexpected token in '.irpc' directive");
5498 // Eat the end of statement.
5499 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5502 // Lex the irpc definition.
5503 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5507 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5508 // to hold the macro body with substitutions.
5509 SmallString<256> Buf;
5510 raw_svector_ostream OS(Buf);
5512 StringRef Values = A.front().front().getString();
5513 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5514 MCAsmMacroArgument Arg;
5515 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5517 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5518 // This is undocumented, but GAS seems to support it.
5519 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5523 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5528 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5529 if (ActiveMacros.empty())
5530 return TokError("unmatched '.endr' directive");
5532 // The only .repl that should get here are the ones created by
5533 // instantiateMacroLikeBody.
5534 assert(getLexer().is(AsmToken::EndOfStatement));
5540 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5542 const MCExpr *Value;
5543 SMLoc ExprLoc = getLexer().getLoc();
5544 if (parseExpression(Value))
5546 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5548 return Error(ExprLoc, "unexpected expression in _emit");
5549 uint64_t IntValue = MCE->getValue();
5550 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5551 return Error(ExprLoc, "literal value out of range for directive");
5553 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5557 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5558 const MCExpr *Value;
5559 SMLoc ExprLoc = getLexer().getLoc();
5560 if (parseExpression(Value))
5562 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5564 return Error(ExprLoc, "unexpected expression in align");
5565 uint64_t IntValue = MCE->getValue();
5566 if (!isPowerOf2_64(IntValue))
5567 return Error(ExprLoc, "literal value not a power of two greater then zero");
5569 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5573 bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5574 const AsmToken StrTok = getTok();
5576 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5577 return Error(DirectiveLoc, "expected double quoted string after .print");
5578 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5580 llvm::outs() << StrTok.getStringContents() << '\n';
5584 bool AsmParser::parseDirectiveAddrsig() {
5585 getStreamer().EmitAddrsig();
5589 bool AsmParser::parseDirectiveAddrsigSym() {
5591 if (check(parseIdentifier(Name),
5592 "expected identifier in '.addrsig_sym' directive"))
5594 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5595 getStreamer().EmitAddrsigSym(Sym);
5599 // We are comparing pointers, but the pointers are relative to a single string.
5600 // Thus, this should always be deterministic.
5601 static int rewritesSort(const AsmRewrite *AsmRewriteA,
5602 const AsmRewrite *AsmRewriteB) {
5603 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5605 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5608 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5609 // rewrite to the same location. Make sure the SizeDirective rewrite is
5610 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5611 // ensures the sort algorithm is stable.
5612 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5613 AsmRewritePrecedence[AsmRewriteB->Kind])
5616 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5617 AsmRewritePrecedence[AsmRewriteB->Kind])
5619 llvm_unreachable("Unstable rewrite sort.");
5622 bool AsmParser::parseMSInlineAsm(
5623 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5624 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5625 SmallVectorImpl<std::string> &Constraints,
5626 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5627 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5628 SmallVector<void *, 4> InputDecls;
5629 SmallVector<void *, 4> OutputDecls;
5630 SmallVector<bool, 4> InputDeclsAddressOf;
5631 SmallVector<bool, 4> OutputDeclsAddressOf;
5632 SmallVector<std::string, 4> InputConstraints;
5633 SmallVector<std::string, 4> OutputConstraints;
5634 SmallVector<unsigned, 4> ClobberRegs;
5636 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5641 // While we have input, parse each statement.
5642 unsigned InputIdx = 0;
5643 unsigned OutputIdx = 0;
5644 while (getLexer().isNot(AsmToken::Eof)) {
5645 // Parse curly braces marking block start/end
5646 if (parseCurlyBlockScope(AsmStrRewrites))
5649 ParseStatementInfo Info(&AsmStrRewrites);
5650 bool StatementErr = parseStatement(Info, &SI);
5652 if (StatementErr || Info.ParseError) {
5653 // Emit pending errors if any exist.
5654 printPendingErrors();
5658 // No pending error should exist here.
5659 assert(!hasPendingError() && "unexpected error from parseStatement");
5661 if (Info.Opcode == ~0U)
5664 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5666 // Build the list of clobbers, outputs and inputs.
5667 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5668 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5671 if (Operand.isImm())
5674 // Register operand.
5675 if (Operand.isReg() && !Operand.needAddressOf() &&
5676 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5677 unsigned NumDefs = Desc.getNumDefs();
5679 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5680 ClobberRegs.push_back(Operand.getReg());
5684 // Expr/Input or Output.
5685 StringRef SymName = Operand.getSymName();
5686 if (SymName.empty())
5689 void *OpDecl = Operand.getOpDecl();
5693 bool isOutput = (i == 1) && Desc.mayStore();
5694 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5697 OutputDecls.push_back(OpDecl);
5698 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5699 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5700 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5702 InputDecls.push_back(OpDecl);
5703 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5704 InputConstraints.push_back(Operand.getConstraint().str());
5705 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5709 // Consider implicit defs to be clobbers. Think of cpuid and push.
5710 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5711 Desc.getNumImplicitDefs());
5712 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5715 // Set the number of Outputs and Inputs.
5716 NumOutputs = OutputDecls.size();
5717 NumInputs = InputDecls.size();
5719 // Set the unique clobbers.
5720 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5721 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5723 Clobbers.assign(ClobberRegs.size(), std::string());
5724 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5725 raw_string_ostream OS(Clobbers[I]);
5726 IP->printRegName(OS, ClobberRegs[I]);
5729 // Merge the various outputs and inputs. Output are expected first.
5730 if (NumOutputs || NumInputs) {
5731 unsigned NumExprs = NumOutputs + NumInputs;
5732 OpDecls.resize(NumExprs);
5733 Constraints.resize(NumExprs);
5734 for (unsigned i = 0; i < NumOutputs; ++i) {
5735 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5736 Constraints[i] = OutputConstraints[i];
5738 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5739 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5740 Constraints[j] = InputConstraints[i];
5744 // Build the IR assembly string.
5745 std::string AsmStringIR;
5746 raw_string_ostream OS(AsmStringIR);
5747 StringRef ASMString =
5748 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5749 const char *AsmStart = ASMString.begin();
5750 const char *AsmEnd = ASMString.end();
5751 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5752 for (const AsmRewrite &AR : AsmStrRewrites) {
5753 AsmRewriteKind Kind = AR.Kind;
5755 const char *Loc = AR.Loc.getPointer();
5756 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5758 // Emit everything up to the immediate/expression.
5759 if (unsigned Len = Loc - AsmStart)
5760 OS << StringRef(AsmStart, Len);
5762 // Skip the original expression.
5763 if (Kind == AOK_Skip) {
5764 AsmStart = Loc + AR.Len;
5768 unsigned AdditionalSkip = 0;
5769 // Rewrite expressions in $N notation.
5774 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5775 if (AR.IntelExp.NeedBracs)
5777 if (AR.IntelExp.hasBaseReg())
5778 OS << AR.IntelExp.BaseReg;
5779 if (AR.IntelExp.hasIndexReg())
5780 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5781 << AR.IntelExp.IndexReg;
5782 if (AR.IntelExp.Scale > 1)
5783 OS << " * $$" << AR.IntelExp.Scale;
5784 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5785 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5786 if (AR.IntelExp.NeedBracs)
5790 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5793 OS << '$' << InputIdx++;
5796 OS << '$' << OutputIdx++;
5798 case AOK_SizeDirective:
5801 case 8: OS << "byte ptr "; break;
5802 case 16: OS << "word ptr "; break;
5803 case 32: OS << "dword ptr "; break;
5804 case 64: OS << "qword ptr "; break;
5805 case 80: OS << "xword ptr "; break;
5806 case 128: OS << "xmmword ptr "; break;
5807 case 256: OS << "ymmword ptr "; break;
5814 // MS alignment directives are measured in bytes. If the native assembler
5815 // measures alignment in bytes, we can pass it straight through.
5817 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5820 // Alignment is in log2 form, so print that instead and skip the original
5822 unsigned Val = AR.Val;
5824 assert(Val < 10 && "Expected alignment less then 2^10.");
5825 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5831 case AOK_EndOfStatement:
5836 // Skip the original expression.
5837 AsmStart = Loc + AR.Len + AdditionalSkip;
5840 // Emit the remainder of the asm string.
5841 if (AsmStart != AsmEnd)
5842 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5844 AsmString = OS.str();
5849 namespace MCParserUtils {
5851 /// Returns whether the given symbol is used anywhere in the given expression,
5852 /// or subexpressions.
5853 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5854 switch (Value->getKind()) {
5855 case MCExpr::Binary: {
5856 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5857 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5858 isSymbolUsedInExpression(Sym, BE->getRHS());
5860 case MCExpr::Target:
5861 case MCExpr::Constant:
5863 case MCExpr::SymbolRef: {
5865 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5867 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5871 return isSymbolUsedInExpression(
5872 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5875 llvm_unreachable("Unknown expr kind!");
5878 bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5879 MCAsmParser &Parser, MCSymbol *&Sym,
5880 const MCExpr *&Value) {
5882 // FIXME: Use better location, we should use proper tokens.
5883 SMLoc EqualLoc = Parser.getTok().getLoc();
5884 if (Parser.parseExpression(Value))
5885 return Parser.TokError("missing expression");
5887 // Note: we don't count b as used in "a = b". This is to allow
5891 if (Parser.parseToken(AsmToken::EndOfStatement))
5894 // Validate that the LHS is allowed to be a variable (either it has not been
5895 // used as a symbol, or it is an absolute symbol).
5896 Sym = Parser.getContext().lookupSymbol(Name);
5898 // Diagnose assignment to a label.
5900 // FIXME: Diagnostics. Note the location of the definition as a label.
5901 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5902 if (isSymbolUsedInExpression(Sym, Value))
5903 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5904 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5906 ; // Allow redefinitions of undefined symbols only used in directives.
5907 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5908 ; // Allow redefinitions of variables that haven't yet been used.
5909 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5910 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5911 else if (!Sym->isVariable())
5912 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5913 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5914 return Parser.Error(EqualLoc,
5915 "invalid reassignment of non-absolute variable '" +
5917 } else if (Name == ".") {
5918 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5921 Sym = Parser.getContext().getOrCreateSymbol(Name);
5923 Sym->setRedefinable(allow_redef);
5928 } // end namespace MCParserUtils
5929 } // end namespace llvm
5931 /// Create an MCAsmParser instance.
5932 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5933 MCStreamer &Out, const MCAsmInfo &MAI,
5935 return new AsmParser(SM, C, Out, MAI, CB);